GetByGroupIdAndPersonId() public method

Returns a collection of Rock.Model.GroupMember">GroupMembers by the Id of the Rock.Model.Person.
public GetByGroupIdAndPersonId ( int groupId, int personId, bool includeDeceased = false ) : IQueryable
groupId int An representing the Id of the to search by.
personId int An representing the Id of the to search by.
includeDeceased bool A value indicating if deceased GroupMembers should be included. If true /// deceased group members will be included, if false deceased group members will not be included. This parameter defaults to false.
return IQueryable
Esempio n. 1
0
        /// <summary>
        /// Validates the group membership.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ValidateGroupMembership(RockContext rockContext, out string errorMessage)
        {
            errorMessage = string.Empty;
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            var groupRole = this.GroupRole ?? new GroupTypeRoleService(rockContext).Get(this.GroupRoleId);

            // check to see if the person is alread a member of the gorup/role
            var existingGroupMembership = groupMemberService.GetByGroupIdAndPersonId(this.GroupId, this.PersonId);

            if (existingGroupMembership.Any(a => a.GroupRoleId == this.GroupRoleId && a.Id != this.Id))
            {
                var person = this.Person ?? new PersonService(rockContext).Get(this.PersonId);

                errorMessage = string.Format(
                    "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role",
                    person,
                    groupRole.Name,
                    groupRole.GroupType.GroupTerm);

                return(false);
            }

            var databaseRecord = existingGroupMembership.FirstOrDefault(a => a.Id == this.Id);

            int memberCountInRole = new GroupMemberService(rockContext).Queryable()
                                    .Where(m =>
                                           m.GroupId == this.GroupId &&
                                           m.GroupRoleId == this.GroupRoleId &&
                                           m.GroupMemberStatus == GroupMemberStatus.Active)
                                    .Count();

            bool roleMembershipAboveMax = false;

            // if adding new active group member..
            if (this.Id.Equals(0) && this.GroupMemberStatus == GroupMemberStatus.Active)
            {
                // verify that active count has not exceeded the max
                if (groupRole.MaxCount != null && (memberCountInRole + 1) > groupRole.MaxCount)
                {
                    roleMembershipAboveMax = true;
                }
            }
            else if (this.Id > 0 && (this.GroupRoleId != databaseRecord.GroupRoleId || this.GroupMemberStatus != databaseRecord.GroupMemberStatus) &&
                     this.GroupMemberStatus == GroupMemberStatus.Active)
            {
                // if existing group member changing role or status..
                // verify that active count has not exceeded the max
                if (groupRole.MaxCount != null && (memberCountInRole + 1) > groupRole.MaxCount)
                {
                    roleMembershipAboveMax = true;
                }
            }

            // throw error if above max.. do not proceed
            if (roleMembershipAboveMax)
            {
                errorMessage = string.Format(
                    "The number of {0} for this {1} is at or above its maximum allowed limit of {2:N0} active {3}.",
                    groupRole.Name.Pluralize(),
                    groupRole.GroupType.GroupTerm,
                    groupRole.MaxCount,
                    groupRole.GroupType.GroupMemberTerm.Pluralize(groupRole.MaxCount == 1));
                return(false);
            }

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

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

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

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

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

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

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

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

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

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

                                }
                            }
                        }
                    }
                }

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

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

            mdMoveRegistration.Hide();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Set Last Sunday Date
            DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
            SundayDate = dt.ToShortDateString();

            if (!Page.IsPostBack)
            {
                //Get Attributes
                FiscalYearStartDate = GetAttributeValue("FiscalYearStartDate").ToString();

                //Generate Campus List
                string[] eventList = {"All Org", "Canton Campus", "Coshocton Campus", "Dover Campus", "Millersburg Campus", "Wooster Campus"};
                cpCampus.DataSource = eventList;
                cpCampus.DataBind();

                PersonService personService = new PersonService(rockContext);
                GroupService groupService = new GroupService(rockContext);
                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                var personObject = personService.Get(CurrentPerson.Guid);

                 //Is Person in Akron Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74786, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 5;
                    cpCampus.SelectedValue = "Akron Campus";
                    SelectedCampus = "Akron Campus";
                }
                //Is Person in Canton Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74787, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 2;
                    cpCampus.SelectedValue = "Canton Campus";
                    SelectedCampus = "Canton Campus";
                }
                //Is Person in Coshocton Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74788, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 3;
                    cpCampus.SelectedValue = "Coshocton Campus";
                    SelectedCampus = "Coshocton Campus";
                }
                //Is Person in Dover Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74789, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 1;
                    cpCampus.SelectedValue = "Dover Campus";
                    SelectedCampus = "Dover Campus";
                }
                //Is Person in Millersburg Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74790, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 4;
                    cpCampus.SelectedValue = "Millersburg Campus";
                    SelectedCampus = "Millersburg Campus";
                }
                //Is Person in Wooster Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74791, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 6;
                    cpCampus.SelectedValue = "Wooster Campus";
                    SelectedCampus = "Wooster Campus";
                }
                //Is Person in Central?
                if (groupMemberService.GetByGroupIdAndPersonId(74785, (int)CurrentPersonId).Any() == true)
                {
                    cpCampus.SelectedValue = "All Org";
                    SelectedCampus = "All Org";
                    SelectedCampusId = 0;
                }

                sMonth = DateTime.Now.ToString("MM");

                switch (sMonth)
                {
                    case "09":
                        CurrentMonthInFiscalYear = 1;
                        GoalOffsetMultiplier = .083M;
                        SecondaryGoalOffsetMultiplier = .89M;
                        break;
                    case "10":
                        CurrentMonthInFiscalYear = 2;
                        GoalOffsetMultiplier = .167M;
                        SecondaryGoalOffsetMultiplier = .90M;
                        break;
                    case "11":
                        CurrentMonthInFiscalYear = 3;
                        GoalOffsetMultiplier = .25M;
                        SecondaryGoalOffsetMultiplier = .91M;
                        break;
                    case "12":
                        CurrentMonthInFiscalYear = 4;
                        GoalOffsetMultiplier = .333M;
                        SecondaryGoalOffsetMultiplier = .92M;
                        break;
                    case "01":
                        CurrentMonthInFiscalYear = 5;
                        GoalOffsetMultiplier = .417M;
                        SecondaryGoalOffsetMultiplier = .93M;
                        break;
                    case "02":
                        CurrentMonthInFiscalYear = 6;
                        GoalOffsetMultiplier = .5M;
                        SecondaryGoalOffsetMultiplier = .94M;
                        break;
                    case "03":
                        CurrentMonthInFiscalYear = 7;
                        GoalOffsetMultiplier = .583M;
                        SecondaryGoalOffsetMultiplier = .95M;
                        break;
                    case "04":
                        CurrentMonthInFiscalYear = 8;
                        GoalOffsetMultiplier = .667M;
                        SecondaryGoalOffsetMultiplier = .96M;
                        break;
                    case "05":
                        CurrentMonthInFiscalYear = 9;
                        GoalOffsetMultiplier = .75M;
                        SecondaryGoalOffsetMultiplier = .97M;
                        break;
                    case "06":
                        CurrentMonthInFiscalYear = 10;
                        GoalOffsetMultiplier = .883M;
                        SecondaryGoalOffsetMultiplier = .98M;
                        break;
                    case "07":
                        CurrentMonthInFiscalYear = 11;
                        GoalOffsetMultiplier = .917M;
                        SecondaryGoalOffsetMultiplier = .99M;
                        break;
                    case "08":
                        CurrentMonthInFiscalYear = 12;
                        GoalOffsetMultiplier = 1;
                        SecondaryGoalOffsetMultiplier = 1;
                        break;
                }

            }

                DoSQL();
        }
Esempio n. 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            FiscalYearStartDate = GetAttributeValue("FiscalYearStartDate");

            //Set Last Sunday Date
            DateTime now = DateTime.Now;
            DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
            SundayDate = dt.ToShortDateString();
            SundayDateSQLFormatted = dt.Date.ToString("yyyy-MM-dd");

            DateTime lastTuesday = DateTime.Now.AddDays(-1);
            while (lastTuesday.DayOfWeek != DayOfWeek.Wednesday)
                lastTuesday = lastTuesday.AddDays(-1);

            DateTime lastWednesday = DateTime.Now.AddDays(-1);
            while (lastWednesday.DayOfWeek != DayOfWeek.Wednesday)
                lastWednesday = lastWednesday.AddDays(-1);

            FinancialStartDate = lastTuesday.AddDays(-7).ToString("yyyy-MM-dd");
            FinancialEndDate = lastWednesday.ToString("yyyy-MM-dd");

            FinancialStartDateLastWeek = lastTuesday.AddDays(-14).ToString("yyyy-MM-dd");
            FinancialEndDateLastWeek = lastWednesday.AddDays(-7).ToString("yyyy-MM-dd");

            sMonth = DateTime.Now.ToString("MM");

            switch (sMonth)
            {
                case "09":
                    CurrentMonthInFiscalYear = 1;
                    GoalOffsetMultiplier = .083M;
                    SecondaryGoalOffsetMultiplier = .89M;
                    break;
                case "10":
                    CurrentMonthInFiscalYear = 2;
                    GoalOffsetMultiplier = .167M;
                    SecondaryGoalOffsetMultiplier = .90M;
                    break;
                case "11":
                    CurrentMonthInFiscalYear = 3;
                    GoalOffsetMultiplier = .25M;
                    SecondaryGoalOffsetMultiplier = .91M;
                    break;
                case "12":
                    CurrentMonthInFiscalYear = 4;
                    GoalOffsetMultiplier =.333M;
                    SecondaryGoalOffsetMultiplier = .92M;
                    break;
                case "01":
                    CurrentMonthInFiscalYear = 5;
                    GoalOffsetMultiplier = .417M;
                    SecondaryGoalOffsetMultiplier = .93M;
                    break;
                case "02":
                    CurrentMonthInFiscalYear = 6;
                    GoalOffsetMultiplier = .5M;
                    SecondaryGoalOffsetMultiplier = .94M;
                    break;
                case "03":
                    CurrentMonthInFiscalYear = 7;
                    GoalOffsetMultiplier = .583M;
                    SecondaryGoalOffsetMultiplier = .95M;
                    break;
                case "04":
                    CurrentMonthInFiscalYear = 8;
                    GoalOffsetMultiplier =.667M;
                    SecondaryGoalOffsetMultiplier = .96M;
                    break;
                case "05":
                    CurrentMonthInFiscalYear = 9;
                    GoalOffsetMultiplier = .75M;
                    SecondaryGoalOffsetMultiplier = .97M;
                    break;
                case "06":
                    CurrentMonthInFiscalYear = 10;
                    GoalOffsetMultiplier = .883M;
                    SecondaryGoalOffsetMultiplier = .98M;
                    break;
                case "07":
                    CurrentMonthInFiscalYear = 11;
                    GoalOffsetMultiplier = .917M;
                    SecondaryGoalOffsetMultiplier = .99M;
                    break;
                case "08":
                    CurrentMonthInFiscalYear = 12;
                    GoalOffsetMultiplier = 1;
                    SecondaryGoalOffsetMultiplier = 1;
                    break;
            }

            if (!Page.IsPostBack)
            {
                //Get Attributes
                FiscalYearStartDate = GetAttributeValue("FiscalYearStartDate").ToString();

                //Generate Campus List
                string[] campusList = {"All Org", "Canton Campus", "Coshocton Campus", "Dover Campus", "Millersburg Campus", "Wooster Campus"};
                cpCampus.DataSource = campusList;
                cpCampus.DataBind();

                //Get the campus of the currently logged in person
                //PersonService personService = new PersonService(rockContext);
                //var personObject = personService.Get(CurrentPerson.Guid);
                //var campus = personObject.GetFamilies().FirstOrDefault().Campus ?? new Campus();
                //SelectedCampusId = campus.Id;
                //cpCampus.SelectedValue = campus.Name;
                //SelectedCampus = campus.Name;

                PersonService personService = new PersonService(rockContext);
                GroupService groupService = new GroupService(rockContext);
                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                var personObject = personService.Get(CurrentPerson.Guid);

                //Is Person in Akron Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74786, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 5;
                    cpCampus.SelectedValue = "Akron Campus";
                    SelectedCampus = "Akron Campus";
                }
                //Is Person in Canton Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74787, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 2;
                    cpCampus.SelectedValue = "Canton Campus";
                    SelectedCampus = "Canton Campus";
                }
                //Is Person in Coshocton Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74788, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 3;
                    cpCampus.SelectedValue = "Coshocton Campus";
                    SelectedCampus = "Coshocton Campus";
                }
                //Is Person in Dover Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74789, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 1;
                    cpCampus.SelectedValue = "Dover Campus";
                    SelectedCampus = "Dover Campus";
                }
                //Is Person in Millersburg Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74790, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 4;
                    cpCampus.SelectedValue = "Millersburg Campus";
                    SelectedCampus = "Millersburg Campus";
                }
                //Is Person in Wooster Campus?
                if (groupMemberService.GetByGroupIdAndPersonId(74791, (int)CurrentPersonId).Any() == true)
                {
                    SelectedCampusId = 6;
                    cpCampus.SelectedValue = "Wooster Campus";
                    SelectedCampus = "Wooster Campus";
                }
                //Is Person in Central?
                if (groupMemberService.GetByGroupIdAndPersonId(74785, (int)CurrentPersonId).Any() == true)
                {
                    cpCampus.SelectedValue = "All Org";
                    SelectedCampus = "All Org";
                    SelectedCampusId = 0;
                }

            }

            DoSQL();
        }
        /// <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;
                DateTime startDateTime = RockDateTime.Now;

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

                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( securityCodeLength );
                            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 ) )
                                    {
                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get( startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id );
                                        if ( attendance == null )
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias( person.Person.Id );
                                            if ( primaryAlias != null )
                                            {
                                                attendance = rockContext.Attendances.Create();
                                                attendance.LocationId = location.Location.Id;
                                                attendance.CampusId = location.CampusId;
                                                attendance.ScheduleId = schedule.Schedule.Id;
                                                attendance.GroupId = group.Group.Id;
                                                attendance.PersonAlias = primaryAlias;
                                                attendance.PersonAliasId = primaryAlias.Id;
                                                attendance.DeviceId = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendance.LoadAttributes();
                                                attendance.SetAttributeValue( "SearchValue", checkInState.CheckIn.SearchValue );
                                                attendance.SetAttributeValue( "SearchResultGroupId", family.Group.Id );
                                                attendanceService.Add( attendance );

                                            }
                                        }

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

                                        rockContext.SaveChanges();
                                        attendance.SaveAttributeValues( rockContext );

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

                rockContext.SaveChanges();

                return true;
            }

            return false;
        }
Esempio n. 6
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <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( Model.WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            var checkInState = GetCheckInState( entity, out errorMessages );
            if ( checkInState != null )
            {
                DateTime startDateTime = DateTime.Now;

                int securityCodeLength = 3;
                if ( !int.TryParse( GetAttributeValue( action, "SecurityCodeLength" ), out securityCodeLength ) )
                {
                    securityCodeLength = 3;
                }

                using ( var uow = new Rock.Data.UnitOfWorkScope() )
                {
                    var attendanceCodeService = new AttendanceCodeService();
                    var attendanceService = new AttendanceService();
                    var groupMemberService = new GroupMemberService();

                    foreach ( var family in checkInState.CheckIn.Families.Where( f => f.Selected ) )
                    {
                        foreach ( var person in family.People.Where( p => p.Selected ) )
                        {
                            var attendanceCode = attendanceCodeService.GetNew( securityCodeLength );
                            person.SecurityCode = attendanceCode.Code;

                            foreach ( var groupType in person.GroupTypes.Where( g => g.Selected ) )
                            {
                                foreach ( var group in groupType.Groups.Where( g => g.Selected ) )
                                {
                                    foreach ( var location in group.Locations.Where( l => l.Selected ) )
                                    {
                                        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, null );
                                            groupMemberService.Save( groupMember, null );
                                        }

                                        foreach ( var schedule in location.Schedules.Where( s => s.Selected ) )
                                        {
                                            // 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 )
                                            {
                                                attendance = ((Rock.Data.RockContext)uow.DbContext).Attendances.Create();
                                                attendance.LocationId = location.Location.Id;
                                                attendance.ScheduleId = schedule.Schedule.Id;
                                                attendance.GroupId = group.Group.Id;
                                                attendance.PersonId = person.Person.Id;
                                                attendance.DeviceId = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendanceService.Add( attendance, null );
                                            }

                                            attendance.AttendanceCodeId = attendanceCode.Id;
                                            attendance.StartDateTime = startDateTime;
                                            attendance.EndDateTime = null;
                                            attendance.DidAttend = true;
                                            attendanceService.Save( attendance, null );

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

                return true;

            }

            return false;
        }
        /// <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 = false;
                if ( bool.TryParse( GetAttributeValue( action, "ReuseCodeForFamily" ), out reuseCodeForFamily ) && reuseCodeForFamily )
                {
                    reuseCodeForFamily = true;
                }

                DateTime startDateTime = RockDateTime.Now;

                int securityCodeLength = 3;
                if ( !int.TryParse( GetAttributeValue( action, "SecurityCodeLength" ), out securityCodeLength ) )
                {
                    securityCodeLength = 3;
                }

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

                foreach ( var family in checkInState.CheckIn.Families.Where( f => f.Selected ) )
                {
                    foreach ( var person in family.People.Where( p => p.Selected ) )
                    {
                        if ( reuseCodeForFamily && attendanceCode != null )
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode = AttendanceCodeService.GetNew( securityCodeLength );
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach ( var groupType in person.GroupTypes.Where( g => g.Selected ) )
                        {
                            foreach ( var group in groupType.Groups.Where( g => g.Selected ) )
                            {
                                foreach ( var location in group.Locations.Where( l => l.Selected ) )
                                {
                                    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 schedule in location.Schedules.Where( s => s.Selected ) )
                                    {
                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get( startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id );
                                        if ( attendance == null )
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias( person.Person.Id );
                                            if ( primaryAlias != null )
                                            {
                                                attendance = rockContext.Attendances.Create();
                                                attendance.LocationId = location.Location.Id;
                                                attendance.CampusId = location.CampuId;
                                                attendance.ScheduleId = schedule.Schedule.Id;
                                                attendance.GroupId = group.Group.Id;
                                                attendance.PersonAlias = primaryAlias;
                                                attendance.PersonAliasId = primaryAlias.Id;
                                                attendance.DeviceId = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendanceService.Add( attendance );
                                            }
                                        }

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

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

                rockContext.SaveChanges();
                return true;
            }

            return false;
        }
Esempio n. 8
0
        /// <summary>
        /// Validates the group membership.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ValidateGroupMembership(RockContext rockContext, out string errorMessage)
        {
            errorMessage = string.Empty;
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            var groupRole = this.GroupRole ?? new GroupTypeRoleService(rockContext).Get(this.GroupRoleId);

            // check to see if the person is already a member of the group/role
            var existingGroupMembership = groupMemberService.GetByGroupIdAndPersonId(this.GroupId, this.PersonId);

            if (existingGroupMembership.Any(a => a.GroupRoleId == this.GroupRoleId && a.Id != this.Id))
            {
                var person = this.Person ?? new PersonService(rockContext).Get(this.PersonId);

                errorMessage = string.Format(
                    "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role",
                    person,
                    groupRole.Name,
                    groupRole.GroupType.GroupTerm);

                return(false);
            }

            var databaseRecord = existingGroupMembership.FirstOrDefault(a => a.Id == this.Id);

            int memberCountInRole = new GroupMemberService(rockContext).Queryable()
                                    .Where(m =>
                                           m.GroupId == this.GroupId &&
                                           m.GroupRoleId == this.GroupRoleId &&
                                           m.GroupMemberStatus == GroupMemberStatus.Active)
                                    .Count();

            bool roleMembershipAboveMax = false;

            // if adding new active group member..
            if (this.Id.Equals(0) && this.GroupMemberStatus == GroupMemberStatus.Active)
            {
                // verify that active count has not exceeded the max
                if (groupRole.MaxCount != null && (memberCountInRole + 1) > groupRole.MaxCount)
                {
                    roleMembershipAboveMax = true;
                }
            }
            else if (databaseRecord != null && this.Id > 0 && (this.GroupRoleId != databaseRecord.GroupRoleId || this.GroupMemberStatus != databaseRecord.GroupMemberStatus) &&
                     this.GroupMemberStatus == GroupMemberStatus.Active)
            {
                // if existing group member changing role or status..
                // verify that active count has not exceeded the max
                if (groupRole.MaxCount != null && (memberCountInRole + 1) > groupRole.MaxCount)
                {
                    roleMembershipAboveMax = true;
                }
            }

            // throw error if above max.. do not proceed
            if (roleMembershipAboveMax)
            {
                errorMessage = string.Format(
                    "The number of {0} for this {1} is at or above its maximum allowed limit of {2:N0} active {3}.",
                    groupRole.Name.Pluralize(),
                    groupRole.GroupType.GroupTerm,
                    groupRole.MaxCount,
                    groupRole.GroupType.GroupMemberTerm.Pluralize(groupRole.MaxCount == 1));
                return(false);
            }

            // if the GroupMember is getting Added (or if Person or Role is different), and if this Group has requirements that must be met before the person is added, check those
            if (this.IsNewOrChangedGroupMember(rockContext))
            {
                var group = this.Group ?? new GroupService(rockContext).Get(this.GroupId);
                if (group.MustMeetRequirementsToAddMember ?? false)
                {
                    var requirementStatuses = group.PersonMeetsGroupRequirements(this.PersonId, this.GroupRoleId);

                    if (requirementStatuses.Any(a => a.MeetsGroupRequirement == MeetsGroupRequirement.NotMet))
                    {
                        // deny if any of the non-manual requirements are not met
                        errorMessage = "This person does not meet the following requirements for this group: "
                                       + requirementStatuses.Where(a => a.MeetsGroupRequirement == MeetsGroupRequirement.NotMet)
                                       .Select(a => string.Format("{0}", a.GroupRequirement.GroupRequirementType))
                                       .ToList().AsDelimited(", ");

                        return(false);
                    }
                }
            }

            return(true);
        }