Example #1
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns(BenevolenceRequest benevolenceRequest)
        {
            ddlRequestStatus.BindToDefinedType(DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_REQUEST_STATUS)), false);
            ddlConnectionStatus.BindToDefinedType(DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)), true);

            Guid groupGuid  = GetAttributeValue("CaseWorkerRole").AsGuid();
            var  personList = new GroupMemberService(new RockContext())
                              .Queryable("Person, Group")
                              .Where(gm => gm.Group.Guid == groupGuid)
                              .Select(gm => gm.Person)
                              .ToList();

            string caseWorkerPersonAliasValue = benevolenceRequest.CaseWorkerPersonAliasId.ToString();

            if (benevolenceRequest.CaseWorkerPersonAlias != null &&
                benevolenceRequest.CaseWorkerPersonAlias.Person != null &&
                !personList.Select(p => p.Id).ToList().Contains(benevolenceRequest.CaseWorkerPersonAlias.Person.Id))
            {
                personList.Add(benevolenceRequest.CaseWorkerPersonAlias.Person);
            }

            ddlCaseWorker.DataSource     = personList.OrderBy(p => p.NickName).ThenBy(p => p.LastName).ToList();
            ddlCaseWorker.DataTextField  = "FullName";
            ddlCaseWorker.DataValueField = "PrimaryAliasId";
            ddlCaseWorker.DataBind();
            ddlCaseWorker.Items.Insert(0, new ListItem());
        }
Example #2
0
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowType workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMember        = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();

                    if (workflowType != null)
                    {
                        try
                        {
                            List <string> workflowErrors;
                            var           workflow = Workflow.Activate(workflowType, person.FullName);
                            new WorkflowService(rockContext).Process(workflow, groupMember, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }
        }
Example #3
0
 /// <summary>
 /// Adds the person to group.
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="person">The person.</param>
 /// <param name="workflowType">Type of the workflow.</param>
 /// <param name="groupMembers">The group members.</param>
 private void AddPersonToGroup(RockContext rockContext, Person person)
 {
     if (person != null)
     {
         if (!CurrentGroup.Members
             .Any(m =>
                  m.PersonId == person.Id &&
                  m.GroupRoleId == _defaultGroupRole.Id))
         {
             var groupMemberService = new GroupMemberService(rockContext);
             var groupMember        = new GroupMember();
             groupMember.PersonId          = person.Id;
             groupMember.GroupRoleId       = _defaultGroupRole.Id;
             groupMember.GroupMemberStatus = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
             groupMember.GroupId           = CurrentGroup.Id;
             groupMemberService.Add(groupMember);
             rockContext.SaveChanges();
         }
         else
         {
             foreach (var groupMember in CurrentGroup.Members
                      .Where(m => m.PersonId == person.Id &&
                             m.GroupRoleId == _defaultGroupRole.Id))
             {
                 var groupMemberService = new GroupMemberService(rockContext);
                 var efGroupMember      = groupMemberService.Get(groupMember.Guid);
                 efGroupMember.GroupMemberStatus = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
                 debug.Text += groupMember.Person.FullName;
             }
             rockContext.SaveChanges();
         }
     }
 }
Example #4
0
        /// <summary>
        /// Adds the group member.
        /// </summary>
        /// <param name="familyGroup">The family group.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        protected GroupMember AddGroupMember(int familyGroupId, Person person)
        {
            var rockContext = new RockContext();

            GroupMember groupMember = new GroupMember();

            groupMember.IsSystem = false;
            groupMember.GroupId  = familyGroupId;
            groupMember.PersonId = person.Id;
            if (person.Age >= 18)
            {
                groupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id;
            }
            else
            {
                groupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id;
            }

            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

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

            return(groupMember);
        }
        /// <summary>
        /// Adds the person as group member.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddPersonAsGroupMember(Person person, RockContext rockContext)
        {
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            GroupTypeRole      role = new GroupTypeRoleService(rockContext).Get(_group.GroupType.DefaultGroupRoleId ?? 0);

            var groupMember = new GroupMember {
                Id = 0
            };

            groupMember.GroupId = _group.Id;

            // check to see if the person is already a member of the group/role
            var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(_group.Id, person.Id, _group.GroupType.DefaultGroupRoleId ?? 0);

            if (existingGroupMember != null)
            {
                return;
            }

            groupMember.PersonId          = person.Id;
            groupMember.GroupRoleId       = role.Id;
            groupMember.GroupMemberStatus = GroupMemberStatus.Active;

            if (groupMember.Id.Equals(0))
            {
                groupMemberService.Add(groupMember);
            }

            rockContext.SaveChanges();
        }
        private void Subscribe(int groupId)
        {
            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            var groupMembers = groupMemberService.GetByGroupIdAndPersonId(groupId, Person.Id).ToList();

            if (groupMembers.Any())
            {
                foreach (var member in groupMembers)
                {
                    member.GroupMemberStatus = GroupMemberStatus.Active;
                    CommunicationMembership.Add(member);
                }
            }
            else
            {
                GroupService groupService       = new GroupService(rockContext);
                var          group              = groupService.Get(groupId);
                var          defaultGroupRoleId = group.GroupType.DefaultGroupRoleId;
                var          newMember          = new GroupMember
                {
                    PersonId          = Person.Id,
                    GroupId           = groupId,
                    GroupRoleId       = defaultGroupRoleId.Value,
                    GroupMemberStatus = GroupMemberStatus.Active
                };
                groupMemberService.Add(newMember);

                CommunicationMembership.Add(newMember);
            }

            rockContext.SaveChanges();
            SaveViewState();
            BindGroups(true);
        }
Example #7
0
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowTypeCache workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                GroupMember groupMember = null;
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    groupMember                   = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    GroupMemberStatus status = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember = _group.Members.Where(m =>
                                                       m.PersonId == person.Id &&
                                                       m.GroupRoleId == _defaultGroupRole.Id).FirstOrDefault();
                    if (groupMember.GroupMemberStatus != status)
                    {
                        var groupMemberService = new GroupMemberService(rockContext);

                        // reload this group member in the current context
                        groupMember = groupMemberService.Get(groupMember.Id);
                        groupMember.GroupMemberStatus = status;
                        rockContext.SaveChanges();
                    }
                }

                if (groupMember != null)
                {
                    groupMember.LoadAttributes();
                    groupMember.SetAttributeValue("RSVPCount", numHowMany.Value);
                    groupMember.SaveAttributeValues();

                    SendGroupEmail(groupMember);
                }

                if (groupMember != null && workflowType != null && (workflowType.IsActive ?? true))
                {
                    try
                    {
                        List <string> workflowErrors;
                        var           workflow = Workflow.Activate(workflowType, person.FullName);
                        new WorkflowService(rockContext).Process(workflow, groupMember, out workflowErrors);
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogService.LogException(ex, this.Context);
                    }
                }
            }
        }
Example #8
0
        /// <summary>
        /// Adds the group member.
        /// </summary>
        /// <param name="familyGroup">The family group.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        protected GroupMember AddGroupMember(int familyGroupId, Person person)
        {
            GroupMember        groupMember        = new GroupMember().Clone(false);
            GroupMemberService groupMemberService = new GroupMemberService();

            groupMember.IsSystem = false;
            groupMember.GroupId  = familyGroupId;
            groupMember.PersonId = person.Id;
            if (person.Age >= 18)
            {
                groupMember.GroupRoleId = new GroupTypeRoleService().Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id;
            }
            else
            {
                groupMember.GroupRoleId = new GroupTypeRoleService().Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id;
            }

            Rock.Data.RockTransactionScope.WrapTransaction(() =>
            {
                groupMemberService.Add(groupMember, CurrentPersonId);
                groupMemberService.Save(groupMember, CurrentPersonId);
            });

            return(groupMember);
        }
Example #9
0
        /// <summary>
        /// Updates the group member.
        /// </summary>
        /// <param name="businessId">The business identifier.</param>
        /// <param name="groupType">Type of the group.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="groupRoleId">The group role identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private GroupMember UpdateGroupMember(int businessId, GroupTypeCache groupType, string groupName, int?campusId, int groupRoleId, RockContext rockContext)
        {
            var groupMemberService = new GroupMemberService(rockContext);

            GroupMember groupMember = groupMemberService.Queryable("Group")
                                      .Where(m =>
                                             m.PersonId == businessId &&
                                             m.GroupRoleId == groupRoleId)
                                      .FirstOrDefault();

            if (groupMember == null)
            {
                groupMember       = new GroupMember();
                groupMember.Group = new Group();
            }

            groupMember.PersonId          = businessId;
            groupMember.GroupRoleId       = groupRoleId;
            groupMember.GroupMemberStatus = GroupMemberStatus.Active;

            groupMember.Group.GroupTypeId = groupType.Id;
            groupMember.Group.Name        = groupName;
            groupMember.Group.CampusId    = campusId;

            if (groupMember.Id == 0)
            {
                groupMemberService.Add(groupMember);
            }

            return(groupMember);
        }
Example #10
0
        void modalAddPerson_SaveClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(acPerson.Value))
            {
                int personId = int.MinValue;
                if (int.TryParse(acPerson.Value, out personId))
                {
                    int?roleId = grpRole.GroupRoleId;
                    if (roleId.HasValue)
                    {
                        using (new UnitOfWorkScope())
                        {
                            var memberService = new GroupMemberService();
                            var group         = memberService.Queryable()
                                                .Where(m =>
                                                       m.PersonId == Person.Id &&
                                                       m.GroupRole.Guid == ownerRoleGuid
                                                       )
                                                .Select(m => m.Group)
                                                .FirstOrDefault();

                            if (group != null)
                            {
                                var groupMember = memberService.Queryable()
                                                  .Where(m =>
                                                         m.GroupId == group.Id &&
                                                         m.PersonId == personId &&
                                                         m.GroupRoleId == roleId.Value)
                                                  .FirstOrDefault();

                                if (groupMember == null)
                                {
                                    groupMember             = new GroupMember();
                                    groupMember.GroupId     = group.Id;
                                    groupMember.PersonId    = personId;
                                    groupMember.GroupRoleId = roleId.Value;
                                    memberService.Add(groupMember, CurrentPersonId);
                                }

                                memberService.Save(groupMember, CurrentPersonId);
                                if (IsKnownRelationships)
                                {
                                    var inverseGroupMember = memberService.GetInverseRelationship(
                                        groupMember, bool.Parse(GetAttributeValue("CreateGroup")), CurrentPersonId);
                                    if (inverseGroupMember != null)
                                    {
                                        memberService.Save(inverseGroupMember, CurrentPersonId);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            BindData();
        }
Example #11
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick(object sender, EventArgs e)
        {
            var rockContext  = new RockContext();
            var groupService = new GroupService(rockContext);

            var group = groupService.Get(ddlGroup.SelectedValue.AsInteger());

            if (group == null)
            {
                nbModalDetailsMessage.Title   = "Please select a Group";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            var roleId = ddlGroupRole.SelectedValue.AsIntegerOrNull();

            if (roleId == null)
            {
                nbModalDetailsMessage.Title   = "Please select a role";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            var personContext      = ContextEntity <Person>();
            var groupMemberService = new GroupMemberService(rockContext);

            if (groupMemberService.Queryable().Any(a => a.PersonId == personContext.Id && a.GroupId == group.Id && a.GroupRoleId == roleId))
            {
                nbModalDetailsMessage.Title   = "Already added to the selected Group & Role";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            if (!(group.IsAuthorized(Authorization.EDIT, this.CurrentPerson) || group.IsAuthorized(Authorization.MANAGE_MEMBERS, this.CurrentPerson)))
            {
                // shouldn't happen because GroupList is limited to EDIT and MANAGE_MEMBERs, but just in case
                nbModalDetailsMessage.Title   = "You are not authorized to add members to this group";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            GroupMember groupMember = new GroupMember {
                Id = 0
            };

            groupMember.GroupId           = group.Id;
            groupMember.PersonId          = personContext.Id;
            groupMember.GroupRoleId       = ddlGroupRole.SelectedValue.AsInteger();
            groupMember.GroupMemberStatus = GroupMemberStatus.Active;

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

            modalDetails.Hide();
            BindFilter();
            BindGrid();
        }
        /// <summary>
        /// Adds the person to group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="workflowType">Type of the workflow.</param>
        /// <param name="groupMembers">The group members.</param>
        private void AddPersonToGroup(RockContext rockContext, Person person, WorkflowType workflowType, List <GroupMember> groupMembers)
        {
            if (person != null)
            {
                if (!_group.Members
                    .Any(m =>
                         m.PersonId == person.Id &&
                         m.GroupRoleId == _defaultGroupRole.Id))
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMember        = new GroupMember();
                    groupMember.PersonId          = person.Id;
                    groupMember.GroupRoleId       = _defaultGroupRole.Id;
                    groupMember.GroupMemberStatus = (GroupMemberStatus)GetAttributeValue("GroupMemberStatus").AsInteger();
                    groupMember.GroupId           = _group.Id;
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();

                    if (workflowType != null)
                    {
                        try
                        {
                            var workflowService = new WorkflowService(rockContext);
                            var workflow        = Workflow.Activate(workflowType, person.FullName);

                            List <string> workflowErrors;
                            if (workflow.Process(rockContext, groupMember, out workflowErrors))
                            {
                                if (workflow.IsPersisted || workflow.IsPersisted)
                                {
                                    if (workflow.Id == 0)
                                    {
                                        workflowService.Add(workflow);
                                    }

                                    rockContext.WrapTransaction(() =>
                                    {
                                        rockContext.SaveChanges();
                                        workflow.SaveAttributeValues(_rockContext);
                                        foreach (var activity in workflow.Activities)
                                        {
                                            activity.SaveAttributeValues(rockContext);
                                        }
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }
        }
Example #13
0
        protected void btnStart_Click(object sender, EventArgs e)
        {
            rockContext = new RockContext();
            GroupService       groupService       = new GroupService(rockContext);
            PersonService      personService      = new PersonService(rockContext);
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            foreach (var year in graduationYears)
            {
                var children = personService.Queryable().Where(p => p.GraduationYear == year);
                foreach (var child in children.ToList())
                {
                    child.LoadAttributes();
                    var breakoutGroupAttribute = child.GetAttributeValue("Arena-16-2938");
                    if (string.IsNullOrEmpty(breakoutGroupAttribute))
                    {
                        continue;
                    }
                    var groupParts = breakoutGroupAttribute.Split('-');
                    if (groupParts.Count() != 2 || !scheduleKey.Keys.Contains(groupParts[0].AsInteger()))
                    {
                        continue;
                    }

                    var groupLetter     = groupParts[1];
                    var groupScheduleId = scheduleKey[groupParts[0].AsInteger()];
                    var gradeName       = graduationKey[year];

                    var group = groupService.Queryable()
                                .Where(g =>
                                       g.GroupTypeId == groupTypeId &&
                                       g.Name.EndsWith(groupLetter) &&
                                       g.Name.StartsWith(gradeName) &&
                                       g.ScheduleId == groupScheduleId
                                       ).FirstOrDefault();
                    if (group == null)
                    {
                        group = CreateNewGroup(gradeName, groupScheduleId, groupLetter);
                    }

                    if (!group.Members.Select(gm => gm.PersonId).Contains(child.Id))
                    {
                        var groupMember = new GroupMember()
                        {
                            GroupId     = group.Id,
                            PersonId    = child.Id,
                            GroupRoleId = groupTypeRoleId
                        };
                        groupMemberService.Add(groupMember);
                        rockContext.SaveChanges();
                    }
                }
            }
        }
Example #14
0
        private int?AddRegistrantToGroup(RegistrationRegistrant registrant)
        {
            if (registrant.PersonAliasId.HasValue &&
                registrant.Registration != null &&
                registrant.Registration.Group != null &&
                registrant.Registration.Group.GroupType != null && _template != null)
            {
                var group = registrant.Registration.Group;

                var groupService       = new GroupService(_rockContext);
                var personAliasService = new PersonAliasService(_rockContext);
                var groupMemberService = new GroupMemberService(_rockContext);

                var         personAlias = personAliasService.Get(registrant.PersonAliasId.Value);
                GroupMember groupMember = group.Members.Where(m => m.PersonId == personAlias.PersonId).FirstOrDefault();
                if (groupMember == null)
                {
                    groupMember          = new GroupMember();
                    groupMember.GroupId  = group.Id;
                    groupMember.PersonId = personAlias.PersonId;

                    if (_template.GroupTypeId.HasValue &&
                        _template.GroupTypeId == group.GroupTypeId &&
                        _template.GroupMemberRoleId.HasValue)
                    {
                        groupMember.GroupRoleId       = _template.GroupMemberRoleId.Value;
                        groupMember.GroupMemberStatus = _template.GroupMemberStatus;
                    }
                    else
                    {
                        if (group.GroupType.DefaultGroupRoleId.HasValue)
                        {
                            groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;
                        }
                        else
                        {
                            groupMember.GroupRoleId = group.GroupType.Roles.Select(r => r.Id).FirstOrDefault();
                        }
                    }

                    groupMemberService.Add(groupMember);
                }

                groupMember.GroupMemberStatus = _template.GroupMemberStatus;

                _rockContext.SaveChanges();

                return(groupMember.Id);
            }

            return((int?)null);
        }
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick(object sender, EventArgs e)
        {
            var rockContext  = new RockContext();
            var groupService = new GroupService(rockContext);

            var group = groupService.Get(ddlGroup.SelectedValue.AsInteger());

            if (group == null)
            {
                nbMessage.Title = "Please select a Group";
                return;
            }

            var personContext      = ContextEntity <Person>();
            var groupMemberService = new GroupMemberService(rockContext);

            if (groupMemberService.Queryable().Any(a => a.PersonId == personContext.Id && a.GroupId == group.Id))
            {
                nbMessage.Title = "Member already added to selected Group";
                return;
            }

            var roleId = group.GroupType.DefaultGroupRoleId;

            if (roleId == null)
            {
                nbMessage.Title = "No default role for particular group is assigned";
                return;
            }

            GroupMember groupMember = new GroupMember {
                Id = 0
            };

            groupMember.GroupId           = group.Id;
            groupMember.PersonId          = personContext.Id;
            groupMember.GroupRoleId       = roleId.Value;
            groupMember.GroupMemberStatus = GroupMemberStatus.Active;

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

            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
            {
                Rock.Security.Role.Flush(group.Id);
            }

            modalDetails.Hide();
            BindFilter();
            BindGrid();
        }
Example #16
0
        /// <summary>
        /// Handles the RowCommand event of the grdPersonSearchResults control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridViewCommandEventArgs"/> instance containing the event data.</param>
        protected void rGridPersonResults_AddExistingPerson(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Add"))
            {
                var selectedFamily = CurrentCheckInState.CheckIn.Families.FirstOrDefault(f => f.Selected);
                if (selectedFamily != null)
                {
                    int rowIndex = int.Parse(e.CommandArgument.ToString());
                    int personId = int.Parse(rGridPersonResults.DataKeys[rowIndex].Value.ToString());

                    var checkInPerson = selectedFamily.People.FirstOrDefault(p => p.Person.Id == personId);
                    if (checkInPerson == null)
                    {
                        var rockContext = new RockContext();
                        checkInPerson.Person = new PersonService(rockContext).Get(personId).Clone(false);

                        if (!newPersonType.Value.Equals("Visitor"))
                        {
                            // New family member, add them to the current family if they don't exist
                            var groupMemberService = new GroupMemberService(rockContext);
                            if (!selectedFamily.Group.Members.Any(gm => gm.PersonId == personId))
                            {
                                var familyMember = new GroupMember();
                                familyMember.GroupId           = selectedFamily.Group.Id;
                                familyMember.PersonId          = personId;
                                familyMember.IsSystem          = false;
                                familyMember.GroupMemberStatus = GroupMemberStatus.Active;
                                familyMember.GroupRoleId       = (int)selectedFamily.Group.GroupType.DefaultGroupRoleId;

                                groupMemberService.Add(familyMember);
                                rockContext.SaveChanges();
                            }

                            checkInPerson.FamilyMember = true;
                        }
                        else
                        {
                            // Visitor, associate with current family
                            AddVisitorRelationships(selectedFamily, personId, rockContext);
                            checkInPerson.FamilyMember = false;
                        }

                        checkInPerson.Selected = true;
                        selectedFamily.People.Add(checkInPerson);
                        ProcessPeople(selectedFamily);
                    }

                    mdlAddPerson.Hide();
                }
            }
        }
        protected void btnSubscribe_Click(object sender, EventArgs e)
        {
            var groupId = ( int )ViewState["KeywordGroupId"];

            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            GroupService       groupService       = new GroupService(rockContext);

            var group = groupService.Get(groupId);
            var defaultGroupRoleId = group.GroupType.DefaultGroupRoleId;


            var groupMembers = groupMemberService.GetByGroupIdAndPersonId(groupId, Person.Id).ToList();

            if (!groupMembers.Any())
            {
                var groupMember = new GroupMember
                {
                    GroupId     = groupId,
                    PersonId    = Person.Id,
                    GroupRoleId = defaultGroupRoleId.Value
                };
                groupMemberService.Add(groupMember);
                groupMembers.Add(groupMember);
                rockContext.SaveChanges();
            }

            foreach (var member in groupMembers)
            {
                member.GroupMemberStatus = GroupMemberStatus.Active;
                rockContext.SaveChanges();

                member.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues(phGroupAttributes, member);
                member.SaveAttributeValues();

                CommunicationMembership.Add(member);
            }

            SaveViewState();
            pnlKeyword.Visible = false;
            nbSuccess.Visible  = true;
            nbSuccess.Text     = "You have been successfully subscribed. We look forward to communicating with you soon!";

            BindGroups(true);
        }
Example #18
0
        void lb_Click(object sender, EventArgs e)
        {
            if (CurrentPersonId.HasValue)
            {
                LinkButton lb = sender as LinkButton;
                if (lb != null)
                {
                    int groupId = 0;
                    if (Int32.TryParse(lb.Attributes["group"], out groupId))
                    {
                        int roleId = 0;
                        if (!Int32.TryParse(AttributeValue("GroupRole"), out roleId))
                        {
                            roleId = 0;
                        }

                        var group = groupService.Get(groupId);
                        if (group != null &&
                            group.AttributeValues.ContainsKey(_videoAttributeKey))
                        {
                            hfVideoUrl.Value = group.AttributeValues[_videoAttributeKey][0].Value;

                            GroupMemberService memberService = new GroupMemberService();
                            var groupMember = memberService.GetByGroupIdAndPersonIdAndGroupRoleId(
                                groupId, CurrentPersonId.Value, roleId);
                            if (groupMember == null)
                            {
                                groupMember             = new GroupMember();
                                groupMember.GroupId     = groupId;
                                groupMember.PersonId    = CurrentPersonId.Value;
                                groupMember.GroupRoleId = roleId;
                                memberService.Add(groupMember, CurrentPersonId);
                                memberService.Save(groupMember, CurrentPersonId);
                            }

                            HtmlGenericControl li = lb.Parent as HtmlGenericControl;
                            if (li != null)
                            {
                                li.RemoveCssClass("not-viewed");
                                li.AddCssClass("viewed");
                            }
                        }
                    }
                }
            }
        }
Example #19
0
 /// <summary>
 /// Adds the person to group.
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="person">The person.</param>
 /// <param name="workflowType">Type of the workflow.</param>
 /// <param name="groupMembers">The group members.</param>
 private void AddPersonToGroup(RockContext rockContext, Person person)
 {
     if (person != null)
     {
         if (!CurrentGroup.Members
             .Any(m =>
                  m.PersonId == person.Id &&
                  m.GroupRoleId == _defaultGroupRole.Id))
         {
             var groupMemberService = new GroupMemberService(rockContext);
             var groupMember        = new GroupMember();
             groupMember.PersonId          = person.Id;
             groupMember.GroupRoleId       = _defaultGroupRole.Id;
             groupMember.GroupMemberStatus = ( GroupMemberStatus )GetAttributeValue("GroupMemberStatus").AsInteger();
             groupMember.GroupId           = CurrentGroup.Id;
             groupMemberService.Add(groupMember);
             rockContext.SaveChanges();
         }
     }
 }
Example #20
0
        public void PostSave_ShouldNotUpdatePersonAccountProtectionProfileToLowerValue(int expectedElevatedSecurityLevel)
        {
            var personGuid = Guid.NewGuid();
            var person     = new Person
            {
                FirstName = "Test",
                LastName  = personGuid.ToString(),
                Email     = $"{personGuid}@test.com",
                Guid      = personGuid,
                AccountProtectionProfile = AccountProtectionProfile.Extreme
            };

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);
                personService.Add(person);
                rockContext.SaveChanges();

                person = personService.Get(person.Id);
                Assert.That.AreEqual(AccountProtectionProfile.Extreme, person.AccountProtectionProfile);

                var group       = CreateTestGroup(rockContext, ( ElevatedSecurityLevel )expectedElevatedSecurityLevel);
                var groupMember = new GroupMember
                {
                    Group             = group,
                    PersonId          = person.Id,
                    GroupRole         = group.GroupType.Roles.FirstOrDefault(),
                    GroupMemberStatus = GroupMemberStatus.Active
                };

                var groupMemberService = new GroupMemberService(rockContext);
                groupMemberService.Add(groupMember);
                rockContext.SaveChanges();

                person = personService.Get(person.Id);
                Assert.That.AreEqual(AccountProtectionProfile.Extreme, person.AccountProtectionProfile);
            }
        }
        private void AddGroupMember(Group group, RockDropDownList ddlRole)
        {
            int roleId = ddlRole.SelectedValue.AsInteger();

            if (Person != null &&
                roleId != 0 &&
                group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                RockContext        rockContext        = new RockContext();
                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                if (groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(group.Id, Person.Id, roleId) == null)
                {
                    GroupMember groupMember = new GroupMember()
                    {
                        GroupId     = group.Id,
                        PersonId    = Person.Id,
                        GroupRoleId = roleId
                    };
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
            }
            ShowEdit();
        }
Example #22
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns(BenevolenceRequest benevolenceRequest)
        {
            dvpRequestStatus.DefinedTypeId    = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_REQUEST_STATUS)).Id;
            dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)).Id;

            if (_caseWorkerGroupGuid.HasValue)
            {
                var personList = new GroupMemberService(new RockContext())
                                 .Queryable("Person, Group")
                                 .Where(gm => gm.Group.Guid == _caseWorkerGroupGuid.Value)
                                 .Select(gm => gm.Person)
                                 .ToList();

                string caseWorkerPersonAliasValue = benevolenceRequest.CaseWorkerPersonAliasId.ToString();
                if (benevolenceRequest.CaseWorkerPersonAlias != null &&
                    benevolenceRequest.CaseWorkerPersonAlias.Person != null &&
                    !personList.Select(p => p.Id).ToList().Contains(benevolenceRequest.CaseWorkerPersonAlias.Person.Id))
                {
                    personList.Add(benevolenceRequest.CaseWorkerPersonAlias.Person);
                }

                ddlCaseWorker.DataSource     = personList.OrderBy(p => p.NickName).ThenBy(p => p.LastName).ToList();
                ddlCaseWorker.DataTextField  = "FullName";
                ddlCaseWorker.DataValueField = "PrimaryAliasId";
                ddlCaseWorker.DataBind();
                ddlCaseWorker.Items.Insert(0, new ListItem());

                ppCaseWorker.Visible  = false;
                ddlCaseWorker.Visible = true;
            }
            else
            {
                ppCaseWorker.Visible  = true;
                ddlCaseWorker.Visible = false;
            }
        }
Example #23
0
        /// <summary>
        /// Handles the SaveClick event of the modalAddPerson 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 modalAddPerson_SaveClick(object sender, EventArgs e)
        {
            if (CanEdit)
            {
                if (ppPerson.PersonId.HasValue)
                {
                    int?roleId = grpRole.GroupRoleId;
                    if (roleId.HasValue)
                    {
                        var rockContext   = new RockContext();
                        var memberService = new GroupMemberService(rockContext);

                        var group = memberService.Queryable(true)
                                    .Where(m =>
                                           m.PersonId == Person.Id &&
                                           m.GroupRole.Guid == ownerRoleGuid)
                                    .Select(m => m.Group)
                                    .FirstOrDefault();

                        if (group != null)
                        {
                            GroupMember groupMember   = null;
                            int?        groupMemberId = hfRoleId.Value.AsIntegerOrNull();
                            if (groupMemberId.HasValue)
                            {
                                groupMember = memberService.Queryable(true)
                                              .Where(m => m.Id == groupMemberId.Value)
                                              .FirstOrDefault();
                            }

                            if (groupMember == null)
                            {
                                groupMember         = new GroupMember();
                                groupMember.GroupId = group.Id;
                                memberService.Add(groupMember);
                            }

                            GroupMember formerInverseGroupMember = null;
                            if (IsKnownRelationships)
                            {
                                formerInverseGroupMember = memberService.GetInverseRelationship(groupMember, false);
                            }

                            groupMember.PersonId    = ppPerson.PersonId.Value;
                            groupMember.GroupRoleId = roleId.Value;

                            rockContext.SaveChanges();

                            if (IsKnownRelationships)
                            {
                                var inverseGroupMember = memberService.GetInverseRelationship(groupMember, GetAttributeValue("CreateGroup").AsBoolean());
                                if (inverseGroupMember != null)
                                {
                                    rockContext.SaveChanges();
                                    if (formerInverseGroupMember != null && formerInverseGroupMember.Id != inverseGroupMember.Id)
                                    {
                                        memberService.Delete(formerInverseGroupMember);
                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }

                HideDialog();

                BindData();
            }
        }
Example #24
0
        /// <summary>
        /// Saves the family and persons to the database
        /// </summary>
        /// <param name="kioskCampusId">The kiosk campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext)
        {
            SaveResult saveResult = new SaveResult();

            FamilyRegistrationState editFamilyState = this;
            var personService             = new PersonService(rockContext);
            var groupService              = new GroupService(rockContext);
            var recordTypePersonId        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            var maritalStatusMarried      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid());
            var maritalStatusSingle       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_SINGLE.AsGuid());
            var numberTypeValueMobile     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
            int groupTypeRoleAdultId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
            int groupTypeRoleChildId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
            int?groupTypeRoleCanCheckInId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid())
                                            ?.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN.AsGuid())?.Id;

            bool?groupTypeDefaultSmsEnabled = GroupTypeCache.GetFamilyGroupType().GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBooleanOrNull();

            Group primaryFamily = null;

            if (editFamilyState.GroupId.HasValue)
            {
                primaryFamily = groupService.Get(editFamilyState.GroupId.Value);
            }

            // see if we can find matches for new people that were added, and also set the primary family if this is a new family, but a matching family was found
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.PersonId.HasValue && !a.IsDeleted))
            {
                var personQuery    = new PersonService.PersonMatchQuery(familyPersonState.FirstName, familyPersonState.LastName, familyPersonState.Email, familyPersonState.MobilePhoneNumber, familyPersonState.Gender, familyPersonState.BirthDate, familyPersonState.SuffixValueId);
                var matchingPerson = personService.FindPerson(personQuery, true);
                if (matchingPerson != null)
                {
                    // newly added person, but a match was found, so set the PersonId, GroupId, and ConnectionStatusValueID to the matching person instead of creating a new person
                    familyPersonState.PersonId                 = matchingPerson.Id;
                    familyPersonState.GroupId                  = matchingPerson.GetFamily(rockContext)?.Id;
                    familyPersonState.RecordStatusValueId      = matchingPerson.RecordStatusValueId;
                    familyPersonState.ConnectionStatusValueId  = matchingPerson.ConnectionStatusValueId;
                    familyPersonState.ConvertedToMatchedPerson = true;
                    if (primaryFamily == null && familyPersonState.IsAdult)
                    {
                        // if this is a new family, but we found a matching adult person, use that person's family as the family
                        primaryFamily = matchingPerson.GetFamily(rockContext);
                    }
                }
            }

            // loop thru all people and add/update as needed
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted))
            {
                Person person;
                if (!familyPersonState.PersonId.HasValue)
                {
                    person = new Person();
                    personService.Add(person);
                    saveResult.NewPersonList.Add(person);
                    person.RecordTypeValueId = recordTypePersonId;
                    person.FirstName         = familyPersonState.FirstName;
                }
                else
                {
                    person = personService.Get(familyPersonState.PersonId.Value);
                }

                // NOTE, Gender, MaritalStatusValueId, NickName, LastName are required fields so, always updated them to match the UI (even if a matched person was found)
                person.Gender = familyPersonState.Gender;
                person.MaritalStatusValueId = familyPersonState.IsMarried ? maritalStatusMarried.Id : maritalStatusSingle.Id;
                person.NickName             = familyPersonState.FirstName;
                person.LastName             = familyPersonState.LastName;

                // if the familyPersonState was converted to a Matched Person, don't overwrite existing values with blank values
                var saveEmptyValues = !familyPersonState.ConvertedToMatchedPerson;

                if (familyPersonState.SuffixValueId.HasValue || saveEmptyValues)
                {
                    person.SuffixValueId = familyPersonState.SuffixValueId;
                }

                if (familyPersonState.BirthDate.HasValue || saveEmptyValues)
                {
                    person.SetBirthDate(familyPersonState.BirthDate);
                }

                if (familyPersonState.DeceasedDate.HasValue || saveEmptyValues)
                {
                    person.DeceasedDate = familyPersonState.DeceasedDate;
                }

                if (familyPersonState.Email.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.Email = familyPersonState.Email;
                }

                if (familyPersonState.GradeOffset.HasValue || saveEmptyValues)
                {
                    person.GradeOffset = familyPersonState.GradeOffset;
                }

                // if a matching person was found, the familyPersonState's RecordStatusValueId and ConnectinoStatusValueId was already updated to match the matched person
                person.RecordStatusValueId     = familyPersonState.RecordStatusValueId;
                person.ConnectionStatusValueId = familyPersonState.ConnectionStatusValueId;

                rockContext.SaveChanges();

                bool isNewPerson = !familyPersonState.PersonId.HasValue;
                if (!familyPersonState.PersonId.HasValue)
                {
                    // if we added a new person, we know now the personId after SaveChanges, so set it
                    familyPersonState.PersonId = person.Id;
                }

                if (familyPersonState.AlternateID.IsNotNullOrWhiteSpace())
                {
                    PersonSearchKey        personAlternateValueIdSearchKey;
                    PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext);
                    if (isNewPerson)
                    {
                        // if we added a new person, a default AlternateId was probably added in the service layer. If a specific Alternate ID was specified, make sure that their SearchKey is updated
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId).FirstOrDefault();
                    }
                    else
                    {
                        // see if the key already exists. If if it doesn't already exist, let a new one get created
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId && a.SearchValue == familyPersonState.AlternateID).FirstOrDefault();
                    }

                    if (personAlternateValueIdSearchKey == null)
                    {
                        personAlternateValueIdSearchKey = new PersonSearchKey();
                        personAlternateValueIdSearchKey.PersonAliasId     = person.PrimaryAliasId;
                        personAlternateValueIdSearchKey.SearchTypeValueId = _personSearchAlternateValueId;
                        personSearchKeyService.Add(personAlternateValueIdSearchKey);
                    }

                    if (personAlternateValueIdSearchKey.SearchValue != familyPersonState.AlternateID)
                    {
                        personAlternateValueIdSearchKey.SearchValue = familyPersonState.AlternateID;
                        rockContext.SaveChanges();
                    }
                }

                person.LoadAttributes();
                foreach (var attributeValue in familyPersonState.PersonAttributeValuesState)
                {
                    // only set attribute values that are editable so we don't accidently delete any attribute values
                    if (familyPersonState.EditableAttributes.Contains(attributeValue.Value.AttributeId))
                    {
                        if (attributeValue.Value.Value.IsNotNullOrWhiteSpace() || saveEmptyValues)
                        {
                            person.SetAttributeValue(attributeValue.Key, attributeValue.Value.Value);
                        }
                    }
                }

                person.SaveAttributeValues(rockContext);

                if (familyPersonState.MobilePhoneNumber.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.UpdatePhoneNumber(numberTypeValueMobile.Id, familyPersonState.MobilePhoneCountryCode, familyPersonState.MobilePhoneNumber, familyPersonState.MobilePhoneSmsEnabled ?? groupTypeDefaultSmsEnabled, false, rockContext);
                }

                rockContext.SaveChanges();
            }

            if (primaryFamily == null)
            {
                // new family and no family found by looking up matching adults, so create a new family
                primaryFamily = new Group();
                var familyLastName = editFamilyState.FamilyPersonListState.OrderBy(a => a.IsAdult).Where(a => !a.IsDeleted).Select(a => a.LastName).FirstOrDefault();
                primaryFamily.Name        = familyLastName + " Family";
                primaryFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                // Set the Campus to the Campus of this Kiosk
                primaryFamily.CampusId = kioskCampusId;

                groupService.Add(primaryFamily);
                saveResult.NewFamilyList.Add(primaryFamily);
                rockContext.SaveChanges();
            }

            if (!editFamilyState.GroupId.HasValue)
            {
                editFamilyState.GroupId = primaryFamily.Id;
            }

            primaryFamily.LoadAttributes();
            foreach (var familyAttribute in editFamilyState.FamilyAttributeValuesState)
            {
                // only set attribute values that are editable so we don't accidently delete any attribute values
                if (editFamilyState.EditableFamilyAttributes.Contains(familyAttribute.Value.AttributeId))
                {
                    primaryFamily.SetAttributeValue(familyAttribute.Key, familyAttribute.Value.Value);
                }
            }

            primaryFamily.SaveAttributeValues(rockContext);

            var groupMemberService = new GroupMemberService(rockContext);

            // loop thru all people that are part of the same family (in the UI) and ensure they are all in the same primary family (in the database)
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily))
            {
                var currentFamilyMember = primaryFamily.Members.FirstOrDefault(m => m.PersonId == familyPersonState.PersonId.Value);

                if (currentFamilyMember == null)
                {
                    currentFamilyMember = new GroupMember
                    {
                        GroupId           = primaryFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(currentFamilyMember);

                    rockContext.SaveChanges();
                }
            }

            // make a dictionary of new related families (by lastname) so we can combine any new related children into a family with the same last name
            Dictionary <string, Group> newRelatedFamilies = new Dictionary <string, Group>(StringComparer.OrdinalIgnoreCase);

            // loop thru all people that are NOT part of the same family
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily == false))
            {
                if (!familyPersonState.GroupId.HasValue)
                {
                    // related person not in a family yet
                    Group relatedFamily = newRelatedFamilies.GetValueOrNull(familyPersonState.LastName);
                    if (relatedFamily == null)
                    {
                        relatedFamily             = new Group();
                        relatedFamily.Name        = familyPersonState.LastName + " Family";
                        relatedFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                        // Set the Campus to the Campus of this Kiosk
                        relatedFamily.CampusId = kioskCampusId;

                        newRelatedFamilies.Add(familyPersonState.LastName, relatedFamily);
                        groupService.Add(relatedFamily);
                        saveResult.NewFamilyList.Add(relatedFamily);
                    }

                    rockContext.SaveChanges();

                    familyPersonState.GroupId = relatedFamily.Id;

                    var familyMember = new GroupMember
                    {
                        GroupId           = relatedFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        familyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        familyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(familyMember);
                }

                // ensure there are known relationships between each adult in the primary family to this person that isn't in the primary family
                foreach (var primaryFamilyAdult in editFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.InPrimaryFamily))
                {
                    groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, familyPersonState.ChildRelationshipToAdult);

                    // if this is something other than the CanCheckIn relationship, but is a relationship that should ensure a CanCheckIn relationship, create a CanCheckinRelationship
                    if (groupTypeRoleCanCheckInId.HasValue && familyPersonState.CanCheckIn && groupTypeRoleCanCheckInId != familyPersonState.ChildRelationshipToAdult)
                    {
                        groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, groupTypeRoleCanCheckInId.Value);
                    }
                }
            }

            return(saveResult);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Read(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);
                        if (group != null)
                        {
                            // use the group's grouptype's default group role if a group role wasn't specified
                            groupRoleId = group.GroupType.DefaultGroupRoleId;
                        }
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("Provided group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                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
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Example #26
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroupMember 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 btnSaveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            GroupTypeRole role = new GroupTypeRoleService(rockContext).Get(ddlGroupRole.SelectedValueAsInt() ?? 0);

            var groupMember = groupMemberService.Get(this.CurrentGroupMemberId);

            if (this.CurrentGroupMemberId == 0)
            {
                groupMember = new GroupMember {
                    Id = 0
                };
                groupMember.GroupId = _groupId;

                // check to see if the person is alread a member of the gorup/role
                var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(
                    _groupId, ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0);

                if (existingGroupMember != null)
                {
                    // if so, don't add and show error message
                    var person = new PersonService(rockContext).Get((int)ppGroupMemberPerson.PersonId);

                    nbGroupMemberErrorMessage.Title = "Person Already In Group";
                    nbGroupMemberErrorMessage.Text  = string.Format(
                        "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role.",
                        person.FullName,
                        ddlGroupRole.SelectedItem.Text,
                        role.GroupType.GroupTerm,
                        RockPage.PageId,
                        existingGroupMember.Id);
                    return;
                }
            }

            groupMember.PersonId    = ppGroupMemberPerson.PersonId.Value;
            groupMember.GroupRoleId = role.Id;

            // set their status.  If HideInactiveGroupMemberStatus is True, and they are already Inactive, keep their status as Inactive;
            bool hideGroupMemberInactiveStatus = this.GetAttributeValue("HideInactiveGroupMemberStatus").AsBooleanOrNull() ?? false;
            var  selectedStatus = rblStatus.SelectedValueAsEnumOrNull <GroupMemberStatus>();

            if (!selectedStatus.HasValue)
            {
                if (hideGroupMemberInactiveStatus)
                {
                    selectedStatus = GroupMemberStatus.Inactive;
                }
                else
                {
                    selectedStatus = GroupMemberStatus.Active;
                }
            }

            groupMember.GroupMemberStatus = selectedStatus.Value;

            groupMember.LoadAttributes();

            Rock.Attribute.Helper.GetEditValues(phAttributes, groupMember);

            if (!Page.IsValid)
            {
                return;
            }

            // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvEditGroupMember.IsValid = groupMember.IsValid;

            if (!cvEditGroupMember.IsValid)
            {
                cvEditGroupMember.ErrorMessage = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                return;
            }

            // using WrapTransaction because there are two Saves
            rockContext.WrapTransaction(() =>
            {
                if (groupMember.Id.Equals(0))
                {
                    groupMemberService.Add(groupMember);
                }

                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);
            });

            Group group = new GroupService(rockContext).Get(groupMember.GroupId);

            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
            {
                Rock.Security.Role.Flush(group.Id);
            }

            pnlEditGroupMember.Visible = false;
            pnlGroupView.Visible       = true;
            DisplayViewGroup();
            this.IsEditingGroupMember = false;
        }
Example #27
0
        /// <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)
            {
                AttendanceCode attendanceCode = null;

                bool reuseCodeForFamily             = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeAlphaNumericLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;
                int  securityCodeAlphaLength        = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaLength : 0;
                int  securityCodeNumericLength      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericLength : 0;
                bool securityCodeNumericRandom      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericRandom : true;


                var attendanceCodeService = new AttendanceCodeService(rockContext);
                var attendanceService     = new AttendanceService(rockContext);
                var groupMemberService    = new GroupMemberService(rockContext);
                var personAliasService    = new PersonAliasService(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(securityCodeAlphaNumericLength, securityCodeAlphaLength, securityCodeNumericLength, securityCodeNumericRandom);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GetGroupTypes(true))
                        {
                            foreach (var group in groupType.GetGroups(true))
                            {
                                if (groupType.GroupType.AttendanceRule == AttendanceRule.AddOnCheckIn &&
                                    groupType.GroupType.DefaultGroupRoleId.HasValue &&
                                    !groupMemberService.GetByGroupIdAndPersonId(group.Group.Id, person.Person.Id, true).Any())
                                {
                                    var groupMember = new GroupMember();
                                    groupMember.GroupId     = group.Group.Id;
                                    groupMember.PersonId    = person.Person.Id;
                                    groupMember.GroupRoleId = groupType.GroupType.DefaultGroupRoleId.Value;
                                    groupMemberService.Add(groupMember);
                                }

                                foreach (var location in group.GetLocations(true))
                                {
                                    foreach (var schedule in location.GetSchedules(true))
                                    {
                                        var startDateTime = schedule.CampusCurrentDateTime;

                                        // 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 = attendanceService.AddOrUpdate(primaryAlias.Id, startDateTime.Date, group.Group.Id,
                                                                                           location.Location.Id, schedule.Schedule.Id, location.CampusId,
                                                                                           checkInState.Kiosk.Device.Id, checkInState.CheckIn.SearchType.Id,
                                                                                           checkInState.CheckIn.SearchValue, family.Group.Id, attendanceCode.Id);

                                                attendance.PersonAlias = primaryAlias;
                                            }
                                        }

                                        attendance.DeviceId                 = checkInState.Kiosk.Device.Id;
                                        attendance.SearchTypeValueId        = checkInState.CheckIn.SearchType.Id;
                                        attendance.SearchValue              = checkInState.CheckIn.SearchValue;
                                        attendance.CheckedInByPersonAliasId = checkInState.CheckIn.CheckedInByPersonAliasId;
                                        attendance.SearchResultGroupId      = family.Group.Id;
                                        attendance.AttendanceCodeId         = attendanceCode.Id;
                                        attendance.StartDateTime            = startDateTime;
                                        attendance.EndDateTime              = null;
                                        attendance.DidAttend                = true;
                                        attendance.Note = group.Notes;

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

                rockContext.SaveChanges();
                return(true);
            }

            return(false);
        }
Example #28
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // Get the job setting(s)
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            bool       requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");

            // Counters for displaying results
            int    groupsSynced  = 0;
            int    groupsChanged = 0;
            string groupName     = string.Empty;
            string dataViewName  = string.Empty;
            var    errors        = new List <string>();

            try
            {
                // get groups set to sync
                var activeSyncIds = new List <int>();
                using (var rockContext = new RockContext())
                {
                    activeSyncIds = new GroupSyncService(rockContext)
                                    .Queryable().AsNoTracking()
                                    .Select(x => x.Id)
                                    .ToList();
                }

                foreach (var syncId in activeSyncIds)
                {
                    bool hasSyncChanged = false;

                    // Use a fresh rockContext per syc so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        // increase the timeout just in case the dataview source is slow
                        rockContext.Database.CommandTimeout = 180;
                        rockContext.SourceOfChange          = "Group Sync";

                        // Get the Sync
                        var sync = new GroupSyncService(rockContext)
                                   .Queryable().AsNoTracking()
                                   .FirstOrDefault(s => s.Id == syncId);

                        // Ensure that the group's Sync Data View is a person dataview
                        if (sync != null && sync.SyncDataView.EntityTypeId == EntityTypeCache.Get(typeof(Person)).Id)
                        {
                            List <string> syncErrors = new List <string>();

                            dataViewName = sync.SyncDataView.Name;
                            groupName    = sync.Group.Name;

                            // Get the person id's from the dataview (source)
                            var personService       = new PersonService(rockContext);
                            var parameterExpression = personService.ParameterExpression;
                            var whereExpression     = sync.SyncDataView.GetExpression(personService, parameterExpression, out syncErrors);
                            var sourcePersonIds     = new PersonService(rockContext)
                                                      .Get(parameterExpression, whereExpression)
                                                      .Select(q => q.Id)
                                                      .ToList();

                            // If any error occurred, just skip this sync for now.
                            if (syncErrors.Count > 0)
                            {
                                errors.AddRange(syncErrors);
                                ExceptionLogService.LogException(new Exception(string.Format("An error occurred while trying to GroupSync group '{0}' and data view '{1}' so the sync was skipped. Error: {2}", groupName, dataViewName, String.Join(",", syncErrors))));
                                continue;
                            }

                            // Get the person id's in the group (target)
                            var targetPersonIds = new GroupMemberService(rockContext)
                                                  .Queryable().AsNoTracking()
                                                  .Where(gm => gm.GroupId == sync.GroupId)
                                                  .Select(gm => gm.PersonId)
                                                  .ToList();

                            // Delete people from the group/role that are no longer in the dataview
                            foreach (var personId in targetPersonIds.Where(t => !sourcePersonIds.Contains(t)))
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    // Delete any group members for the role with the person id
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    foreach (var groupMember in groupMemberService
                                             .Queryable()
                                             .Where(m =>
                                                    m.GroupId == sync.GroupId &&
                                                    m.GroupRoleId == sync.GroupTypeRoleId &&
                                                    m.PersonId == personId)
                                             .ToList())
                                    {
                                        groupMemberService.Delete(groupMember);
                                    }

                                    groupMemberContext.SaveChanges();

                                    // If the Group has an exit email, and person has an email address, send them the exit email
                                    if (sync.ExitSystemEmail != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(personId);
                                        if (person.Email.IsNotNullOrWhiteSpace())
                                        {
                                            // Send the exit email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", sync.Group);
                                            mergeFields.Add("Person", person);
                                            var emailMessage = new RockEmailMessage(sync.ExitSystemEmail);
                                            emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                            var emailErrors = new List <string>();
                                            emailMessage.Send(out emailErrors);
                                            errors.AddRange(emailErrors);
                                        }
                                    }
                                }

                                hasSyncChanged = true;
                            }

                            foreach (var personId in sourcePersonIds.Where(s => !targetPersonIds.Contains(s)))
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    // Add new person to the group with the role specified in the sync
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    var newGroupMember     = new GroupMember {
                                        Id = 0
                                    };
                                    newGroupMember.PersonId          = personId;
                                    newGroupMember.GroupId           = sync.GroupId;
                                    newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                    newGroupMember.GroupRoleId       = sync.GroupTypeRoleId;
                                    groupMemberService.Add(newGroupMember);
                                    groupMemberContext.SaveChanges();

                                    // If the Group has a welcome email, and person has an email address, send them the welcome email and possibly create a login
                                    if (sync.WelcomeSystemEmail != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(personId);
                                        if (person.Email.IsNotNullOrWhiteSpace())
                                        {
                                            // If the group is configured to add a user account for anyone added to the group, and person does not yet have an
                                            // account, add one for them.
                                            string newPassword = string.Empty;
                                            bool   createLogin = sync.AddUserAccountsDuringSync;

                                            // Only create a login if requested, no logins exist and we have enough information to generate a username.
                                            if (createLogin && !person.Users.Any() && !string.IsNullOrWhiteSpace(person.NickName) && !string.IsNullOrWhiteSpace(person.LastName))
                                            {
                                                newPassword = System.Web.Security.Membership.GeneratePassword(9, 1);
                                                string username = Rock.Security.Authentication.Database.GenerateUsername(person.NickName, person.LastName);

                                                UserLogin login = UserLoginService.Create(
                                                    groupMemberContext,
                                                    person,
                                                    AuthenticationServiceType.Internal,
                                                    EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                                    username,
                                                    newPassword,
                                                    true,
                                                    requirePasswordReset);
                                            }

                                            // Send the welcome email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", sync.Group);
                                            mergeFields.Add("Person", person);
                                            mergeFields.Add("NewPassword", newPassword);
                                            mergeFields.Add("CreateLogin", createLogin);
                                            var emailMessage = new RockEmailMessage(sync.WelcomeSystemEmail);
                                            emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                            var emailErrors = new List <string>();
                                            emailMessage.Send(out emailErrors);
                                            errors.AddRange(emailErrors);
                                        }
                                    }
                                }

                                hasSyncChanged = true;
                            }

                            // Increment Groups Changed Counter (if people were deleted or added to the group)
                            if (hasSyncChanged)
                            {
                                groupsChanged++;
                            }

                            // Increment the Groups Synced Counter
                            groupsSynced++;
                        }
                    }
                }

                // Format the result message
                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was sync'ed";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were sync'ed", groupsSynced);
                }

                resultMessage += string.Format(" and {0} groups were changed", groupsChanged);

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors: ");
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    resultMessage += errorMessage;
                    throw new Exception(errorMessage);
                }

                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Example #29
0
        /// <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>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState == null)
            {
                return(false);
            }

            AttendanceCode attendanceCode = null;

            bool reuseCodeForFamily             = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
            int  securityCodeAlphaNumericLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;
            int  securityCodeAlphaLength        = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaLength : 0;
            int  securityCodeNumericLength      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericLength : 0;
            bool securityCodeNumericRandom      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericRandom : true;

            bool enablePresence = checkInState.CheckInType != null && checkInState.CheckInType.EnablePresence;

            var attendanceCodeService = new AttendanceCodeService(rockContext);
            var attendanceService     = new AttendanceService(rockContext);
            var groupMemberService    = new GroupMemberService(rockContext);
            var personAliasService    = new PersonAliasService(rockContext);
            var attendanceRecords     = new List <Attendance>();

            AttendanceCheckInSession attendanceCheckInSession = new AttendanceCheckInSession()
            {
                DeviceId        = checkInState.DeviceId,
                ClientIpAddress = RockPage.GetClientIpAddress()
            };

            checkInState.Messages.Clear();

            var family = checkInState.CheckIn.CurrentFamily;

            if (family != null)
            {
                var currentOccurrences = new List <OccurrenceRecord>();
                foreach (var person in family.GetPeople(true))
                {
                    if (reuseCodeForFamily && attendanceCode != null)
                    {
                        person.SecurityCode = attendanceCode.Code;
                    }
                    else
                    {
                        attendanceCode      = AttendanceCodeService.GetNew(securityCodeAlphaNumericLength, securityCodeAlphaLength, securityCodeNumericLength, securityCodeNumericRandom);
                        person.SecurityCode = attendanceCode.Code;
                    }

                    foreach (var groupType in person.GetGroupTypes(true))
                    {
                        foreach (var group in groupType.GetGroups(true))
                        {
                            if (groupType.GroupType.AttendanceRule == AttendanceRule.AddOnCheckIn &&
                                groupType.GroupType.DefaultGroupRoleId.HasValue &&
                                !groupMemberService.GetByGroupIdAndPersonId(group.Group.Id, person.Person.Id, true).Any())
                            {
                                var groupMember = new GroupMember();
                                groupMember.GroupId     = group.Group.Id;
                                groupMember.PersonId    = person.Person.Id;
                                groupMember.GroupRoleId = groupType.GroupType.DefaultGroupRoleId.Value;
                                groupMemberService.Add(groupMember);
                            }

                            foreach (var location in group.GetLocations(true))
                            {
                                bool isCheckedIntoLocation = false;
                                foreach (var schedule in location.GetSchedules(true))
                                {
                                    var startDateTime = schedule.CampusCurrentDateTime;

                                    // If we're enforcing strict location thresholds, then before we create an attendance record
                                    // we need to check the location-schedule's current count.
                                    if (GetAttributeValue(action, AttributeKey.EnforceStrictLocationThreshold).AsBoolean() && location.Location.SoftRoomThreshold.HasValue)
                                    {
                                        EnforceStrictLocationThreshold(action, checkInState, attendanceService, currentOccurrences, person, group, location, schedule, startDateTime);
                                    }

                                    // 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 = attendanceService.AddOrUpdate(
                                                primaryAlias.Id,
                                                startDateTime.Date,
                                                group.Group.Id,
                                                location.Location.Id,
                                                schedule.Schedule.Id,
                                                location.CampusId,
                                                checkInState.Kiosk.Device.Id,
                                                checkInState.CheckIn.SearchType?.Id,
                                                checkInState.CheckIn.SearchValue,
                                                family.Group.Id,
                                                attendanceCode.Id);

                                            attendance.PersonAlias = primaryAlias;
                                        }
                                    }

                                    attendance.AttendanceCheckInSession = attendanceCheckInSession;

                                    attendance.DeviceId                  = checkInState.Kiosk.Device.Id;
                                    attendance.SearchTypeValueId         = checkInState.CheckIn.SearchType?.Id;
                                    attendance.SearchValue               = checkInState.CheckIn.SearchValue;
                                    attendance.CheckedInByPersonAliasId  = checkInState.CheckIn.CheckedInByPersonAliasId;
                                    attendance.SearchResultGroupId       = family.Group.Id;
                                    attendance.AttendanceCodeId          = attendanceCode.Id;
                                    attendance.StartDateTime             = startDateTime;
                                    attendance.EndDateTime               = null;
                                    attendance.CheckedOutByPersonAliasId = null;
                                    attendance.DidAttend                 = true;
                                    attendance.Note        = group.Notes;
                                    attendance.IsFirstTime = person.FirstTime;

                                    /*
                                     *  7/16/2020 - JH
                                     *  If EnablePresence is true for this Check-in configuration, it will be the responsibility of the room
                                     *  attendants to mark a given Person as present, so do not set the 'Present..' property values below.
                                     *  Otherwise, set the values to match those of the Check-in values: the Person checking them in will
                                     *  have simultaneously marked them as present.
                                     *
                                     *  Also, note that we sometimes reuse Attendance records (i.e. the Person was already checked into this
                                     *  schedule/group/location, might have already been checked out, and also might have been previously
                                     *  marked as present). In this case, the same 'Present..' rules apply, but we might need to go so far
                                     *  as to null-out the previously set 'Present..' property values, hence the conditional operators below.
                                     */
                                    attendance.PresentDateTime        = enablePresence ? ( DateTime? )null : startDateTime;
                                    attendance.PresentByPersonAliasId = enablePresence ? null : checkInState.CheckIn.CheckedInByPersonAliasId;

                                    KioskLocationAttendance.AddAttendance(attendance);
                                    isCheckedIntoLocation = true;

                                    // Keep track of attendance (Ids) for use by other actions later in the workflow pipeline
                                    attendanceRecords.Add(attendance);
                                }

                                // If the person was NOT checked into the location for any schedule then remove the location
                                if (!isCheckedIntoLocation)
                                {
                                    group.Locations.Remove(location);
                                }
                            }
                        }
                    }
                }
            }

            if (checkInState.CheckInType.AchievementTypes.Any())
            {
                // Get any achievements that were in-progress *prior* to adding these attendance records
                var configuredAchievementTypeIds    = checkInState.CheckInType.AchievementTypes.Select(a => a.Id).ToList();
                var attendanceRecordsPersonAliasIds = attendanceRecords.Where(a => a.PersonAliasId.HasValue).Select(a => a.PersonAliasId.Value).ToArray();
                var successfullyCompletedAchievementsPriorToSaveChanges = GetSuccessfullyCompletedAchievementAttempts(rockContext, attendanceRecordsPersonAliasIds, configuredAchievementTypeIds);

                rockContext.SaveChanges();

                AchievementAttemptService.AchievementAttemptWithPersonAlias[] achievementAttemptsAfterSaveChanges =
                    GetAchievementAttemptsWithPersonAliasQuery(rockContext, attendanceRecordsPersonAliasIds, configuredAchievementTypeIds).AsNoTracking().ToArray();

                checkInState.CheckIn.SuccessfullyCompletedAchievementsPriorToCheckin = successfullyCompletedAchievementsPriorToSaveChanges;
                checkInState.CheckIn.AchievementsStateAfterCheckin = achievementAttemptsAfterSaveChanges;
            }
            else
            {
                rockContext.SaveChanges();
            }

            // Now that the records are persisted, take the Ids and save them to the temp CheckInFamliy object
            family.AttendanceIds = attendanceRecords.Select(a => a.Id).ToList();
            family.AttendanceCheckinSessionGuid = attendanceCheckInSession.Guid;
            attendanceRecords = null;

            return(true);
        }
Example #30
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick(object sender, EventArgs e)
        {
            var rockContext  = new RockContext();
            var groupService = new GroupService(rockContext);

            var group = groupService.Get(ddlGroup.SelectedValue.AsInteger());

            if (group == null)
            {
                nbModalDetailsMessage.Title   = "Please select a Group";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            var personContext      = ContextEntity <Person>();
            var groupMemberService = new GroupMemberService(rockContext);

            if (groupMemberService.Queryable().Any(a => a.PersonId == personContext.Id && a.GroupId == group.Id))
            {
                nbModalDetailsMessage.Title   = "Member already added to selected Group";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            var roleId = group.GroupType.DefaultGroupRoleId;

            if (roleId == null)
            {
                nbModalDetailsMessage.Title   = "No default role for particular group is assigned";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            if (!(group.IsAuthorized(Authorization.EDIT, this.CurrentPerson) || group.IsAuthorized(Authorization.MANAGE_MEMBERS, this.CurrentPerson)))
            {
                // shouldn't happen because GroupList is limited to EDIT and MANAGE_MEMBERs, but just in case
                nbModalDetailsMessage.Title   = "You are not authorized to add members to this group";
                nbModalDetailsMessage.Visible = true;
                return;
            }

            GroupMember groupMember = new GroupMember {
                Id = 0
            };

            groupMember.GroupId           = group.Id;
            groupMember.PersonId          = personContext.Id;
            groupMember.GroupRoleId       = roleId.Value;
            groupMember.GroupMemberStatus = GroupMemberStatus.Active;

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

            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
            {
                Rock.Security.Role.Flush(group.Id);
            }

            modalDetails.Hide();
            BindFilter();
            BindGrid();
        }