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);
        }
Пример #2
0
        public void RenderPage()
        {
            var                   pairs                 = GetAttributeValue("GroupIds").ToKeyValuePairList();
            RockContext           rockContext           = new RockContext();
            GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            List <GroupMember>    members               = new List <GroupMember>();

            foreach (var pair in pairs)
            {
                var volunteerId = pair.Key.AsInteger();
                var volunteers  = groupMemberService.GetByGroupIdAndPersonId(volunteerId, CurrentPerson.Id);
                foreach (var volunteer in volunteers)
                {
                    //Add the volunteer and any other volunteers
                    members.Add(volunteer);
                    volunteer.LoadAttributes();
                    var campGroupName   = volunteer.GetAttributeValue(GetAttributeValue("VolunteerGroupKey"));
                    var otherVolunteers = groupMemberService.GetByGroupId(volunteer.GroupId);
                    var volunterGroupAttributeValues = attributeValueService.GetByAttributeId(volunteer.Attributes[GetAttributeValue("VolunteerGroupKey")].Id).ToList();

                    foreach (var otherVolunteer in otherVolunteers)
                    {
                        if (volunterGroupAttributeValues.Where(av => av.EntityId == otherVolunteer.Id && av.Value == campGroupName).Any())
                        {
                            members.Add(otherVolunteer);
                        }
                    }

                    //Now add matching students
                    var students = groupMemberService.GetByGroupId((( string )pair.Value).AsInteger());
                    if (students.Any())
                    {
                        var firstStudent = students.FirstOrDefault();
                        firstStudent.LoadAttributes();
                        var studentGroupAttributeValues = attributeValueService.GetByAttributeId(firstStudent.Attributes[GetAttributeValue("StudentGroupKey")].Id).ToList();
                        foreach (var student in students)
                        {
                            if (studentGroupAttributeValues.Where(av => av.EntityId == student.Id && av.Value == campGroupName).Any())
                            {
                                members.Add(student);
                            }
                        }
                    }
                }
            }
            members = members.DistinctBy(gm => gm.PersonId).ToList();
            var enabledCommands = GetAttributeValue("EnabledLavaCommands");
            var mergeObjects    = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson);

            mergeObjects.Add("GroupMembers", members);
            ltOutput.Text = GetAttributeValue("Lava").ResolveMergeFields(mergeObjects, enabledCommands);
        }
        private void Unsubscribe(int groupId)
        {
            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            var groupMembers = groupMemberService.GetByGroupIdAndPersonId(groupId, Person.Id).ToList();

            foreach (var member in groupMembers)
            {
                member.GroupMemberStatus = GroupMemberStatus.Inactive;
                CommunicationMembership.RemoveAll(m => m.GroupId == groupId);
            }

            rockContext.SaveChanges();
            SaveViewState();
            BindGroups(true);
        }
        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);
        }
Пример #5
0
        public static Person TestPin(RockContext rockContext, string pin)
        {
            UserLoginService   userLoginService   = new UserLoginService(rockContext);
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
            var user = userLoginService.GetByUserName(pin);

            if (user != null)
            {
                var personId    = user.PersonId ?? 0;
                var groupMember = groupMemberService.GetByGroupIdAndPersonId(allowedGroupId, personId).ToList();
                if (groupMember.Any())
                {
                    return(user.Person);
                }
            }
            return(null);
        }
Пример #6
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, Rock.Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var isMobile          = GetAttributeValue(action, "IsMobile").AsBoolean();
            var mobileDidAttendId = DefinedValueCache.Get(Constants.DEFINED_VALUE_MOBILE_DID_ATTEND).Id;
            var mobileNotAttendId = DefinedValueCache.Get(Constants.DEFINED_VALUE_MOBILE_NOT_ATTEND).Id;

            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                KioskService kioskService = new KioskService(rockContext);
                var          kioskTypeId  = kioskService.GetByClientName(checkInState.Kiosk.Device.Name).KioskTypeId;
                var          kioskType    = KioskTypeCache.Get(kioskTypeId.Value);
                var          campusId     = kioskType.CampusId;
                if (campusId == null)
                {
                    var compatableKioskType = KioskTypeCache.All().Where(kt => kt.CampusId.HasValue && kt.CheckinTemplateId == kioskType.CheckinTemplateId).FirstOrDefault();
                    if (compatableKioskType != null)
                    {
                        campusId = compatableKioskType.CampusId;
                    }
                    else
                    {
                        campusId = 0;
                    }
                }

                campusId = GetCampusOrFamilyCampusId(campusId, checkInState.CheckIn.CurrentFamily.Group.CampusId);


                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = Rock.RockDateTime.Now;
                DateTime       today          = startDateTime.Date;
                DateTime       tomorrow       = startDateTime.AddDays(1);

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

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

                //This list is just for mobile check-in
                List <Attendance> attendances = new List <Attendance>();

                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))
                                    {
                                        var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                        if (primaryAlias != null)
                                        {
                                            int groupId = ActualGroupId(group.Group);
                                            // If a like attendance service exists close it before creating another one.
                                            var oldAttendance = attendanceService.Queryable()
                                                                .Where(a =>
                                                                       a.StartDateTime >= today &&
                                                                       a.StartDateTime < tomorrow &&
                                                                       a.Occurrence.LocationId == location.Location.Id &&
                                                                       a.Occurrence.ScheduleId == schedule.Schedule.Id &&
                                                                       a.Occurrence.GroupId == groupId &&
                                                                       a.PersonAlias.PersonId == person.Person.Id)
                                                                .FirstOrDefault();

                                            if (oldAttendance != null)
                                            {
                                                oldAttendance.EndDateTime = Rock.RockDateTime.Now;
                                                oldAttendance.DidAttend   = false;
                                            }
                                            var attendance = attendanceService.AddOrUpdate(primaryAlias.Id, startDateTime.Date, groupId,
                                                                                           location.Location.Id, schedule.Schedule.Id, campusId ?? location.CampusId,
                                                                                           checkInState.Kiosk.Device.Id, checkInState.CheckIn.SearchType.Id,
                                                                                           checkInState.CheckIn.SearchValue, family.Group.Id, attendanceCode.Id);

                                            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.CreatedDateTime          = startDateTime;
                                            attendance.StartDateTime            = startDateTime;
                                            attendance.EndDateTime              = null;
                                            attendance.Note      = group.Notes;
                                            attendance.DidAttend = isMobile ? false : groupType.GroupType.GetAttributeValue("SetDidAttend").AsBoolean();
                                            if (isMobile)
                                            {
                                                if (groupType.GroupType.GetAttributeValue("SetDidAttend").AsBoolean())
                                                {
                                                    attendance.QualifierValueId = mobileDidAttendId;
                                                }
                                                else
                                                {
                                                    attendance.QualifierValueId = mobileNotAttendId;
                                                }
                                            }
                                            ;

                                            attendanceService.Add(attendance);
                                            attendances.Add(attendance);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (isMobile)
                {
                    var alreadyExistingMobileCheckin = MobileCheckinRecordCache.GetActiveByFamilyGroupId(checkInState.CheckIn.CurrentFamily.Group.Id);
                    if (alreadyExistingMobileCheckin != null)
                    {
                        //This should never run, it's just in case. Each family should only have 1 mobile check-in reservation.
                        MobileCheckinRecordCache.CancelReservation(alreadyExistingMobileCheckin, true);
                    }

                    campusId = RollUpToParentCampus(campusId);

                    MobileCheckinRecordService mobileCheckinRecordService = new MobileCheckinRecordService(rockContext);
                    var mobileCheckinRecord = new MobileCheckinRecord
                    {
                        AccessKey             = "MCR" + Guid.NewGuid().ToString("N").Substring(0, 12),
                        ReservedUntilDateTime = Rock.RockDateTime.Now.AddMinutes(kioskType.MinutesValid ?? 10),
                        ExpirationDateTime    = Rock.RockDateTime.Now.AddMinutes((kioskType.MinutesValid ?? 10) + (kioskType.GraceMinutes ?? 60)),
                        UserName      = checkInState.CheckIn.SearchValue,
                        FamilyGroupId = checkInState.CheckIn.CurrentFamily.Group.Id,
                        CampusId      = campusId.Value
                    };

                    foreach (var attendance in attendances)
                    {
                        mobileCheckinRecord.Attendances.Add(attendance);
                    }

                    mobileCheckinRecordService.Add(mobileCheckinRecord);
                }

                rockContext.SaveChanges();
                foreach (var attendance in attendances)
                {
                    AttendanceCache.AddOrUpdate(attendance);
                }
                return(true);
            }
            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            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, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);
            var matrixAttributeMedicationKey   = GetAttributeValue(action, "MatrixAttributeMedicationKey");
            var matrixAttributeInstructionsKey = GetAttributeValue(action, "MatrixAttributeInstructionsKey");
            var matrixAttributeScheduleKey     = GetAttributeValue(action, "MatrixAttributeScheduleKey");

            AttributeMatrixService attributeMatrixService = new AttributeMatrixService(rockContext);
            GroupMemberService     groupMemberService     = new GroupMemberService(rockContext);

            if (checkInState != null)
            {
                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

                    var people = family.GetPeople(true);
                    foreach (var person in people.Where(p => p.Selected))
                    {
                        foreach (var groupType in person.GroupTypes)
                        {
                            groupType.Labels = new List <CheckInLabel>();


                            foreach (var group in groupType.Groups)
                            {
                                List <string> medicationText   = (( string )GetAttributeValue(action, "MedicationText")).Split(',').ToList();
                                List <string> instructionsText = (( string )GetAttributeValue(action, "InstructionsText")).Split(',').ToList();

                                List <MedInfo> medInfos = new List <MedInfo>();
                                if (medicationText.Count == instructionsText.Count)
                                {
                                    for (int i = 0; i < medicationText.Count; i++)
                                    {
                                        medInfos.Add(new MedInfo {
                                            Medication = medicationText[i], Instructions = instructionsText[i]
                                        });
                                    }
                                }

                                group.Group.LoadAttributes();
                                var groupGuid         = group.Group.GetAttributeValue(GetAttributeValue(action, "GroupAttributeKey"));
                                var registrationGroup = new GroupService(rockContext).Get(groupGuid.AsGuid());
                                if (registrationGroup == null)
                                {
                                    continue;
                                }

                                var groupMember = groupMemberService.GetByGroupIdAndPersonId(registrationGroup.Id, person.Person.Id).FirstOrDefault();

                                var medicationKey    = GetAttributeValue(action, "MatrixAttributeKey");
                                var medicationMatrix = person.Person.GetAttributeValue(medicationKey);


                                var attributeMatrix = attributeMatrixService.Get(medicationMatrix.AsGuid());

                                var labelCache = KioskLabel.Get(new Guid(GetAttributeValue(action, "MedicationLabel")));

                                //Set up merge fields so we can use the lava from the merge fields
                                var mergeObjects = new Dictionary <string, object>();
                                foreach (var keyValue in commonMergeFields)
                                {
                                    mergeObjects.Add(keyValue.Key, keyValue.Value);
                                }

                                mergeObjects.Add("RegistrationGroup", registrationGroup);
                                mergeObjects.Add("RegistrationGroupMember", groupMember);
                                mergeObjects.Add("Group", group);
                                mergeObjects.Add("Person", person);
                                mergeObjects.Add("People", people);
                                mergeObjects.Add("GroupType", groupType);

                                if (attributeMatrix == null || attributeMatrix.AttributeMatrixItems.Count == 0)
                                {
                                    // Add a No Medication Information label for anyone without data
                                    var checkInLabel = new CheckInLabel(labelCache, mergeObjects);

                                    var index = 0;
                                    foreach (string mergeFieldText in medicationText)
                                    {
                                        checkInLabel.MergeFields.Add(mergeFieldText, index == 0 ? "No Medication Information Found" : "");
                                        checkInLabel.MergeFields.Add(instructionsText[index], "");
                                        index++;
                                    }
                                    addLabel(checkInLabel, checkInState, groupType, group, rockContext);
                                }
                                else
                                {
                                    var items = attributeMatrix.AttributeMatrixItems.ToList();
                                    var index = 0;

                                    while (index < items.Count)
                                    {
                                        var checkInLabel = new CheckInLabel(labelCache, mergeObjects);

                                        foreach (var med in medInfos)
                                        {
                                            if (items.Count > index)
                                            {
                                                items[index].LoadAttributes();

                                                string scheduleText = "";
                                                string separator    = "";
                                                var    schedule     = items[index].GetAttributeValue(matrixAttributeScheduleKey).SplitDelimitedValues();
                                                foreach (var scheduleGuid in schedule)
                                                {
                                                    scheduleText += separator + DefinedValueCache.Get(scheduleGuid);
                                                    separator     = ", ";
                                                }

                                                checkInLabel.MergeFields.Add(med.Medication,
                                                                             items[index].GetAttributeValue(matrixAttributeMedicationKey)
                                                                             + " - "
                                                                             + scheduleText
                                                                             );

                                                checkInLabel.MergeFields.Add(med.Instructions, items[index].GetAttributeValue(matrixAttributeInstructionsKey));
                                            }
                                            else
                                            {
                                                checkInLabel.MergeFields.Add(med.Medication, "");
                                                checkInLabel.MergeFields.Add(med.Instructions, "");
                                            }

                                            index++;
                                        }

                                        addLabel(checkInLabel, checkInState, groupType, group, rockContext);
                                    }
                                }
                            }
                        }
                    }
                }
                return(true);
            }

            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            return(false);
        }
Пример #8
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, Rock.Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = Rock.RockDateTime.Now;
                DateTime       today          = startDateTime.Date;
                DateTime       tomorrow       = startDateTime.AddDays(1);

                bool reuseCodeForFamily = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 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))
                                    {
                                        var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                        if (primaryAlias != null)
                                        {
                                            // If a like attendance service exists close it before creating another one.
                                            var oldAttendance = attendanceService.Queryable()
                                                                .Where(a =>
                                                                       a.StartDateTime >= today &&
                                                                       a.StartDateTime < tomorrow &&
                                                                       a.Occurrence.LocationId == location.Location.Id &&
                                                                       a.Occurrence.ScheduleId == schedule.Schedule.Id &&
                                                                       a.Occurrence.GroupId == group.Group.Id &&
                                                                       a.PersonAlias.PersonId == person.Person.Id)
                                                                .FirstOrDefault();

                                            if (oldAttendance != null)
                                            {
                                                oldAttendance.EndDateTime = Rock.RockDateTime.Now;
                                                oldAttendance.DidAttend   = false;
                                            }
                                            var 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.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.Note      = group.Notes;
                                            attendance.DidAttend = groupType.GroupType.GetAttributeValue("SetDidAttend").AsBoolean();

                                            attendanceService.Add(attendance);
                                            CheckInCountCache.AddAttendance(attendance);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

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

            return(false);
        }
        private void ShowEdit(int savedGroupMemberId = 0)
        {
            phGroups.Controls.Clear();
            var                groups             = GetGroups();
            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            foreach (var group in groups)
            {
                Panel pnlGroup = new Panel();
                phGroups.Controls.Add(pnlGroup);

                Literal ltGroup = new Literal();
                ltGroup.Text = string.Format("<h4>{0}</h4>", group.Name);
                pnlGroup.Controls.Add(ltGroup);

                var groupMembers = groupMemberService.GetByGroupIdAndPersonId(group.Id, Person.Id);
                var unusedRoles  = group.GroupType.Roles.Where(r => !groupMembers.Select(gm => gm.GroupRoleId).Contains(r.Id));

                if (unusedRoles.Any())
                {
                    Panel pnlButtonGroup = new Panel();
                    pnlButtonGroup.CssClass = "input-group";
                    pnlGroup.Controls.Add(pnlButtonGroup);

                    RockDropDownList ddlRole = new RockDropDownList();
                    ddlRole.DataSource     = unusedRoles;
                    ddlRole.DataTextField  = "Name";
                    ddlRole.DataValueField = "Id";
                    ddlRole.CssClass       = "form-control";
                    ddlRole.ID             = "ddl" + group.Id.ToString();
                    ddlRole.DataBind();
                    pnlButtonGroup.Controls.Add(ddlRole);

                    Panel pnlInputGroupButton = new Panel();
                    pnlInputGroupButton.CssClass = "input-group-btn";
                    pnlButtonGroup.Controls.Add(pnlInputGroupButton);

                    BootstrapButton btnAdd = new BootstrapButton();
                    btnAdd.Text     = "Add To Group";
                    btnAdd.CssClass = "btn btn-primary";
                    btnAdd.ID       = "Add" + group.Id.ToString();
                    btnAdd.Click   += (s, e) => { AddGroupMember(group, ddlRole); };
                    pnlInputGroupButton.Controls.Add(btnAdd);
                }

                foreach (var groupMember in groupMembers)
                {
                    Panel pnlWell = new Panel();
                    pnlWell.CssClass = "well";
                    phGroups.Controls.Add(pnlWell);

                    Literal ltRole = new Literal();
                    ltRole.Text = string.Format("<b><em>Group Role: {0}</em></b> ", groupMember.GroupRole.Name);
                    pnlWell.Controls.Add(ltRole);

                    BootstrapButton btnRemove = new BootstrapButton();
                    btnRemove.Text     = "Remove";
                    btnRemove.CssClass = "btn btn-danger btn-xs pull-right";
                    btnRemove.ID       = groupMember.Id.ToString();
                    btnRemove.Click   += (s, e) => { ConfirmDelete(groupMember.Id); };
                    pnlWell.Controls.Add(btnRemove);

                    HtmlGenericContainer hr = new HtmlGenericContainer("hr");
                    pnlWell.Controls.Add(hr);

                    groupMember.LoadAttributes();
                    var attributeList = groupMember.Attributes.Select(d => d.Value)
                                        .OrderBy(a => a.Order).ThenBy(a => a.Name).ToList();
                    foreach (var attribute in attributeList)
                    {
                        string attributeValue = groupMember.GetAttributeValue(attribute.Key);
                        attribute.AddControl(pnlWell.Controls, attributeValue, "", true, true);
                    }

                    RockTextBox tbNotes = new RockTextBox();
                    tbNotes.TextMode = TextBoxMode.MultiLine;
                    tbNotes.ID       = "Note" + groupMember.Id.ToString();
                    tbNotes.Label    = "Notes";
                    tbNotes.Text     = groupMember.Note;
                    pnlWell.Controls.Add(tbNotes);

                    if (savedGroupMemberId == groupMember.Id)
                    {
                        NotificationBox nbSavedNote = new NotificationBox();
                        nbSavedNote.Text = "Group member information saved";
                        nbSavedNote.NotificationBoxType = NotificationBoxType.Success;
                        pnlWell.Controls.Add(nbSavedNote);
                    }

                    BootstrapButton btnSave = new BootstrapButton();
                    btnSave.ID       = "save" + groupMember.Id.ToString();
                    btnSave.Text     = "Save";
                    btnSave.CssClass = "btn btn-primary btn-xs";
                    btnSave.Click   += (s, e) => { SaveGroupMember(rockContext, groupMember, pnlWell, attributeList, tbNotes); };
                    pnlWell.Controls.Add(btnSave);
                }
            }

            HtmlGenericContainer hrDone = new HtmlGenericContainer("hr");

            phGroups.Controls.Add(hrDone);

            BootstrapButton btnDone = new BootstrapButton();

            btnDone.Text   = "Done";
            btnDone.ID     = "btnDone";
            btnDone.Click += (s, e) =>
            {
                hfEditMode.Value = "0";
                ShowView();
            };
            phGroups.Controls.Add(btnDone);
        }
Пример #10
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;
                DateTime       startDateTime  = RockDateTime.Now;

                bool reuseCodeForFamily = GetAttributeValue(action, "ReuseCodeForFamily").AsBoolean();

                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.Occurrence.LocationId = location.Location.Id;
                                                attendance.CampusId = location.CampusId;
                                                attendance.Occurrence.ScheduleId = schedule.Schedule.Id;
                                                attendance.Occurrence.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        = false;

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

                rockContext.SaveChanges();
                return(true);
            }
            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            return(false);
        }
Пример #11
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);
        }
        private void LoadKeywordGroup()
        {
            var keyword = PageParameter("keyword");

            if (keyword.IsNullOrWhiteSpace())
            {
                pnlKeyword.Visible = false;
                return;
            }

            var attributeKey = GetAttributeValue("KeywordKey");

            int         communicationListGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id;
            var         groupEntityTypeId            = EntityTypeCache.Get(typeof(Group)).Id;
            RockContext rockContext = new RockContext();

            AttributeService attributeService = new AttributeService(rockContext);
            var attribute = attributeService.Queryable().AsNoTracking()
                            .Where(a => a.EntityTypeId == groupEntityTypeId &&
                                   a.EntityTypeQualifierValue == communicationListGroupTypeId.ToString() &&
                                   a.Key == attributeKey)
                            .FirstOrDefault();

            if (attribute == null)
            {
                pnlKeyword.Visible = false;
                return;
            }

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            var attributeValue = attributeValueService.Queryable().AsNoTracking()
                                 .Where(av => av.AttributeId == attribute.Id &&
                                        (av.Value == keyword ||
                                         av.Value.Contains("|" + keyword) ||
                                         av.Value.Contains(keyword + "|") ||
                                         av.Value.Contains("|" + keyword + "|"))
                                        ).FirstOrDefault();

            if (attributeValue == null)
            {
                pnlKeyword.Visible = false;
                return;
            }

            GroupService groupService = new GroupService(rockContext);
            var          group        = groupService.Get(attributeValue.EntityId ?? 0);

            if (group == null || !group.IsActive || group.IsArchived)
            {
                pnlKeyword.Visible = false;
                return;
            }
            group.LoadAttributes();

            var name = group.GetAttributeValue("PublicName");

            if (name.IsNullOrWhiteSpace())
            {
                name = group.Name;
            }
            ltGroupName.Text = name;

            var type = group.GetAttributeValue(GetAttributeValue("AttributeKey"));

            if (type.IsNullOrWhiteSpace())
            {
                type = "Text Message,Email";
            }

            type = string.Join(", ", type.SplitDelimitedValues(false));

            ltType.Text        = type;
            ltDescription.Text = group.Description;

            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            GroupMember activeMember = null;

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

            foreach (var member in groupMembers)
            {
                if (member.GroupMemberStatus == GroupMemberStatus.Active)
                {
                    activeMember = member;
                }
            }

            bool hasActiveMember = false;

            if (activeMember != null)
            {
                hasActiveMember = true;
            }
            else
            {
                activeMember = new GroupMember
                {
                    GroupId = group.Id
                };
            }

            activeMember.LoadAttributes();
            activeMember.Attributes = activeMember.Attributes.Where(a => a.Value.IsGridColumn).ToDictionary(a => a.Key, a => a.Value);


            if (hasActiveMember)
            {
                if (activeMember.Attributes.Any())
                {
                    nbAlreadySubscribed.Visible = true;
                    nbAlreadySubscribed.Text    = "You are already subscribed to this list, but you can update your subscription settings here.";
                    btnSubscribe.Text           = "Update";
                }
                else
                {
                    nbAlreadySubscribed.Visible = true;
                    nbAlreadySubscribed.Text    = "You are already subscribed to this list, but you can manage the rest of your subscriptions on this page. ";
                    btnSubscribe.Visible        = false;
                }
            }

            if (activeMember.Attributes.Any())
            {
                ltAttributesHeader.Text = "<h3>Subscription Settings</h3>";
                Rock.Attribute.Helper.AddEditControls(activeMember, phGroupAttributes, true);
            }

            ViewState["KeywordGroupId"] = group.Id;
        }
Пример #13
0
        /// <summary>Process all leagues (programs) from LeagueApps.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            GroupService          groupService          = new GroupService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            BinaryFileService     binaryFileService     = new BinaryFileService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var warnings  = string.Empty;
            var processed = 0;

            try
            {
                var apiClient = new APIClient();

                var settings = SettingsComponent.GetComponent <LeagueAppsSettings>();

                //Group Attributes
                var parentGroup          = groupService.Get(settings.GetAttributeValue(Constants.ParentGroup).AsGuid());
                var yearGroupType        = GroupTypeCache.Get(settings.GetAttributeValue(Constants.YearGroupType).AsGuid());
                var categoryGroupType    = GroupTypeCache.Get(settings.GetAttributeValue(Constants.CategoryGroupType).AsGuid());
                var leagueGroupType      = GroupTypeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupType).AsGuid());
                var sportsType           = DefinedTypeCache.Get(Constants.SPORTS_TYPE.AsGuid());
                var seasonsType          = DefinedTypeCache.Get(Constants.SEASONS_TYPE.AsGuid());
                var gendersType          = DefinedTypeCache.Get(Constants.GENDERS_TYPE.AsGuid());
                var groupMemberAttribute = AttributeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupTeam).AsGuid());

                //Person Attribute
                var personattribute  = AttributeCache.Get(Constants.ATTRIBUTE_PERSON_USER_ID.AsGuid());
                var connectionStatus = DefinedValueCache.Get(settings.GetAttributeValue(Constants.DefaultConnectionStatus).AsGuid());

                var groupEntityType = EntityTypeCache.Get(typeof(Group)).Id;

                var programs = apiClient.GetPublic <List <Programs> >("/v1/sites/{siteid}/programs/current");


                var groups = groupService.Queryable().Where(g => g.GroupTypeId == leagueGroupType.Id).ToList();

                foreach (Contracts.Programs program in programs)
                {
                    // Process the program
                    Group league    = null;
                    Group league2   = null;
                    Group league3   = null;
                    var   startdate = program.startTime;
                    var   mode      = program.mode.ToLower();
                    mode = mode.First().ToString().ToUpper() + mode.Substring(1);
                    var grandparentgroup = string.Format("{0}", startdate.Year);
                    if (program.programId > 0)
                    {
                        league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == parentGroup.Id).FirstOrDefault();
                        if (league != null)
                        {
                            league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault();
                            if (league2 != null)
                            {
                                league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == leagueGroupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault();
                            }
                        }
                    }
                    Guid guid  = Guid.NewGuid();
                    Guid guid2 = Guid.NewGuid();
                    Guid guid3 = Guid.NewGuid();

                    if (league == null)
                    {
                        // Create league grandparent Group
                        Group leagueGPG = new Group();
                        leagueGPG.Name           = grandparentgroup;
                        leagueGPG.GroupTypeId    = yearGroupType.Id;
                        leagueGPG.ParentGroupId  = parentGroup.Id;
                        leagueGPG.IsSystem       = false;
                        leagueGPG.IsActive       = true;
                        leagueGPG.IsSecurityRole = false;
                        leagueGPG.Order          = 0;
                        leagueGPG.Guid           = guid;
                        groupService.Add(leagueGPG);

                        // Now save the league grandparent group
                        dbContext.SaveChanges();
                        league = leagueGPG;
                    }

                    if (league2 == null)
                    {
                        // Create league parent Group
                        Group leaguePG = new Group();
                        leaguePG.Name           = mode;
                        leaguePG.GroupTypeId    = categoryGroupType.Id;
                        leaguePG.ParentGroupId  = league.Id;
                        leaguePG.IsSystem       = false;
                        leaguePG.IsActive       = true;
                        leaguePG.IsSecurityRole = false;
                        leaguePG.Order          = 0;
                        leaguePG.Guid           = guid2;
                        groupService.Add(leaguePG);

                        // Now save the league parent group
                        dbContext.SaveChanges();
                        league2 = leaguePG;
                    }

                    if (league3 == null)
                    {
                        // Create the league
                        Group leagueG = new Group();
                        leagueG.Name           = program.name;
                        leagueG.GroupTypeId    = leagueGroupType.Id;
                        leagueG.ParentGroupId  = league2.Id;
                        leagueG.IsSystem       = false;
                        leagueG.IsActive       = true;
                        leagueG.IsSecurityRole = false;
                        leagueG.Order          = 0;
                        leagueG.Description    = HTMLConvertor.Convert(program.description);
                        leagueG.ForeignId      = program.programId;
                        groupService.Add(leagueG);

                        // Now save the league
                        dbContext.SaveChanges();
                        league3 = leagueG;
                    }
                    else
                    {
                        groups.Remove(league3);
                    }
                    league3.LoadAttributes();
                    var sport       = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sportsType.Id).FirstOrDefault();
                    var season      = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasonsType.Id).FirstOrDefault();
                    var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == gendersType.Id).FirstOrDefault();

                    if (!sport.IsNull())
                    {
                        league3.SetAttributeValue("Sport", sport.Guid);
                    }

                    if (!season.IsNull())
                    {
                        league3.SetAttributeValue("Season", season.Guid);
                    }
                    league3.SetAttributeValue("ExperienceLevel", program.experienceLevel);

                    if (!groupgender.IsNull())
                    {
                        league3.SetAttributeValue("Gender", groupgender.Guid);
                    }

                    if (startdate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("StartTime", startdate);
                    }

                    if (program.publicRegistrationTime != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime);
                    }

                    if (program.ageLimitEffectiveDate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d"));
                    }
                    league3.SetAttributeValue("ProgramURL", program.programUrlHtml);
                    league3.SetAttributeValue("RegisterURL", program.registerUrlHtml);
                    league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml);
                    league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml);
                    league3.SetAttributeValue("ProgramLogo", program.programLogo150);
                    league3.SaveAttributeValues();
                    dbContext.SaveChanges();

                    var applicants = apiClient.GetPrivate <List <Registrations> >("/v2/sites/{siteid}/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId);

                    context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members).");

                    foreach (Contracts.Registrations applicant in applicants)
                    {
                        // Use a fresh RockContext on every person/groupmember to keep things moving quickly
                        using (var rockContext = new RockContext())
                        {
                            PersonService      personService      = new PersonService(rockContext);
                            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                            LocationService    locationService    = new LocationService(rockContext);

                            Person person = null;

                            // 1. Try to load the person using the LeagueApps UserId
                            var attributevalue = applicant.userId.ToString();
                            var personIds      = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id &&
                                                                                         (av.Value == attributevalue ||
                                                                                          av.Value.Contains("|" + attributevalue + "|") ||
                                                                                          av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId);
                            if (personIds.Count() == 1)
                            {
                                person = personService.Get(personIds.FirstOrDefault().Value);
                            }

                            // 2. If we don't have a person match then
                            //    just use the standard person match/create logic
                            if (person == null)
                            {
                                var member = apiClient.GetPrivate <Member>("/v2/sites/{siteid}/members/" + applicant.userId);
                                person = LeagueAppsHelper.CreatePersonFromMember(member, connectionStatus);
                            }

                            // Check to see if the group member already exists
                            var groupmember = groupMemberService.GetByGroupIdAndPersonId(league3.Id, person.Id).FirstOrDefault();

                            if (groupmember == null)
                            {
                                Guid guid5 = Guid.NewGuid();
                                groupmember          = new GroupMember();
                                groupmember.PersonId = person.Id;
                                groupmember.GroupId  = league3.Id;
                                groupmember.IsSystem = false;
                                groupmember.Guid     = guid5;

                                if (!String.IsNullOrEmpty(applicant.role))
                                {
                                    var role = applicant.role.Split('(')[0].Trim();

                                    if (role == "FREEAGENT" || role == "PLAYER")
                                    {
                                        role = "Member";
                                    }
                                    else if (role == "CAPTAIN")
                                    {
                                        role = "Captain";
                                    }
                                    else if (role == "HEAD COACH" || role == "Head Coach")
                                    {
                                        role = "Head Coach";
                                    }
                                    else if (role == "ASST. COACH" || role == "Asst. Coach")
                                    {
                                        role = "Asst. Coach";
                                    }
                                    else
                                    {
                                        role = "Member";
                                    }
                                    var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == leagueGroupType.Id && r.Name == role).FirstOrDefault().Id;
                                    groupmember.GroupRoleId = grouprole;
                                }
                                else
                                {
                                    groupmember.GroupRoleId = leagueGroupType.DefaultGroupRoleId.Value;
                                }
                                groupmember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMemberService.Add(groupmember);
                                rockContext.SaveChanges();
                            }

                            // Make sure we update the team if necessary
                            groupmember.LoadAttributes();
                            groupmember.SetAttributeValue(groupMemberAttribute.Key, applicant.team);
                            groupmember.SaveAttributeValues(rockContext);
                        }
                    }
                    processed++;
                }

                foreach (Group sportsleague in groups)
                {
                    sportsleague.IsActive = false;
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LeagueApps Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }
Пример #14
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);
        }
Пример #15
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);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

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

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

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();
                return(true);
            }
            return(false);
        }
        private void ShowView()
        {
            phGroups.Controls.Clear();
            var                groups             = GetGroups();
            RockContext        rockContext        = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            foreach (var group in groups)
            {
                if (!group.IsAuthorized(Authorization.VIEW, CurrentPerson))
                {
                    continue;
                }

                var groupRoleIds = group.GroupType.Roles.Select(r => r.Id).ToList();
                var groupMembers = groupMemberService.GetByGroupIdAndPersonId(group.Id, Person.Id);
                foreach (var groupMember in groupMembers)
                {
                    var incorrectRoleIdAlert = "";
                    if (!groupRoleIds.Contains(groupMember.GroupRoleId))
                    {
                        incorrectRoleIdAlert = string.Format(" <i class='fa fa-exclamation-triangle' title='{0}'></i>",
                                                             group.GroupType.DefaultGroupRoleId);
                    }

                    Literal ltGroup = new Literal();
                    ltGroup.Text = string.Format("<h4>{0} [{1}{2}]</h4>", group.Name, groupMember.GroupRole.Name, incorrectRoleIdAlert);
                    phGroups.Controls.Add(ltGroup);
                    string formattedValue = string.Empty;

                    groupMember.LoadAttributes();
                    var attributeList = groupMember.Attributes.Select(d => d.Value)
                                        .OrderBy(a => a.Order).ThenBy(a => a.Name).ToList();
                    foreach (var attribute in attributeList)
                    {
                        var attributeValue = groupMember.GetAttributeValue(attribute.Key);

                        if (attribute.FieldType.Class == typeof(Rock.Field.Types.ImageFieldType).FullName)
                        {
                            formattedValue = attribute.FieldType.Field.FormatValueAsHtml(phGroups, attributeValue, attribute.QualifierValues, true);
                        }
                        else
                        {
                            formattedValue = attribute.FieldType.Field.FormatValueAsHtml(phGroups, attributeValue, attribute.QualifierValues, false);
                        }

                        if (!string.IsNullOrWhiteSpace(formattedValue))
                        {
                            phGroups.Controls.Add(new RockLiteral {
                                Label = attribute.Name, Text = formattedValue
                            });
                        }

                        if (!string.IsNullOrWhiteSpace(groupMember.Note))
                        {
                            RockLiteral ltNote = new RockLiteral();
                            ltNote.Label = "Note";
                            ltNote.Text  = groupMember.Note;
                            phGroups.Controls.Add(ltNote);
                        }
                    }
                }
            }
        }
Пример #18
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            using (OdbcConnection con = new OdbcConnection(ConnString))
            {
                RockContext rockContext = new RockContext();
                Group       group       = null;
                var         groupGuid   = this.GetAttributeValue("Group").AsGuidOrNull();
                var         whereClause = String.Empty;

                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);
                }

                if (group != null)
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var groupMember        = groupMemberService.GetByGroupIdAndPersonId(group.Id, CurrentPerson.Id).FirstOrDefault();

                    if (groupMember != null)
                    {
                        if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                        {
                            // Get any existing group member attribute values
                            groupMember.LoadAttributes(rockContext);

                            foreach (var attributeValue in groupMember.AttributeValues)
                            {
                                if (attributeValue.Key == "ProviderId" && groupMember.GroupRole.Name == "Member")
                                {
                                    if (!String.IsNullOrEmpty(attributeValue.Value.Value))
                                    {
                                        // It is possible that the Provider Id was typed incorrectly and
                                        // won't return any results.
                                        whereClause = "WHERE [Code] = '" + attributeValue.Value.Value + "'";
                                        gfSettings.SaveUserPreference("Counselor", attributeValue.Value.Value);
                                    }
                                    else
                                    {
                                        // This person was added to the security group as a member and doesn't have
                                        // a Provider Id.
                                        gfSettings.SaveUserPreference("Counselor", "");
                                        pnlList.Visible   = false;
                                        nbMessage.Title   = "You have been added to the security group, but need a Provider Id to view appointments.";
                                        nbMessage.Visible = true;
                                    }

                                    break;
                                }
                            }
                        }
                        else
                        {
                            // This person is not active in the security group.
                            pnlList.Visible   = false;
                            nbMessage.Title   = "You are not active in the security group.";
                            nbMessage.Visible = true;
                        }
                    }
                    else
                    {
                        // This person is not in the security group at all.
                        gfSettings.SaveUserPreference("Counselor", "");
                        pnlList.Visible   = false;
                        nbMessage.Title   = "You have not been added to the security group.";
                        nbMessage.Visible = true;
                    }
                }

                if (string.IsNullOrEmpty(whereClause))
                {
                    whereClause = "WHERE [Code] <> '00000'";
                }
                else
                {
                    whereClause = whereClause + " AND [Code] <> '00000'";
                }

                string qry = @"SELECT [Code], CONCAT(CONCAT([First Name] WITH ' ') WITH [Last Name]) AS [Counselor Name] 
                    FROM Provider " +
                             whereClause +
                             " ORDER BY [Counselor Name]";

                OdbcDataAdapter da  = new OdbcDataAdapter(qry, con);
                DataTable       dt1 = new DataTable();
                da.Fill(dt1);
                if (dt1.Rows.Count > 0)
                {
                    cblCounselors.DataSource     = dt1;
                    cblCounselors.DataTextField  = "Counselor Name";
                    cblCounselors.DataValueField = "Code";
                    cblCounselors.DataBind();

                    string selectedCounselors = gfSettings.GetUserPreference("Counselor");
                    if (!string.IsNullOrWhiteSpace(selectedCounselors))
                    {
                        cblCounselors.SetValues(selectedCounselors.Split(';').ToList());
                    }
                }
                else
                {
                    pnlList.Visible   = false;
                    nbMessage.Title   = "No results found.  If you were expecting to see something, then please verify that your Provider Id information is correct.";
                    nbMessage.Visible = true;
                }
            }

            drpDates.DelimitedValues = gfSettings.GetUserPreference("Appt Date Range");
        }
Пример #19
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 attendanceRecords     = new List <Attendance>();

                checkInState.Messages.Clear();

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    var currentOccurences = new List <OccurenceRecord>();
                    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, "EnforceStrictLocationThreshold").AsBoolean() && location.Location.SoftRoomThreshold.HasValue)
                                        {
                                            var thresHold = location.Location.SoftRoomThreshold.Value;
                                            if (checkInState.ManagerLoggedIn && location.Location.FirmRoomThreshold.HasValue && location.Location.FirmRoomThreshold.Value > location.Location.SoftRoomThreshold.Value)
                                            {
                                                thresHold = location.Location.FirmRoomThreshold.Value;
                                            }

                                            var currentOccurence = GetCurrentOccurence(currentOccurences, location, schedule, startDateTime.Date);

                                            // The totalAttended is the number of people still checked in (not people who have been checked-out)
                                            // not counting the current person who may already be checked in,
                                            // + the number of people we have checked in so far (but haven't been saved yet).
                                            var attendanceQry = attendanceService.GetByDateOnLocationAndSchedule(startDateTime.Date, location.Location.Id, schedule.Schedule.Id)
                                                                .AsNoTracking()
                                                                .Where(a => a.EndDateTime == null);

                                            // Only process if the current person is NOT already checked-in to this location and schedule
                                            if (!attendanceQry.Where(a => a.PersonAlias.PersonId == person.Person.Id).Any())
                                            {
                                                var totalAttended = attendanceQry.Count() + (currentOccurence == null ? 0 : currentOccurence.Count);

                                                // If over capacity, remove the schedule and add a warning message.
                                                if (totalAttended >= thresHold)
                                                {
                                                    // Remove the schedule since the location was full for this schedule.
                                                    location.Schedules.Remove(schedule);

                                                    var message = new CheckInMessage()
                                                    {
                                                        MessageType = MessageType.Warning
                                                    };

                                                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                                                    mergeFields.Add("Person", person.Person);
                                                    mergeFields.Add("Group", group.Group);
                                                    mergeFields.Add("Location", location.Location);
                                                    mergeFields.Add("Schedule", schedule.Schedule);
                                                    message.MessageText = GetAttributeValue(action, "NotChecked-InMessageFormat").ResolveMergeFields(mergeFields);

                                                    // Now add it to the check-in state message list for others to see.
                                                    checkInState.Messages.Add(message);
                                                    continue;
                                                }
                                                else
                                                {
                                                    // Keep track of anyone who was checked in so far.
                                                    if (currentOccurence == null)
                                                    {
                                                        currentOccurence = new OccurenceRecord()
                                                        {
                                                            Date       = startDateTime.Date,
                                                            LocationId = location.Location.Id,
                                                            ScheduleId = schedule.Schedule.Id
                                                        };
                                                        currentOccurences.Add(currentOccurence);
                                                    }

                                                    currentOccurence.Count += 1;
                                                }
                                            }
                                        }

                                        // 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);
                                        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);
                                    }
                                }
                            }
                        }
                    }
                }

                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();
                attendanceRecords    = null;

                return(true);
            }

            return(false);
        }