Esempio n. 1
0
        private void AddGroupMemberAttributes(RockContext rockContext = null)
        {
            // Group
            if (RoleRequests.Count > 0 && rptGroupRoleAttributes.Items.Count > 0)
            {
                if (rockContext == null)
                {
                    rockContext = new RockContext();
                }
                var viewStateAttributes = new List <Dictionary <string, string> >();
                var RepeaterIndex       = 0;
                foreach (var roleRequest in RoleRequests)
                {
                    var hdnGroupId   = (( HiddenField )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("hdnGroupId")));
                    var phAttributes = (( PlaceHolder )(rptGroupRoleAttributes.Items[RepeaterIndex].FindControl("phAttributes")));
                    hdnGroupId.Value = roleRequest.GroupId.ToString();

                    var group = new GroupService(rockContext).Get(hdnGroupId.Value.AsInteger());
                    if (group != null)
                    {
                        // Group Attributes
                        var formKeys = GetAttributeValues("FormKeys");
                        var urlKeys  = GetAttributeValues("UrlKeys");

                        AttributeService attributeService = new AttributeService(rockContext);

                        string groupQualifierValue     = group.Id.ToString();
                        string groupTypeQualifierValue = group.GroupTypeId.ToString();

                        // Make a fake group member so we can load some attributes.
                        GroupMember groupMember = new GroupMember();
                        groupMember.Group   = group;
                        groupMember.GroupId = group.Id;
                        groupMember.LoadAttributes();

                        // Store URL Keys into the ViewState
                        var viewStateAttribute = new Dictionary <string, string>();
                        foreach (string urlKey in urlKeys)
                        {
                            if (roleRequest.Attributes != null && roleRequest.Attributes.ContainsKey(urlKey) && !string.IsNullOrEmpty(roleRequest.Attributes[urlKey]) && groupMember.Attributes.ContainsKey(urlKey))
                            {
                                groupMember.SetAttributeValue(urlKey, roleRequest.Attributes[urlKey]);
                                viewStateAttribute.Add(urlKey, roleRequest.Attributes[urlKey]);
                            }
                        }
                        viewStateAttributes.Add(viewStateAttribute);

                        Helper.AddDisplayControls(groupMember, phAttributes, groupMember.Attributes.Where(a => !urlKeys.Contains(a.Key)).Select(a => a.Key).ToList(), true, false);
                        Helper.AddEditControls("", formKeys, groupMember, phAttributes, tbLastName.ValidationGroup, false, new List <String>());
                    }
                    RepeaterIndex++;
                }
                ViewState.Add("SelectedAttributes", viewStateAttributes);
                SaveViewState();
            }
        }
        private void SaveGroupMember(RockContext rockContext, GroupMember groupMember, Panel pnlWell, List <AttributeCache> AttributeList, TextBox notes)
        {
            var changes = new List <string>();

            foreach (var attribute in AttributeList)
            {
                if (Person != null && groupMember.Group.IsAuthorized(Authorization.EDIT, CurrentPerson))
                {
                    groupMember.Note = notes.Text;
                    rockContext.SaveChanges();

                    Control attributeControl = pnlWell.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                    if (attributeControl != null)
                    {
                        string newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                        groupMember.SetAttributeValue(attribute.Key, newValue);

                        groupMember.SaveAttributeValues();
                    }
                }
            }
            ShowEdit(groupMember.Id);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                Guid checkinGroupAttributeGuid = GetAttributeValue(action, "CheckinGroupAttribute").AsGuid();
                if (checkinGroupAttributeGuid == Guid.Empty)
                {
                    throw new Exception("CheckInGroupAttribute not set. Set attribute to continue.");
                }
                string checkinGroupAttributeKey = AttributeCache.Read(checkinGroupAttributeGuid, rockContext).Key;

                string sessionAttributeKey = GetAttributeValue(action, "SessionAttributeKey");

                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = RockDateTime.Now;

                bool reuseCodeForFamily = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;

                AttendanceCodeService attendanceCodeService = new AttendanceCodeService(rockContext);
                AttendanceService     attendanceService     = new AttendanceService(rockContext);
                GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
                PersonAliasService    personAliasService    = new PersonAliasService(rockContext);
                GroupService          groupService          = new GroupService(rockContext);

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    foreach (var person in family.GetPeople(true))
                    {
                        if (reuseCodeForFamily && attendanceCode != null)
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode      = AttendanceCodeService.GetNew(securityCodeLength);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GetGroupTypes(true))
                        {
                            foreach (var group in groupType.GetGroups(true))
                            {
                                var referenceGroupGuid = group.Group.GetAttributeValue(checkinGroupAttributeKey).AsGuid();
                                var referenceGroup     = groupService.Get(referenceGroupGuid);
                                if (referenceGroup == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                GroupMember groupMember = groupMemberService.GetByGroupIdAndPersonId(referenceGroup.Id, person.Person.Id).FirstOrDefault();
                                if (groupMember == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                groupMember.LoadAttributes();
                                int sessions = groupMember.GetAttributeValue(sessionAttributeKey).AsInteger();

                                foreach (var location in group.GetLocations(true))
                                {
                                    foreach (var schedule in location.GetSchedules(true))
                                    {
                                        if (sessions == 0)
                                        {
                                            continue;
                                        }

                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get(startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id);
                                        if (attendance == null)
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                            if (primaryAlias != null)
                                            {
                                                attendance                   = rockContext.Attendances.Create();
                                                attendance.LocationId        = location.Location.Id;
                                                attendance.CampusId          = location.CampusId;
                                                attendance.ScheduleId        = schedule.Schedule.Id;
                                                attendance.GroupId           = group.Group.Id;
                                                attendance.PersonAlias       = primaryAlias;
                                                attendance.PersonAliasId     = primaryAlias.Id;
                                                attendance.DeviceId          = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendanceService.Add(attendance);
                                            }

                                            //decrement sessions and save
                                            sessions--;
                                            groupMember.SetAttributeValue(sessionAttributeKey, sessions);
                                            groupMember.SaveAttributeValues();
                                        }
                                        else
                                        {
                                            foreach (var cPerson in checkInState.CheckIn.Families.SelectMany(f => f.People))
                                            {
                                                cPerson.Selected = false;
                                                cPerson.GroupTypes.ForEach(gt => gt.Selected = false);
                                            }
                                            return(true);
                                        }

                                        attendance.AttendanceCodeId = attendanceCode.Id;
                                        attendance.StartDateTime    = startDateTime;
                                        attendance.EndDateTime      = null;
                                        attendance.DidAttend        = true;

                                        KioskLocationAttendance.AddAttendance(attendance);
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.SaveChanges();
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Handles the Click event of the lbConnect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbConnect_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );
                var connectionActivityTypeService = new ConnectionActivityTypeService( rockContext );
                var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext );
                var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() );

                if ( connectionRequest != null &&
                    connectionRequest.PersonAlias != null &&
                    connectionRequest.ConnectionOpportunity != null )
                {
                    bool okToConnect = true;

                    GroupMember groupMember = null;

                    // Only do group member placement if the request has an assigned placement group, role, and status
                    if ( connectionRequest.AssignedGroupId.HasValue &&
                        connectionRequest.AssignedGroupMemberRoleId.HasValue &&
                        connectionRequest.AssignedGroupMemberStatus.HasValue )
                    {
                        var group = new GroupService( rockContext ).Get( connectionRequest.AssignedGroupId.Value );
                        if ( group != null )
                        {
                            // Only attempt the add if person does not already exist in group with same role
                            groupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( connectionRequest.AssignedGroupId.Value,
                                connectionRequest.PersonAlias.PersonId, connectionRequest.AssignedGroupMemberRoleId.Value );
                            if ( groupMember == null )
                            {
                                groupMember = new GroupMember();
                                groupMember.PersonId = connectionRequest.PersonAlias.PersonId;
                                groupMember.GroupId = connectionRequest.AssignedGroupId.Value;
                                groupMember.GroupRoleId = connectionRequest.AssignedGroupMemberRoleId.Value;
                                groupMember.GroupMemberStatus = connectionRequest.AssignedGroupMemberStatus.Value;

                                foreach ( ListItem item in cblManualRequirements.Items )
                                {
                                    if ( !item.Selected && group.MustMeetRequirementsToAddMember.HasValue && group.MustMeetRequirementsToAddMember.Value )
                                    {
                                        okToConnect = false;
                                        nbRequirementsErrors.Text = "Group Requirements have not been met. Please verify all of the requirements.";
                                        nbRequirementsErrors.Visible = true;
                                        break;
                                    }
                                    else
                                    {
                                        groupMember.GroupMemberRequirements.Add( new GroupMemberRequirement
                                        {
                                            GroupRequirementId = item.Value.AsInteger(),
                                            RequirementMetDateTime = RockDateTime.Now,
                                            LastRequirementCheckDateTime = RockDateTime.Now
                                        } );
                                    }
                                }

                                if ( okToConnect )
                                {
                                    groupMemberService.Add( groupMember );
                                    if ( !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                                    {
                                        var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( connectionRequest.AssignedGroupMemberAttributeValues );
                                        if ( savedValues != null )
                                        {
                                            groupMember.LoadAttributes();
                                            foreach ( var item in savedValues )
                                            {
                                                groupMember.SetAttributeValue( item.Key, item.Value );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if ( okToConnect )
                    {
                        // ... but always record the connection activity and change the state to connected.
                        var guid = Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid();
                        var connectedActivityId = connectionActivityTypeService.Queryable()
                            .Where( t => t.Guid == guid )
                            .Select( t => t.Id )
                            .FirstOrDefault();
                        if ( connectedActivityId > 0 )
                        {
                            var connectionRequestActivity = new ConnectionRequestActivity();
                            connectionRequestActivity.ConnectionRequestId = connectionRequest.Id;
                            connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId;
                            connectionRequestActivity.ConnectionActivityTypeId = connectedActivityId;
                            connectionRequestActivity.ConnectorPersonAliasId = CurrentPersonAliasId;
                            connectionRequestActivityService.Add( connectionRequestActivity );
                        }

                        connectionRequest.ConnectionState = ConnectionState.Connected;

                        rockContext.SaveChanges();
                        if ( groupMember != null && !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                        {
                            groupMember.SaveAttributeValues( rockContext );
                        }

                        ShowDetail( connectionRequest.Id, connectionRequest.ConnectionOpportunityId );
                    }
                }
            }
        }
        private void BuildGroupMemberAttributes( int? groupId, int? groupMemberRoleId, GroupMemberStatus? groupMemberStatus, bool setValues )
        {
            phGroupMemberAttributes.Controls.Clear();
            phGroupMemberAttributesView.Controls.Clear();

            if ( groupId.HasValue && groupMemberRoleId.HasValue && groupMemberStatus != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    var role = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId.Value );
                    if ( group != null && role != null )
                    {
                        var groupMember = new GroupMember();
                        groupMember.Group = group;
                        groupMember.GroupId = group.Id;
                        groupMember.GroupRole = role;
                        groupMember.GroupRoleId = role.Id;
                        groupMember.GroupMemberStatus = groupMemberStatus.Value;

                        groupMember.LoadAttributes();

                        if ( setValues && !string.IsNullOrWhiteSpace( hfGroupMemberAttributeValues.Value ) )
                        {
                            var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( hfGroupMemberAttributeValues.Value );
                            if ( savedValues != null )
                            {
                                foreach( var item in savedValues )
                                {
                                    groupMember.SetAttributeValue( item.Key, item.Value );
                                }
                            }
                        }

                        Rock.Attribute.Helper.AddEditControls( groupMember, phGroupMemberAttributes, setValues, BlockValidationGroup, 2 );
                        Rock.Attribute.Helper.AddDisplayControls( groupMember, phGroupMemberAttributesView, null, false, false );
                    }
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Handles the Click event of the btnMoveGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnMoveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var groupMember        = groupMemberService.Get(hfGroupMemberId.Value.AsInteger());

            groupMember.LoadAttributes();
            int destGroupId = gpMoveGroupMember.SelectedValue.AsInteger();
            var destGroup   = new GroupService(rockContext).Get(destGroupId);

            var destGroupMember = groupMemberService.Queryable().Where(a =>
                                                                       a.GroupId == destGroupId &&
                                                                       a.PersonId == groupMember.PersonId &&
                                                                       a.GroupRoleId == grpMoveGroupMember.GroupRoleId).FirstOrDefault();

            if (destGroupMember != null)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("{0} is already in {1}", groupMember.Person, destGroupMember.Group);
                return;
            }

            if (!grpMoveGroupMember.GroupRoleId.HasValue)
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Please select a Group Role");
                return;
            }

            string canDeleteWarning;

            if (!groupMemberService.CanDelete(groupMember, out canDeleteWarning))
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text    = string.Format("Unable to remove {0} from {1}: {2}", groupMember.Person, groupMember.Group, canDeleteWarning);
                return;
            }

            destGroupMember             = new GroupMember();
            destGroupMember.GroupId     = destGroupId;
            destGroupMember.GroupRoleId = grpMoveGroupMember.GroupRoleId.Value;
            destGroupMember.PersonId    = groupMember.PersonId;
            destGroupMember.LoadAttributes();

            foreach (var attribute in groupMember.Attributes)
            {
                if (destGroupMember.Attributes.Any(a => a.Key == attribute.Key && a.Value.FieldTypeId == attribute.Value.FieldTypeId))
                {
                    destGroupMember.SetAttributeValue(attribute.Key, groupMember.GetAttributeValue(attribute.Key));
                }
            }

            // Un-link any registrant records that point to this group member.
            foreach (var registrant in new RegistrationRegistrantService(rockContext).Queryable()
                     .Where(r => r.GroupMemberId == groupMember.Id))
            {
                registrant.GroupMemberId = null;
            }

            rockContext.WrapTransaction(() =>
            {
                groupMemberService.Add(destGroupMember);
                rockContext.SaveChanges();
                destGroupMember.SaveAttributeValues(rockContext);

                // move any Note records that were associated with the old groupMember to the new groupMember record
                if (cbMoveGroupMemberMoveNotes.Checked)
                {
                    destGroupMember.Note        = groupMember.Note;
                    int groupMemberEntityTypeId = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
                    var noteService             = new NoteService(rockContext);
                    var groupMemberNotes        = noteService.Queryable().Where(a => a.NoteType.EntityTypeId == groupMemberEntityTypeId && a.EntityId == groupMember.Id);
                    foreach (var note in groupMemberNotes)
                    {
                        note.EntityId = destGroupMember.Id;
                    }

                    rockContext.SaveChanges();
                }

                groupMemberService.Delete(groupMember);
                rockContext.SaveChanges();

                destGroupMember.CalculateRequirements(rockContext, true);
            });

            var queryString = new Dictionary <string, string>();

            queryString.Add("GroupMemberId", destGroupMember.Id.ToString());
            this.NavigateToPage(this.RockPage.Guid, queryString);
        }
        protected void btnRunSync_Click(object sender, EventArgs e)
        {
            var kvList = GetAttributeValue("ColumnMapping").ToKeyValuePairList();

            RockContext   rockContext   = new RockContext();
            GroupService  groupService  = new GroupService(rockContext);
            PersonService personService = new PersonService(rockContext);

            Group group = groupService.Get(GetAttributeValue("Group").AsGuid());

            foreach (GroupMember gm in group.Members)
            {
                gm.LoadAttributes();
                litSuccess.Text += "Clearing attributes for " + gm.Person + "<br />";
                foreach (var kvp in kvList)
                {
                    gm.SetAttributeValue(kvp.Value.ToString(), "");
                }

                gm.SaveAttributeValues();
            }

            GoogleCredential credential = GoogleCredential.FromJson(GetAttributeValue("ServiceAccountKey"));

            credential = credential.CreateScoped(Scopes);

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = BlockName
            });

            // Define request parameters.
            String spreadsheetId = GetAttributeValue("SpreadsheetId");

            var allPersonIds = new ValueRange()
            {
                Values = new List <IList <object> >()
            };

            litErrors.Text         = "";
            litErrorsSummary.Text  = "";
            litOutput.Text         = "";
            litOutputSummary.Text  = "";
            litSuccess.Text        = "";
            litSuccessSummary.Text = "";
            int errorCount   = 0;
            int successCount = 0;


            foreach (String sheetName in GetAttributeValue("SheetName").SplitDelimitedValues(false))
            {
                if (string.IsNullOrWhiteSpace(sheetName))
                {
                    continue;
                }

                SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, "'" + sheetName + "'!" + GetAttributeValue("StartColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("EndColumn"));
                IList <IList <Object> > data = request.Execute().Values;


                // Prints the names and majors of students in a sample spreadsheet:
                // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
                if (data != null)
                {
                    var personIds = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var phoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent1Names = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent1PhoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent2Names = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    var parent2PhoneNumbers = new ValueRange()
                    {
                        Values = new List <IList <object> >()
                    };
                    for (var i = 0; i < data.Count; i++)
                    {
                        if (data[i].Count == 0)
                        {
                            continue;
                        }
                        try
                        {
                            string firstName = data[i][GetAttributeValue("FirstNameColumn").AsInteger()].ToString();
                            string lastName  = data[i][GetAttributeValue("LastNameColumn").AsInteger()].ToString();
                            string grade     = data[i][GetAttributeValue("GradeColumn").AsInteger()].ToString();
                            string role      = data[i][GetAttributeValue("RoleColumn").AsInteger()].ToString();
                            string campus    = "";
                            if (!string.IsNullOrEmpty(GetAttributeValue("CampusColumn")))
                            {
                                campus = data[i][GetAttributeValue("CampusColumn").AsInteger()].ToString();
                            }
                            string campusShortCode = "";
                            if (!string.IsNullOrEmpty(GetAttributeValue("Campus")))
                            {
                                campusShortCode = CampusCache.Read(GetAttributeValue("Campus").AsGuid()).ShortCode;
                                if (campusShortCode == "920")
                                {
                                    campusShortCode = "BL";
                                }
                            }


                            string personId           = "";
                            string phone              = "";
                            string parent1Name        = "";
                            string parent1PhoneNumber = "";
                            string parent2Name        = "";
                            string parent2PhoneNumber = "";
                            if (GetAttributeValue("PersonIdColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("PersonIdColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    if (System.Text.RegularExpressions.Regex.IsMatch(data[i][columnIndex].ToString(), "^\\d+$"))
                                    {
                                        personId = data[i][columnIndex].ToString();
                                    }
                                }
                            }

                            if (GetAttributeValue("PersonPhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("PersonPhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    phone = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent1Column") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent1Column").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent1Name = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent1PhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent1PhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent1PhoneNumber = data[i][columnIndex].ToString();
                                }
                            }
                            if (GetAttributeValue("Parent2Column") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent2Column").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent2Name = data[i][columnIndex].ToString();
                                }
                            }

                            if (GetAttributeValue("Parent2PhoneColumn") != "")
                            {
                                int columnIndex = ColumnNumber(GetAttributeValue("Parent2PhoneColumn").ToString()) - ColumnNumber(GetAttributeValue("StartColumn").ToString());

                                if (data[i].Count >= columnIndex + 1)
                                {
                                    parent2PhoneNumber = data[i][columnIndex].ToString();
                                }
                            }

                            // If the role or the campus short code don't match, just skip this
                            if ((GetAttributeValue("Role").ToLower() == "other" && role.ToLower() != "student" || role.ToLower() == GetAttributeValue("Role").ToLower()) && (string.IsNullOrEmpty(campus) || campus == campusShortCode) && firstName != "" && lastName != "")
                            {
                                var members = group.Members.Where(m => (m.Person.NickName.ToLower() == firstName.ToLower().Trim(' ') || m.Person.FirstName.ToLower() == firstName.ToLower().Trim(' ')) && (m.Person.LastName.ToLower() == lastName.ToLower().Trim(' ') || m.Person.LastName.ToLower() == lastName.ToLower().Replace("jr.", "").Trim(' ')));

                                if (members.Count() > 1)
                                {
                                    litErrors.Text += "Matched more than one matching Group Member: " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                    errorCount++;
                                }
                                else if (members.Count() == 1)
                                {
                                    GroupMember member = members.FirstOrDefault();
                                    if (allPersonIds.Values.Select(v => v[0]).Contains(member.PersonId))
                                    {
                                        litErrors.Text += "Duplicate person " + firstName + " " + lastName + " (Sheet: \"" + sheetName + "\" PersonId: " + member.PersonId + " Row: " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + " Duplicate Row: " + (personIds.Values.Select(v => v[0]).ToList().IndexOf(member.PersonId) + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                        errorCount++;
                                    }
                                    else
                                    {
                                        personId = member.PersonId.ToString();
                                        phone    = member.Person.PhoneNumbers.Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault();

                                        var parent1 = member.Person.GetFamilyMembers().Where(fm => fm.GroupRole.Guid.ToString() == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT).Select(fm => fm.Person).FirstOrDefault();

                                        if (parent1 != null)
                                        {
                                            parent1Name        = parent1.NickName + " " + parent1.LastName;
                                            parent1PhoneNumber = personService.Get(parent1.Id).PhoneNumbers.Where(pn => pn.NumberTypeValueId == 12).Select(pn => pn.NumberFormatted).FirstOrDefault();
                                            var parent2 = member.Person.GetFamilyMembers().Where(fm => fm.GroupRole.Guid.ToString() == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT && fm.PersonId != parent1.Id).Select(fm => fm.Person).FirstOrDefault();

                                            if (parent2 != null)
                                            {
                                                parent2Name        = parent2.NickName + " " + parent2.LastName;
                                                parent2PhoneNumber = personService.Get(parent2.Id).PhoneNumbers.Where(pn => pn.NumberTypeValueId == 12).Select(pn => pn.NumberFormatted).FirstOrDefault();
                                            }
                                        }

                                        member.LoadAttributes();

                                        foreach (var kvp in kvList)
                                        {
                                            string value     = "";
                                            var    separator = "";
                                            foreach (var index in kvp.Key.ToString().Replace("%2C", ",").Split(','))
                                            {
                                                if (data[i].Count >= index.AsInteger() + 1 && !string.IsNullOrWhiteSpace(data[i][index.AsInteger()].ToString()))
                                                {
                                                    value    += separator + data[i][index.AsInteger()].ToString();
                                                    separator = "-";
                                                }
                                            }
                                            member.SetAttributeValue(kvp.Value.ToString(), value);
                                        }
                                        member.SaveAttributeValues();

                                        litSuccess.Text += "Updated " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                        successCount++;
                                    }
                                }
                                else
                                {
                                    litErrors.Text += "Unable to find Group Member for " + firstName + " " + lastName + " (Sheet \"" + sheetName + "\" - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + ")<br />";
                                    errorCount++;
                                }
                            }

                            personIds.Values.Add(new List <object>()
                            {
                                personId
                            });
                            allPersonIds.Values.Add(new List <object>()
                            {
                                personId
                            });
                            phoneNumbers.Values.Add(new List <object>()
                            {
                                phone
                            });
                            parent1Names.Values.Add(new List <object>()
                            {
                                parent1Name
                            });
                            parent1PhoneNumbers.Values.Add(new List <object>()
                            {
                                parent1PhoneNumber
                            });
                            parent2Names.Values.Add(new List <object>()
                            {
                                parent2Name
                            });
                            parent2PhoneNumbers.Values.Add(new List <object>()
                            {
                                parent2PhoneNumber
                            });
                        }
                        catch (Exception exception)
                        {
                            litErrors.Text += "Error: " + exception.Message + " - Row " + (i + GetAttributeValue("FirstDataRow").AsInteger()) + "<br />";
                        }
                    }

                    if (GetAttributeValue("PersonIdColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(personIds, spreadsheetId, sheetName + "!" + GetAttributeValue("PersonIdColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("PersonIdColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += (litOutput.Text.Length > 0 ? "<br />" : "") + "Updated " + (personIds.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Person Id's on Sheet " + sheetName + " in Column " + GetAttributeValue("PersonIdColumn");
                    }
                    if (GetAttributeValue("PersonPhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(phoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("PersonPhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("PersonPhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (phoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("PersonPhoneColumn");
                    }
                    if (GetAttributeValue("Parent1Column") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent1Names, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent1Column") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent1Column"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent1Names.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 1 Names on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent1Column");
                    }
                    if (GetAttributeValue("Parent1PhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent1PhoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent1PhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent1PhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent1PhoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 1 Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent1PhoneColumn");
                    }
                    if (GetAttributeValue("Parent2Column") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent2Names, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent2Column") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent2Column"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent2Names.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 2 Names on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent2Column");
                    }
                    if (GetAttributeValue("Parent2PhoneColumn") != "")
                    {
                        var updateRequest = service.Spreadsheets.Values.Update(parent2PhoneNumbers, spreadsheetId, sheetName + "!" + GetAttributeValue("Parent2PhoneColumn") + GetAttributeValue("FirstDataRow") + ":" + GetAttributeValue("Parent2PhoneColumn"));
                        updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
                        var result = updateRequest.Execute();

                        litOutput.Text += "<br />Updated " + (parent2PhoneNumbers.Values.Select(v => v[0]).Where(v => v != null && v.ToString() != "").Count()) + " Parent 2 Phone Numbers on Sheet " + sheetName + " in Column " + GetAttributeValue("Parent2PhoneColumn");
                    }
                }
            }

            var missedPeople = group.Members.Where(gm => !allPersonIds.Values.Select(v => v[0]).Contains(gm.PersonId.ToString()) && gm.GroupMemberStatus == GroupMemberStatus.Active);

            foreach (var person in missedPeople)
            {
                litErrors.Text += "Unable to find entry in Google Sheet for " + person.Person + "<br />";
                errorCount++;
            }

            litErrorsSummary.Text  += errorCount + " Record Errors<br />";
            litSuccessSummary.Text += successCount + " Records Updated";
            litOutputSummary.Text   = "General Information";

            mdShowOutput.Show();
        }
        protected void btnMoveRegistration_Click( object sender, EventArgs e )
        {
            // set the new registration id
            using ( var rockContext = new RockContext() )
            {
                var registrationService = new RegistrationService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );

                var registration = registrationService.Get( Registration.Id );
                registration.RegistrationInstanceId = ddlNewRegistrationInstance.SelectedValue.AsInteger();

                // Move registrants to new group
                int? groupId = ddlMoveGroup.SelectedValueAsInt();
                if ( groupId.HasValue )
                {
                    registration.GroupId = groupId;
                    rockContext.SaveChanges();

                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        int? groupRoleId = null;
                        var template = registration.RegistrationInstance.RegistrationTemplate;
                        if ( group.GroupTypeId == template.GroupTypeId && template.GroupMemberRoleId.HasValue )
                        {
                            groupRoleId = template.GroupMemberRoleId.Value;
                        }
                        if ( !groupRoleId.HasValue )
                        {
                            groupRoleId = group.GroupType.DefaultGroupRoleId;
                        }
                        if ( !groupRoleId.HasValue )
                        {
                            groupRoleId = group.GroupType.Roles.OrderBy( r => r.Order ).Select( r => r.Id ).FirstOrDefault();
                        }

                        if ( groupRoleId.HasValue )
                        {
                            foreach ( var registrant in registration.Registrants.Where( r => r.PersonAlias != null ) )
                            {
                                var newGroupMembers = groupMemberService.GetByGroupIdAndPersonId( groupId.Value, registrant.PersonAlias.PersonId );
                                if ( !newGroupMembers.Any() )
                                {
                                    // Get any existing group member attribute values
                                    var existingAttributeValues = new Dictionary<string, string>();
                                    if ( registrant.GroupMemberId.HasValue )
                                    {
                                        var existingGroupMember = groupMemberService.Get( registrant.GroupMemberId.Value );
                                        if ( existingGroupMember != null )
                                        {
                                            existingGroupMember.LoadAttributes( rockContext );
                                            foreach ( var attributeValue in existingGroupMember.AttributeValues )
                                            {
                                                existingAttributeValues.Add( attributeValue.Key, attributeValue.Value.Value );
                                            }
                                        }

                                        registrant.GroupMember = null;
                                        groupMemberService.Delete( existingGroupMember );
                                    }

                                    var newGroupMember = new GroupMember();
                                    groupMemberService.Add( newGroupMember );
                                    newGroupMember.Group = group;
                                    newGroupMember.PersonId = registrant.PersonAlias.PersonId;
                                    newGroupMember.GroupRoleId = groupRoleId.Value;
                                    rockContext.SaveChanges();

                                    newGroupMember = groupMemberService.Get( newGroupMember.Id );
                                    newGroupMember.LoadAttributes();

                                    foreach( var attr in newGroupMember.Attributes )
                                    {
                                        if ( existingAttributeValues.ContainsKey( attr.Key ) )
                                        {
                                            newGroupMember.SetAttributeValue( attr.Key, existingAttributeValues[attr.Key] );
                                        }
                                    }
                                    newGroupMember.SaveAttributeValues( rockContext );

                                    registrant.GroupMember = newGroupMember;
                                    rockContext.SaveChanges();

                                }
                            }
                        }
                    }
                }

                // Reload registration
                Registration = GetRegistration( Registration.Id );

                lWizardInstanceName.Text = Registration.RegistrationInstance.Name;
                ShowReadonlyDetails( Registration );
            }

            mdMoveRegistration.Hide();
        }
Esempio n. 9
0
        /// <summary>
        /// Handles the Click event of the btnMoveGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnMoveGroupMember_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var groupMemberService = new GroupMemberService( rockContext );
            var groupMember = groupMemberService.Get( hfGroupMemberId.Value.AsInteger() );
            groupMember.LoadAttributes();
            int destGroupId = gpMoveGroupMember.SelectedValue.AsInteger();
            var destGroup = new GroupService( rockContext ).Get( destGroupId );

            var destGroupMember = groupMemberService.Queryable().Where( a =>
                a.GroupId == destGroupId
                && a.PersonId == groupMember.PersonId
                && a.GroupRoleId == grpMoveGroupMember.GroupRoleId ).FirstOrDefault();

            if ( destGroupMember != null )
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text = string.Format( "{0} is already in {1}", groupMember.Person, destGroupMember.Group );
                return;
            }

            if ( !grpMoveGroupMember.GroupRoleId.HasValue )
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text = string.Format( "Please select a Group Role" );
                return;
            }

            string canDeleteWarning;
            if ( !groupMemberService.CanDelete( groupMember, out canDeleteWarning ) )
            {
                nbMoveGroupMemberWarning.Visible = true;
                nbMoveGroupMemberWarning.Text = string.Format( "Unable to remove {0} from {1}: {2}", groupMember.Person, groupMember.Group, canDeleteWarning );
                return;
            }

            destGroupMember = new GroupMember();
            destGroupMember.GroupId = destGroupId;
            destGroupMember.GroupRoleId = grpMoveGroupMember.GroupRoleId.Value;
            destGroupMember.PersonId = groupMember.PersonId;
            destGroupMember.LoadAttributes();

            foreach ( var attribute in groupMember.Attributes )
            {
                if ( destGroupMember.Attributes.Any( a => a.Key == attribute.Key && a.Value.FieldTypeId == attribute.Value.FieldTypeId ) )
                {
                    destGroupMember.SetAttributeValue( attribute.Key, groupMember.GetAttributeValue( attribute.Key ) );
                }
            }

            rockContext.WrapTransaction( () =>
            {
                groupMemberService.Add( destGroupMember );
                rockContext.SaveChanges();
                destGroupMember.SaveAttributeValues( rockContext );

                // move any Note records that were associated with the old groupMember to the new groupMember record
                if ( cbMoveGroupMemberMoveNotes.Checked )
                {
                    destGroupMember.Note = groupMember.Note;
                    int groupMemberEntityTypeId = EntityTypeCache.GetId<Rock.Model.GroupMember>().Value;
                    var noteService = new NoteService( rockContext );
                    var groupMemberNotes = noteService.Queryable().Where( a => a.NoteType.EntityTypeId == groupMemberEntityTypeId && a.EntityId == groupMember.Id );
                    foreach ( var note in groupMemberNotes )
                    {
                        note.EntityId = destGroupMember.Id;
                    }

                    rockContext.SaveChanges();
                }

                groupMemberService.Delete( groupMember );
                rockContext.SaveChanges();

                destGroupMember.CalculateRequirements( rockContext, true );
            } );

            var queryString = new Dictionary<string, string>();
            queryString.Add( "GroupMemberId", destGroupMember.Id.ToString() );
            this.NavigateToPage( this.RockPage.Guid, queryString );
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="item">The item.</param>
        protected void SaveChanges(RepeaterItem item)
        {
            var hfGroupId = item.FindControl("hfGroupId") as HiddenField;
            var cbCommunicationListIsSubscribed = item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox;
            var tglCommunicationPreference      = item.FindControl("tglCommunicationPreference") as Toggle;
            var nbGroupNotification             = item.FindControl("nbGroupNotification") as NotificationBox;

            nbGroupNotification.Visible = false;

            using (var rockContext = new RockContext())
            {
                int groupId            = hfGroupId.Value.AsInteger();
                var groupMemberService = new GroupMemberService(rockContext);
                var group = new GroupService(rockContext).Get(groupId);
                var groupMemberRecordsForPerson = groupMemberService.Queryable().Where(a => a.GroupId == groupId && a.PersonId == this.CurrentPersonId).ToList();
                if (groupMemberRecordsForPerson.Any())
                {
                    // normally there would be at most 1 group member record for the person, but just in case, mark them all
                    foreach (var groupMember in groupMemberRecordsForPerson)
                    {
                        if (cbCommunicationListIsSubscribed.Checked)
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Inactive)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                if (groupMember.Note == "Unsubscribed")
                                {
                                    groupMember.Note = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                                if (groupMember.Note.IsNullOrWhiteSpace())
                                {
                                    groupMember.Note = "Unsubscribed";
                                }
                            }
                        }

                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());
                        groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                    }
                }
                else
                {
                    // they are not currently in the Group
                    if (cbCommunicationListIsSubscribed.Checked)
                    {
                        var groupMember = new GroupMember();
                        groupMember.PersonId = this.CurrentPersonId.Value;
                        groupMember.GroupId  = group.Id;
                        int?defaultGroupRoleId = GroupTypeCache.Get(group.GroupTypeId).DefaultGroupRoleId;
                        if (defaultGroupRoleId.HasValue)
                        {
                            groupMember.GroupRoleId = defaultGroupRoleId.Value;
                        }
                        else
                        {
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = "Group has no default group role";
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }

                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());

                        if (groupMember.IsValidGroupMember(rockContext))
                        {
                            groupMemberService.Add(groupMember);
                            rockContext.SaveChanges();
                            groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                        }
                        else
                        {
                            // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }
                    }
                }

                rockContext.SaveChanges();
            }
        }