/// <summary>
        /// Maps the attendance.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        //private DateTime? StartDateTime { get; set;}
        private void MapAttendance(IQueryable <Row> tableData)
        {
            var lookupContext = new RockContext();
            int completed     = 0;
            int totalRows     = tableData.Count();
            int percentage    = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Attendance import ({0:N0} found).", totalRows));

            var attendanceList    = new List <Rock.Model.Attendance>();
            var groupService      = new GroupService(lookupContext);
            var existingGroupList = new List <Group>();

            existingGroupList = groupService.Queryable().ToList();

            foreach (var row in tableData)
            {
                DateTime?startTime = row["Start_Date_Time"] as DateTime?;
                if (startTime != null && startTime != DateTime.MinValue)
                {
                    DateTime startDateTime = (DateTime)startTime;
                    if (startDateTime.Year == 2014 && startDateTime.Month >= 1 && startDateTime.Month <= 8)
                    {
                        //startDateTime = BruteForceDateTime(startTime);

                        var attendance = new Rock.Model.Attendance();
                        attendance.CreatedByPersonAliasId  = ImportPersonAlias.Id;
                        attendance.ModifiedByPersonAliasId = ImportPersonAlias.Id;
                        attendance.CreatedDateTime         = DateTime.Today;
                        attendance.ModifiedDateTime        = DateTime.Today;
                        attendance.StartDateTime           = startDateTime; //(DateTime)startTime;
                        attendance.DidAttend = true;
                        attendance.CampusId  = 1;                           //Campus is needed for attendance to show in attendance analysis.


                        //string position = row["CheckedInAs"] as string;
                        //string jobTitle = row["Job_Title"] as string;
                        //string machineName = row["Checkin_Machine_Name"] as string;
                        int?rlcId = row["RLC_ID"] as int?;

                        int?individualId = row["Individual_ID"] as int?;

                        if (individualId != null)
                        {
                            attendance.PersonAliasId = GetPersonAliasId(individualId);
                        }

                        DateTime?checkInTime = row["Check_In_Time"] as DateTime?;
                        if (checkInTime != null)
                        {
                            // set the start time to the time they actually checked in. If null it maintains Start_Date_Time
                            attendance.StartDateTime = (DateTime)checkInTime; //BruteForceDateTime( checkInTime );
                        }

                        DateTime?checkOutTime = row["Check_Out_Time"] as DateTime?;
                        if (checkOutTime != null)
                        {
                            attendance.EndDateTime = (DateTime)checkOutTime; //BruteForceDateTime( checkOutTime );
                        }

                        //string f1AttendanceCode = row["Tag_Code"] as string;
                        //if ( f1AttendanceCode != null )
                        //{
                        //    attendance.AttendanceCode = new Rock.Model.AttendanceCode();
                        //    attendance.AttendanceCode.Code = f1AttendanceCode;
                        //}
                        string f1AttendanceCheckedInAs = row["CheckedInAs"] as string;
                        if (f1AttendanceCheckedInAs != null)
                        {
                            attendance.Note = f1AttendanceCheckedInAs;
                        }


                        // look up location, schedule, and device -- all of these fields can be null if need be
                        attendance.LocationId = GetLocationId(Convert.ToInt32(rlcId));


                        //look up Group
                        Group rlcGroup = existingGroupList.Where(g => g.ForeignId == (rlcId.ToString())).FirstOrDefault();
                        if (rlcGroup != null)
                        {
                            attendance.GroupId = rlcGroup.Id;
                        }

                        var dvService = new DefinedValueService(lookupContext);

                        attendance.SearchTypeValueId = dvService.Queryable().Where(dv => dv.Value == "Phone Number").FirstOrDefault().Id;

                        //ReportProgress( 0, string.Format( "{0},{1},{2},{3},{4},{5},{6},{7},{8}", individualId,rlcId,rlcGroup.Name,attendance.CreatedByPersonAliasId,attendance.ModifiedByPersonAliasId,attendance.StartDateTime,attendance.DidAttend,attendance.AttendanceCode,attendance.LocationId ) );

                        //look into creating DeviceIds and Locations (Generic)


                        // Other Attributes to create:
                        // Tag_Comment
                        // BreakoutGroup_Name
                        // Pager_Code

                        //attendanceList.Add( attendance );


                        completed++;
                        if (completed % percentage < 1)
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress(percentComplete, string.Format("Completed: {0:N0} Percent Completed: {0:N0} ", completed, percentComplete));
                        }
                        //    else if ( completed % ReportingNumber < 1 )
                        //    {
                        //        var rockContext = new RockContext();
                        //        rockContext.WrapTransaction( () =>
                        //{
                        //    rockContext.Configuration.AutoDetectChangesEnabled = false;
                        //    rockContext.Attendances.AddRange( attendanceList );
                        //    rockContext.SaveChanges( DisableAudit );
                        //} );


                        //        ReportPartialProgress();
                        //    }


                        var rockContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;

                            rockContext.Attendances.Add(attendance);
                            rockContext.SaveChanges(DisableAudit);
                        });


                        ReportPartialProgress();
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            GroupType        groupType;
            GroupTypeService groupTypeService = new GroupTypeService();

            int groupTypeId = int.Parse(hfGroupTypeId.Value);

            if (groupTypeId == 0)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType, CurrentPersonId);
            }
            else
            {
                groupType = groupTypeService.Get(groupTypeId);
            }

            groupType.Name = tbName.Text;
            if (ddlDefaultGroupRole.SelectedValue.Equals(None.Id.ToString()))
            {
                groupType.DefaultGroupRoleId = null;
            }
            else
            {
                groupType.DefaultGroupRoleId = int.Parse(ddlDefaultGroupRole.SelectedValue);
            }

            groupType.Description = tbDescription.Text;

            groupType.ChildGroupTypes = new List <GroupType>();
            groupType.ChildGroupTypes.Clear();
            foreach (var item in ChildGroupTypesDictionary)
            {
                var childGroupType = groupTypeService.Get(item.Key);
                if (childGroupType != null)
                {
                    groupType.ChildGroupTypes.Add(childGroupType);
                }
            }

            DefinedValueService definedValueService = new DefinedValueService();

            groupType.LocationTypes = new List <GroupTypeLocationType>();
            groupType.LocationTypes.Clear();
            foreach (var item in LocationTypesDictionary)
            {
                var locationType = definedValueService.Get(item.Key);
                if (locationType != null)
                {
                    groupType.LocationTypes.Add(new GroupTypeLocationType {
                        LocationTypeValueId = locationType.Id
                    });
                }
            }

            // check for duplicates
            if (groupTypeService.Queryable().Count(a => a.Name.Equals(groupType.Name, StringComparison.OrdinalIgnoreCase) && !a.Id.Equals(groupType.Id)) > 0)
            {
                tbName.ShowErrorMessage(WarningMessage.DuplicateFoundMessage("name", GroupType.FriendlyTypeName));
                return;
            }

            if (!groupType.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            RockTransactionScope.WrapTransaction(() =>
            {
                groupTypeService.Save(groupType, CurrentPersonId);
            });

            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var rockContext             = new RockContext();
            var financialPledgeService  = new FinancialPledgeService(rockContext);
            var financialAccountService = new FinancialAccountService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var person = FindPerson(rockContext);

            FinancialPledge financialPledge = new FinancialPledge();

            financialPledge.PersonAliasId = person.PrimaryAliasId;
            financialPledge.GroupId       = ddlGroup.SelectedValueAsInt();

            var financialAccount = financialAccountService.Get(GetAttributeValue("Account").AsGuid());

            if (financialAccount != null)
            {
                financialPledge.AccountId = financialAccount.Id;
            }

            financialPledge.TotalAmount = tbTotalAmount.Text.AsDecimal();

            var pledgeFrequencySelection = DefinedValueCache.Get(ddlFrequency.SelectedValue.AsInteger());

            if (pledgeFrequencySelection != null)
            {
                financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id;
            }

            financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue;
            financialPledge.EndDate   = drpDateRange.UpperValue ?? DateTime.MaxValue;

            if (sender != btnConfirm)
            {
                var duplicatePledges = financialPledgeService.Queryable()
                                       .Where(a => a.PersonAlias.PersonId == person.Id)
                                       .Where(a => a.AccountId == financialPledge.AccountId)
                                       .Where(a => a.StartDate == financialPledge.StartDate)
                                       .Where(a => a.EndDate == financialPledge.EndDate).ToList();

                if (duplicatePledges.Any())
                {
                    pnlAddPledge.Visible           = false;
                    pnlConfirm.Visible             = true;
                    nbDuplicatePledgeWarning.Text  = "The following pledges have already been entered for you:";
                    nbDuplicatePledgeWarning.Text += "<ul>";
                    foreach (var pledge in duplicatePledges.OrderBy(a => a.StartDate).ThenBy(a => a.Account.Name))
                    {
                        nbDuplicatePledgeWarning.Text += string.Format("<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount);
                    }

                    nbDuplicatePledgeWarning.Text += "</ul>";

                    return;
                }
            }

            if (financialPledge.IsValid)
            {
                financialPledgeService.Add(financialPledge);

                rockContext.SaveChanges();

                // populate account so that Liquid can access it
                financialPledge.Account = financialAccount;

                // populate PledgeFrequencyValue so that Liquid can access it
                financialPledge.PledgeFrequencyValue = definedValueService.Get(financialPledge.PledgeFrequencyValueId ?? 0);

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("Person", person);
                mergeFields.Add("FinancialPledge", financialPledge);
                mergeFields.Add("PledgeFrequency", pledgeFrequencySelection);
                mergeFields.Add("Account", financialAccount);
                lReceipt.Text = GetAttributeValue("ReceiptText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                lReceipt.Text = lReceipt.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);

                lReceipt.Visible     = true;
                pnlAddPledge.Visible = false;
                pnlConfirm.Visible   = false;

                // if a ConfirmationEmailTemplate is configured, send an email
                var confirmationEmailTemplateGuid = GetAttributeValue("ConfirmationEmailTemplate").AsGuidOrNull();
                if (confirmationEmailTemplateGuid.HasValue)
                {
                    var emailMessage = new RockEmailMessage(confirmationEmailTemplateGuid.Value);
                    emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                    emailMessage.AppRoot   = ResolveRockUrl("~/");
                    emailMessage.ThemeRoot = ResolveRockUrl("~~/");
                    emailMessage.Send();
                }
            }
            else
            {
                ShowInvalidResults(financialPledge.ValidationResults);
            }
        }
        public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);
            var groupMemberService      = new GroupMemberService(rockContext);
            var groupService            = new GroupService(rockContext);

            Guid  nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid();
            Guid  nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid();
            Guid  volunteerGroup  = GetAttributeValue("VolunteerGroup").AsGuid();
            Group groupId         = new Group();

            List <DefinedValueCache>  facilities    = DefinedTypeCache.Get(nursingHomeList).DefinedValues;
            Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>();

            groupId = groupService.GetByGuid(volunteerGroup);

            var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id;

            var groupMemberAttributeQry = attributeService.Queryable()
                                          .Where(a => a.EntityTypeId == groupMemberEntityTypeId)
                                          .Select(a => a.Id);

            var groupMemberAttributeValueQry = attributeValueService.Queryable()
                                               .Where(av => groupMemberAttributeQry.Contains(av.AttributeId));

            if (groupId.IsNotNull())
            {
                var groupMemberList = groupMemberService.Queryable()
                                      .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active)
                                      .GroupJoin(groupMemberAttributeValueQry,
                                                 gm => gm.Id,
                                                 av => av.EntityId,
                                                 (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av })
                                      .ToList();

                var groupMembers = new List <GroupMember>();

                foreach (var set in groupMemberList)
                {
                    var groupMember = set.GroupMember;

                    groupMember.Attributes = set.GroupMemberAttributeValues
                                             .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId));

                    groupMember.AttributeValues = set.GroupMemberAttributeValues
                                                  .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av));

                    groupMembers.Add(groupMember);
                }

                foreach (var nursingHome in facilities)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace())
                        {
                            if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower()))
                            {
                                if (volunteerList.ContainsKey(nursingHome.Guid))
                                {
                                    volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue;
                                }

                                else
                                {
                                    volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue);
                                }
                            }
                        }
                    }
                }
            }
            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            var workflowType           = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();

            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new NursingHomeRow
            {
                Id          = w.Workflow.Id,
                Workflow    = w.Workflow,
                NursingHome = new Func <string>(() =>
                {
                    if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any())
                    {
                        return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault());
                    }
                    return("N/A");
                })(),
                Person = new Func <Person>(() =>
                {
                    AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault();
                    if (personAliasAV != null)
                    {
                        PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid());

                        return(pa != null ? pa.Person : new Person());
                    }
                    return(new Person());
                })(),
                Address = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null)
                    {
                        return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                               dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                               dv.AttributeValues["Qualifier4"].ValueFormatted);
                    }
                    return("");
                })(),
                PastoralMinister = new Func <string>(() =>
                {
                    DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault();
                    if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6")))
                    {
                        return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted);
                    }
                    return("");
                })(),
                Volunteers = new Func <string>(() =>
                {
                    String vList = "";
                    if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList))
                    {
                        return(vList);
                    }
                    else
                    {
                        return("");
                    }
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() =>
                {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName);

            return(newQry);
        }
Example #5
0
        /// <summary>
        /// Handles the Click event of the btnSaveDefinedValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSaveValue_Click(object sender, EventArgs e)
        {
            DefinedValue        definedValue;
            var                 rockContext         = new RockContext();
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            int definedValueId = hfDefinedValueId.ValueAsInt();

            if (definedValueId.Equals(0))
            {
                int definedTypeId = hfDefinedTypeId.ValueAsInt();
                definedValue = new DefinedValue {
                    Id = 0
                };
                definedValue.DefinedTypeId = definedTypeId;
                definedValue.IsSystem      = false;

                var orders = definedValueService.Queryable()
                             .Where(d => d.DefinedTypeId == definedTypeId)
                             .Select(d => d.Order)
                             .ToList();

                definedValue.Order = orders.Any() ? orders.Max() + 1 : 0;
            }
            else
            {
                definedValue = definedValueService.Get(definedValueId);
            }

            definedValue.Value       = tbValueName.Text;
            definedValue.Description = tbValueDescription.Text;
            definedValue.IsActive    = cbValueActive.Checked;
            avcDefinedValueAttributes.GetEditValues(definedValue);

            if (!Page.IsValid)
            {
                return;
            }

            if (!definedValue.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                if (definedValue.Id.Equals(0))
                {
                    definedValueService.Add(definedValue);
                }

                rockContext.SaveChanges();

                definedValue.SaveAttributeValues(rockContext);
            });

            BindDefinedValuesGrid();

            hfDefinedValueId.Value = string.Empty;
            modalValue.Hide();
        }
Example #6
0
        private IQueryable <HospitalRow> GetQuery(RockContext rockContext)
        {
            var contextEntity = this.ContextEntity();

            var workflowService         = new WorkflowService(rockContext);
            var workflowActivityService = new WorkflowActivityService(rockContext);
            var attributeService        = new AttributeService(rockContext);
            var attributeValueService   = new AttributeValueService(rockContext);
            var personAliasService      = new PersonAliasService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var entityTypeService       = new EntityTypeService(rockContext);


            int    entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id;
            string status       = (contextEntity != null ? "Completed" : "Active");

            Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid();

            var workflowType           = new WorkflowTypeService(rockContext).Get(hospitalWorkflow);
            var workflowTypeIdAsString = workflowType.Id.ToString();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString)
                               .Select(a => a.Id).ToList();

            // Look up the activity type for "Visitation"
            var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault();

            var activityAttributeIds = attributeService.Queryable()
                                       .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString)
                                       .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status));

            var visitQry = workflowActivityService.Queryable()
                           .Join(
                attributeValueService.Queryable(),
                wa => wa.Id,
                av => av.EntityId.Value,
                (wa, av) => new { WorkflowActivity = wa, AttributeValue = av })
                           .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(wa => wa.WorkflowActivity)
                           .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });

            if (contextEntity != null)
            {
                var personGuid       = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList();
                var validWorkflowIds = new AttributeValueService(rockContext).Queryable()
                                       .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId);
                wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id));
                visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId));
                gReport.Columns[10].Visible = true;
            }

            var visits = visitQry.ToList();

            var workflows = wfTmpqry.Join(
                attributeValueService.Queryable(),
                obj => obj.Id,
                av => av.EntityId.Value,
                (obj, av) => new { Workflow = obj, AttributeValue = av })
                            .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                            .GroupBy(obj => obj.Workflow)
                            .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) })
                            .ToList();

            var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa })
                      .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList();


            if (contextEntity == null)
            {
                // Make sure they aren't deceased
                qry = qry.AsQueryable().Where(w => !
                                              (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ?
                                               personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased :
                                               false)).ToList();
            }

            var newQry = qry.Select(w => new HospitalRow
            {
                Id              = w.Workflow.Id,
                Workflow        = w.Workflow,
                Name            = w.Workflow.Name,
                Hospital        = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(),
                HospitalAddress = new Func <string>(() =>
                {
                    DefinedValueCache dv = DefinedValueCache.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid());
                    return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier2"].ValueFormatted + " " +
                           dv.AttributeValues["Qualifier3"].ValueFormatted + ", " +
                           dv.AttributeValues["Qualifier4"].ValueFormatted);
                })(),
                PersonToVisit = new Func <Person>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person);
                    }
                    return(new Person());
                })(),
                Campus = new Func <string>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        var campus = pa.Person.GetCampus();
                        return(campus != null ? campus.Name : "[Unknown]");
                    }
                    return("[Unknown]");
                })(),
                Age = new Func <int?>(() =>
                {
                    PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid());
                    if (pa != null)
                    {
                        return(pa.Person.Age);
                    }
                    return(null);
                })(),
                Room        = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                NotifiedBy  = w.AttributeValues.Where(av => av.AttributeKey == "NotifiedBy").Select(av => av.ValueFormatted).FirstOrDefault(),
                AdmitDate   = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(),
                Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                Visits      = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(),
                LastVisitor = new Func <string>(() =>
                {
                    var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault();
                    if (visitor != null)
                    {
                        return(visitor.ValueFormatted);
                    }
                    return("N/A");
                })(),
                LastVisitDate  = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(),
                DischargeDate  = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                Status         = w.Workflow.Status,
                Communion      = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(),
                Actions        = ""
            }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName);

            return(newQry);
        }
Example #7
0
        /// <summary>
        /// Handles the SaveClick event of the dlgLocations control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dlgLocations_SaveClick(object sender, EventArgs e)
        {
            Location    location            = null;
            int?        memberPersonAliasId = null;
            RockContext rockContext         = new RockContext();

            if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
            {
                if (ddlMember.SelectedValue != null)
                {
                    var ids = ddlMember.SelectedValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).AsIntegerList().ToArray();
                    if (ids.Length == 2)
                    {
                        int locationId     = ids[0];
                        int primaryAliasId = ids[1];
                        var dbLocation     = new LocationService(rockContext).Get(locationId);
                        if (dbLocation != null)
                        {
                            location = new Location();
                            location.CopyPropertiesFrom(dbLocation);
                        }

                        memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(primaryAliasId);
                    }
                }
            }
            else
            {
                if (locpGroupLocation.Location != null)
                {
                    location = new Location();
                    location.CopyPropertiesFrom(locpGroupLocation.Location);
                }
            }

            if (location != null)
            {
                GroupLocation groupLocation = null;

                Guid guid = hfAddLocationGroupGuid.Value.AsGuid();
                if (!guid.IsEmpty())
                {
                    groupLocation = GroupLocationsState.FirstOrDefault(l => l.Guid.Equals(guid));
                }

                if (groupLocation == null)
                {
                    groupLocation = new GroupLocation();
                    GroupLocationsState.Add(groupLocation);
                }

                groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                groupLocation.Location   = location;
                groupLocation.LocationId = groupLocation.Location.Id;
                groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();

                var selectedIds = spSchedules.SelectedValuesAsInt();
                groupLocation.Schedules = new ScheduleService(rockContext).Queryable()
                                          .Where(s => selectedIds.Contains(s.Id)).ToList();

                if (groupLocation.GroupLocationTypeValueId.HasValue)
                {
                    groupLocation.GroupLocationTypeValue = new DefinedValue();
                    var definedValue = new DefinedValueService(rockContext).Get(groupLocation.GroupLocationTypeValueId.Value);
                    if (definedValue != null)
                    {
                        groupLocation.GroupLocationTypeValue.CopyPropertiesFrom(definedValue);
                    }
                }
            }

            BindLocationsGrid();

            dlgLocations.Hide();
            hfActiveDialog.Value = string.Empty;
        }
Example #8
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var    personService = new PersonService(rockContext);
            Person business      = null;

            if (int.Parse(hfBusinessId.Value) != 0)
            {
                business = personService.Get(int.Parse(hfBusinessId.Value));
            }

            if (business == null)
            {
                business = new Person();
                personService.Add(business);
                tbBusinessName.Text = tbBusinessName.Text.FixCase();
            }

            // Business Name
            business.LastName = tbBusinessName.Text;

            // Phone Number
            var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

            var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
            {
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = businessPhoneTypeId
                    };
                    business.PhoneNumbers.Add(phoneNumber);
                }
                phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                phoneNumber.IsMessagingEnabled = cbSms.Checked;
                phoneNumber.IsUnlisted         = cbUnlisted.Checked;
            }
            else
            {
                if (phoneNumber != null)
                {
                    business.PhoneNumbers.Remove(phoneNumber);
                    new PhoneNumberService(rockContext).Delete(phoneNumber);
                }
            }

            // Record Type - this is always "business". it will never change.
            business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

            // Record Status
            business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();;

            // Record Status Reason
            int?newRecordStatusReasonId = null;

            if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
            {
                newRecordStatusReasonId = dvpReason.SelectedValueAsInt();
            }
            business.RecordStatusReasonValueId = newRecordStatusReasonId;

            // Email
            business.IsEmailActive   = true;
            business.Email           = tbEmail.Text.Trim();
            business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

            avcEditAttributes.GetEditValues(business);

            if (!business.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        if (cbSaveFormerAddressAsPreviousAddress.Checked)
                        {
                            GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now);
                        }

                        groupLocationService.Delete(workLocation);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    else
                    {
                        // Save this to history if the box is checked and the new info is different than the current one.
                        if (cbSaveFormerAddressAsPreviousAddress.Checked && newLocation.Id != workLocation.Location.Id)
                        {
                            new GroupLocationHistoricalService(rockContext).Add(GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now));
                        }
                    }

                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

            /* Ethan Drotning 2022-01-11
             * Need save the PersonSearchKeys outside of the transaction since the DB might not have READ_COMMITTED_SNAPSHOT enabled.
             */

            // PersonSearchKey
            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var validSearchTypes       = GetValidSearchKeyTypes();
            var databaseSearchKeys     = personSearchKeyService.Queryable().Where(a => a.PersonAlias.PersonId == business.Id && validSearchTypes.Contains(a.SearchTypeValue.Guid)).ToList();

            foreach (var deletedSearchKey in databaseSearchKeys.Where(a => !PersonSearchKeysState.Any(p => p.Guid == a.Guid)))
            {
                personSearchKeyService.Delete(deletedSearchKey);
            }

            foreach (var personSearchKey in PersonSearchKeysState.Where(a => !databaseSearchKeys.Any(d => d.Guid == a.Guid)))
            {
                personSearchKey.PersonAliasId = business.PrimaryAliasId.Value;
                personSearchKeyService.Add(personSearchKey);
            }

            rockContext.SaveChanges();

            business.SaveAttributeValues();

            var queryParams = new Dictionary <string, string>
            {
                { "BusinessId", hfBusinessId.Value }
            };

            NavigateToCurrentPage(queryParams);
        }
        /// <summary>
        /// Maps the Individual Giftedness.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapIndividualGiftedness(IQueryable <Row> tableData)
        {
            var lookupContext    = new RockContext();
            var attributeService = new AttributeService(lookupContext);

            int rank1Id = attributeService.Queryable().Where(a => a.Key == "Rank1").FirstOrDefault().Id;
            int rank2Id = attributeService.Queryable().Where(a => a.Key == "Rank2").FirstOrDefault().Id;
            int rank3Id = attributeService.Queryable().Where(a => a.Key == "Rank3").FirstOrDefault().Id;
            int rank4Id = attributeService.Queryable().Where(a => a.Key == "Rank4").FirstOrDefault().Id;



            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Giftedness Program import ({0:N0} found).", totalRows));

            var newAttributeValueList = new List <AttributeValue>();

            foreach (var row in tableData)
            {
                int?individualId      = row["Individual_ID"] as int?;
                int personId          = (int)GetPersonAliasId(individualId);
                var newAttributeValue = new AttributeValue();
                int?rank   = row["Rank"] as int?;
                int rankId = 0;

                //not everyone has all 4 ranks, some are missing the fourth and that was causing it to run in the below if condition and try to create a duplicate record.
                if (rank == 1)
                {
                    rankId = rank1Id;
                }
                if (rank == 2)
                {
                    rankId = rank2Id;
                }
                if (rank == 3)
                {
                    rankId = rank3Id;
                }
                if (rank == 4)
                {
                    rankId = rank4Id;
                }


                if (personId != 0 && rankId != 0)
                {
                    var attributeValueService = new AttributeValueService(lookupContext);

                    //checks if they are in the database already or if there is a record currently in the newAttributeValueList
                    if (attributeValueService.Queryable().Where(a => a.AttributeId == rankId && a.EntityId == personId).FirstOrDefault() == null && newAttributeValueList.Find(a => a.AttributeId == rankId && a.EntityId == personId) == null)
                    {
                        DateTime?assessmentDate        = row["AssessmentDate"] as DateTime?;
                        int?     giftAttributeId       = row["GiftAttributeID"] as int?;
                        string   giftAttributeIdString = Convert.ToString(giftAttributeId);



                        var definedValueService = new DefinedValueService(lookupContext);


                        newAttributeValue.IsSystem = false;
                        newAttributeValue.EntityId = personId;

                        if (rank == 1)
                        {
                            newAttributeValue.AttributeId = rank1Id;
                        }
                        if (rank == 2)
                        {
                            newAttributeValue.AttributeId = rank2Id;
                        }
                        if (rank == 3)
                        {
                            newAttributeValue.AttributeId = rank3Id;
                        }
                        if (rank == 4)
                        {
                            newAttributeValue.AttributeId = rank4Id;
                        }

                        newAttributeValue.Value           = Convert.ToString(definedValueService.Queryable().Where(a => a.ForeignId == giftAttributeIdString).FirstOrDefault().Guid);
                        newAttributeValue.CreatedDateTime = assessmentDate;

                        newAttributeValueList.Add(newAttributeValue);
                        completed++;
                    }
                }
                if (newAttributeValueList.Any())
                {
                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        var rockContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.AttributeValues.AddRange(newAttributeValueList);
                            rockContext.SaveChanges(DisableAudit);
                            newAttributeValueList.Clear();
                        });
                        ReportPartialProgress();
                    }
                }
            }

            if (newAttributeValueList.Any())
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    rockContext.AttributeValues.AddRange(newAttributeValueList);
                    rockContext.SaveChanges(DisableAudit);
                });
            }

            ReportProgress(100, string.Format("Finished individual gifts import: {0:N0} spiritual gifts imported.", completed));
        }
        /// <summary>
        /// Maps the Giftedness Program.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapGiftednessProgram(IQueryable <Row> tableData)
        {
            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Giftedness Program import ({0:N0} found).", totalRows));

            foreach (var row in tableData)
            {
                var rockContext      = new RockContext();
                var categoryList     = new CategoryService(rockContext).Queryable().ToList();
                var attributeList    = new AttributeService(rockContext).Queryable().ToList();
                var definedTypeList  = new DefinedTypeService(rockContext).Queryable().ToList();
                var definedValueList = new DefinedValueService(rockContext).Queryable().ToList();

                //check if category exists
                string category = row["CategoryName"] as string;
                if (categoryList.Find(c => c.Name == category) == null)
                {
                    var entityType = new EntityTypeService(rockContext);
                    //creates if category doesn't exist
                    var newCategory = new Category();
                    newCategory.IsSystem     = false;
                    newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault();
                    newCategory.EntityTypeQualifierColumn = "EntityTypeId";
                    newCategory.EntityTypeQualifierValue  = Convert.ToString(PersonEntityTypeId);   //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault());
                    newCategory.Name        = category;
                    newCategory.Description = "Contains the spiritual gifts attributes";

                    //var newCategoryContext = new RockContext();
                    //newCategoryContext.WrapTransaction( () =>
                    //{
                    //    newCategoryContext.Configuration.AutoDetectChangesEnabled = false;
                    //    newCategoryContext.Categories.Add( newCategory );
                    //    newCategoryContext.SaveChanges( DisableAudit );
                    //} );
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Categories.Add(newCategory);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //Check if Attribute exists
                if (attributeList.Find(a => a.Key == "Rank1") == null || attributeList.Find(a => a.Key == "Rank2") == null || attributeList.Find(a => a.Key == "Rank3") == null || attributeList.Find(a => a.Key == "Rank4") == null)
                {
                    var fieldType        = new FieldTypeService(rockContext);
                    var newAttributeList = new List <Rock.Model.Attribute>();
                    var fieldTypeId      = fieldType.Queryable().Where(e => e.Name == "Defined Value").FirstOrDefault().Id;
                    var category2        = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Spiritual Gifts").FirstOrDefault();


                    if (attributeList.Find(a => a.Key == "Rank1") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank1";
                        newAttribute.Name                      = "Rank 1";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 1";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank2") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank2";
                        newAttribute.Name                      = "Rank 2";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 2";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank3") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank3";
                        newAttribute.Name                      = "Rank 3";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 3";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank4") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank4";
                        newAttribute.Name                      = "Rank 4";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 4";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);


                        newAttributeList.Add(newAttribute);
                    }

                    if (newAttributeList.Any())
                    {
                        //var newAttributeContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Attributes.AddRange(newAttributeList);
                            rockContext.SaveChanges(DisableAudit);
                            newAttributeList.Clear();
                        });
                    }
                }
                //checks if Defined Type exists
                if (definedTypeList.Find(d => d.Name == "Spiritual Gifts") == null)
                {
                    var fieldTypeService = new FieldTypeService(rockContext);

                    //creates Defined Type
                    var newDefinedType = new DefinedType();
                    newDefinedType.IsSystem    = false;
                    newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where(f => f.Name == "Text").Select(f => f.Id).FirstOrDefault();
                    newDefinedType.Name        = "Spiritual Gifts";
                    newDefinedType.Description = "Defined Type for Spiritual Gifts values";
                    newDefinedType.CategoryId  = categoryList.Find(c => c.Name == "Person").Id;

                    //var newDTContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedTypes.Add(newDefinedType);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //checks if Defined Value exists
                var    spiritualGiftsDefineType = new DefinedTypeService(rockContext).Queryable().Where(d => d.Name == "Spiritual Gifts").FirstOrDefault();
                string attributeName            = row["AttributeName"] as string;
                int?   giftAttributeId          = row["GiftAttributeID"] as int?;
                if (definedValueList.Find(d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName) == null)
                {
                    var definedTypeService = new DefinedTypeService(rockContext);
                    //creates Defined Value
                    var newDefinedValue = new DefinedValue();
                    newDefinedValue.IsSystem      = false;
                    newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where(d => d.Name == "Spiritual Gifts").Select(d => d.Id).FirstOrDefault();
                    newDefinedValue.Value         = attributeName;
                    newDefinedValue.Description   = "Spiritual Gift attribute value: " + attributeName;
                    newDefinedValue.ForeignId     = Convert.ToString(giftAttributeId);

                    //var newDVContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedValues.Add(newDefinedValue);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }

                completed++;

                if (completed % percentage < 1)
                {
                    int percentComplete = completed / percentage;
                    ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete));
                }
                else if (completed % ReportingNumber < 1)
                {
                    ReportPartialProgress();
                }
            }

            ReportProgress(100, string.Format("Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed));
        }
        public void Execute(IJobExecutionContext context)
        {
            var rockContext     = new RockContext();
            var dataMap         = context.JobDetail.JobDataMap;
            var systemEmailGuid = dataMap.GetString("Email").AsGuidOrNull();
            var groupFieldGuid  = dataMap.GetString("RootGroup").AsGuidOrNull();

            string appRoot = GlobalAttributesCache.Read().GetValue("ExternalApplicationRoot");

            if (systemEmailGuid == null)
            {
                throw new Exception("A system email template needs to be set.");
            }
            var systemEmailTemplate = new SystemEmailService(rockContext).Get(systemEmailGuid.Value);

            if (systemEmailTemplate == null)
            {
                throw new Exception("The system email template setting is not a valid system email template.");
            }

            if (groupFieldGuid == null)
            {
                throw new Exception("A group must be specified");
            }

            var groupService  = new GroupService(rockContext);
            var rootGroup     = groupService.GetByGuid(groupFieldGuid.Value);
            var validGroupIds = new List <int> {
                rootGroup.Id
            };

            validGroupIds.AddRange(groupService.GetAllDescendents(rootGroup.Id).Select(g => g.Id));

            // Check to see if we should skip this week
            var definedTypeId = new DefinedTypeService(rockContext).Queryable().FirstOrDefault(dt => dt.Name == "Volunteer Reminder Exclusions")?.Id;

            if (definedTypeId == null)
            {
                context.Result = "Could not get Volunteer Reminder Exclusions defined type";
                return;
            }
            var datesToSkip = new DefinedValueService(rockContext).GetByDefinedTypeId(definedTypeId.Value);

            foreach (var dateToSkipValue in datesToSkip)
            {
                dateToSkipValue.LoadAttributes();
                var date = dateToSkipValue.GetAttributeValue("Date").AsDateTime();
                if (date != null && DatesAreInTheSameWeek(date.Value, RockDateTime.Today))
                {
                    context.Result = "This week should be skipped because of the exclusion " + date.Value.ToString("o");
                    return;
                }
            }


            string weekTeam         = "Team " + Utils.ServingWeek.GetTeamNumber();
            var    attributeService = new AttributeService(rockContext);
            var    attributeIds     =
                attributeService.GetByEntityTypeId(
                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id).Where(a => a.Key == "AssignedTeam").Select(a => a.Id);
            var attributeValueService = new AttributeValueService(rockContext);
            var groupMemberIds        = new List <int>();

            foreach (int attributeId in attributeIds)
            {
                var attributeValues = attributeValueService.GetByAttributeId(attributeId).AsQueryable().AsNoTracking().Where(av => av.Value.Contains(weekTeam));
                groupMemberIds.AddRange(attributeValues.Where(av => av.EntityId != null).Select(av => av.EntityId.Value));
            }


            var groupMembers = new GroupMemberService(rockContext).GetListByIds(groupMemberIds).Where(gm => validGroupIds.Contains(gm.GroupId)).Distinct();
            int mailedCount  = 0;

            foreach (var groupMember in groupMembers)
            {
                var mergeFields = new Dictionary <string, object>
                {
                    { "GroupMember", groupMember },
                    { "Person", groupMember.Person },
                    { "Group", groupMember.Group }
                };

                var recipients = new List <string> {
                    groupMember.Person.Email
                };

                Email.Send(systemEmailTemplate.From.ResolveMergeFields(mergeFields), systemEmailTemplate.FromName.ResolveMergeFields(mergeFields), systemEmailTemplate.Subject.ResolveMergeFields(mergeFields), recipients, systemEmailTemplate.Body.ResolveMergeFields(mergeFields), appRoot, null, null);
                mailedCount++;
            }
            context.Result = string.Format("{0} reminders were sent ", mailedCount);
        }
Example #12
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                var communication = new CommunicationService(rockContext).Get(CommunicationId);

                if (communication != null && communication.Status == CommunicationStatus.PendingApproval)
                {
                    // get notification group
                    var approvers = new GroupService(rockContext).Get(SystemGuid.Group.GROUP_COMMUNICATION_APPROVERS.AsGuid());

                    if (approvers != null)
                    {
                        var mergeFields = new Dictionary <string, object>();

                        var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(null);
                        globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value));

                        string fromName             = Rock.Web.Cache.GlobalAttributesCache.Value("OrganizationName");
                        string fromEmail            = Rock.Web.Cache.GlobalAttributesCache.Value("OrganizationEmail");
                        string subject              = "Pending Communication Requires Approval";
                        var    appRoot              = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot");
                        string communicationDetails = string.Empty;
                        string typeName             = string.Empty;

                        // get custom details by type
                        switch (communication.Medium.TypeName)
                        {
                        case "Rock.Communication.Medium.Email":
                            string emailFromName    = communication.GetMediumDataValue("FromName");
                            string emailFromAddress = communication.GetMediumDataValue("FromAddress");
                            communicationDetails = string.Format(@"
                                        <strong>From Name:</strong> {0}<br/>
                                        <strong>From Address:</strong> {1}<br/>
                                        <strong>Subject:</strong> {2}<br/>"
                                                                 , emailFromName
                                                                 , emailFromAddress
                                                                 , communication.Subject);
                            typeName = "Email";
                            break;

                        case "Rock.Communication.Medium.Sms":
                            int fromValueId = communication.GetMediumDataValue("FromValue").AsInteger();
                            var fromValue   = new DefinedValueService(rockContext).Get(fromValueId);
                            typeName = "SMS";

                            if (fromValue != null)
                            {
                                communicationDetails = string.Format("<strong>SMS Number:</strong> {0} ({1})<br/>", fromValue.Description, fromValue.Value);
                            }
                            break;
                        }

                        // create approval link if one was not provided
                        if (ApprovalPageUrl == null)
                        {
                            ApprovalPageUrl = string.Format("{0}Communication/{1}", Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"), communication.Id);
                        }


                        foreach (var approver in approvers.Members)
                        {
                            string message = string.Format(@"
                                    {{{{ 'Global' | Attribute:'EmailHeader' }}}}
                            
                                    <p>{0}:</p>

                                    <p>A new communication requires approval. Information about this communication can be found below.</p>

                                    <p>
                                        <strong>From:</strong> {1}<br />
                                        <strong>Type:</strong> {2}<br />
                                        {3}
                                        <strong>Recipient Count:</strong> {4}<br />
                                    </p>

                                    <p>
                                        <a href='{5}'>View Communication</a>
                                    </p>
    
                                    {{{{ 'Global' | Attribute:'EmailFooter' }}}}",
                                                           approver.Person.NickName,
                                                           communication.SenderPersonAlias.Person.FullName,
                                                           typeName,
                                                           communicationDetails,
                                                           communication.GetRecipientCount(rockContext),
                                                           ApprovalPageUrl);

                            var recipients = new List <string>();
                            recipients.Add(approver.Person.Email);

                            Email.Send(fromEmail, fromName, subject, recipients, message.ResolveMergeFields(mergeFields), appRoot, string.Empty, null, false);
                        }
                    }
                }
            }
        }
Example #13
0
        /// <summary>
        /// Loads the group type data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadGroupType(CSVInstance csvData)
        {
            // Required variables
            var lookupContext     = new RockContext();
            var newGroupTypeList  = new List <GroupType>();
            var purposeTypeValues = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.GROUPTYPE_PURPOSE), lookupContext).DefinedValues;
            var locationMeetingId = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION), lookupContext).Id;

            var numImportedGroupTypes = ImportedGroupTypes.Count();
            var completed             = 0;

            ReportProgress(0, $"Starting group type import ({numImportedGroupTypes:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowGroupTypeKey    = row[GroupTypeId];
                var groupTypeForeignId = rowGroupTypeKey.AsType <int?>();

                // Check that this group type isn't already in our data
                var groupTypeExists = false;
                if (numImportedGroupTypes > 0)
                {
                    groupTypeExists = ImportedGroupTypes.Any(t => t.ForeignKey == rowGroupTypeKey);
                }

                if (!groupTypeExists)
                {
                    var rowGroupTypeName = row[GroupTypeName].Left(100);

                    var newGroupType = new GroupType
                    {
                        // set required properties (terms set by default)
                        IsSystem = false,
                        Name     = rowGroupTypeName,
                        Order    = 1000 + completed,

                        // set optional properties
                        CreatedDateTime         = ParseDateOrDefault(row[GroupTypeCreatedDate], ImportDateTime),
                        ModifiedDateTime        = ImportDateTime,
                        CreatedByPersonAliasId  = ImportPersonAliasId,
                        ModifiedByPersonAliasId = ImportPersonAliasId,
                        ForeignKey = rowGroupTypeKey,
                        ForeignId  = groupTypeForeignId
                    };

                    // set meeting location
                    var definedValueService = new DefinedValueService(lookupContext);
                    newGroupType.LocationTypes = new List <GroupTypeLocationType>();
                    newGroupType.LocationTypes.Clear();
                    var meetingLocationType = definedValueService.Get(locationMeetingId);
                    if (meetingLocationType != null)
                    {
                        newGroupType.LocationTypes.Add(new GroupTypeLocationType {
                            LocationTypeValueId = meetingLocationType.Id
                        });
                    }

                    // set provided optional properties
                    newGroupType.TakesAttendance = ( bool )ParseBoolOrDefault(row[GroupTypeTakesAttendance], false);
                    newGroupType.AttendanceCountsAsWeekendService = ( bool )ParseBoolOrDefault(row[GroupTypeWeekendService], false);
                    newGroupType.ShowInGroupList  = ( bool )ParseBoolOrDefault(row[GroupTypeShowInGroupList], false);
                    newGroupType.ShowInNavigation = ( bool )ParseBoolOrDefault(row[GroupTypeShowInNav], false);

                    // set schedule
                    var allowGroupScheduleWeekly = ( bool )ParseBoolOrDefault(row[GroupTypeWeeklySchedule], false);
                    if (allowGroupScheduleWeekly)
                    {
                        newGroupType.AllowedScheduleTypes = ScheduleType.Weekly;
                    }

                    var rowGroupTypePurpose = row[GroupTypePurpose];
                    if (!string.IsNullOrWhiteSpace(rowGroupTypePurpose))
                    {
                        var purposeId = purposeTypeValues.Where(v => v.Value.Equals(rowGroupTypePurpose) || v.Id.Equals(rowGroupTypePurpose) || v.Guid.ToString().ToLower().Equals(rowGroupTypePurpose.ToLower()))
                                        .Select(v => ( int? )v.Id).FirstOrDefault();

                        newGroupType.GroupTypePurposeValueId = purposeId;
                    }

                    var inheritedGroupType = GroupTypeCache.Get(LoadGroupTypeId(lookupContext, row[GroupTypeInheritedGroupType]));
                    if (inheritedGroupType.Id != GroupTypeCache.Get(new Guid("8400497B-C52F-40AE-A529-3FCCB9587101"), lookupContext).Id)
                    {
                        newGroupType.InheritedGroupTypeId = inheritedGroupType.Id;
                    }

                    // add default role of member
                    var defaultRoleGuid = Guid.NewGuid();
                    var memberRole      = new GroupTypeRole {
                        Guid = defaultRoleGuid, Name = "Member"
                    };
                    newGroupType.Roles.Add(memberRole);

                    // save changes each loop
                    newGroupTypeList.Add(newGroupType);

                    lookupContext.WrapTransaction(() =>
                    {
                        lookupContext.GroupTypes.AddRange(newGroupTypeList);
                        lookupContext.SaveChanges(DisableAuditing);
                    });

                    // Set Parent Group Type
                    var rowGroupTypeParentId = row[GroupTypeParentId];
                    if (!string.IsNullOrWhiteSpace(rowGroupTypeParentId))
                    {
                        var parentGroupType     = ImportedGroupTypes.FirstOrDefault(t => t.ForeignKey.Equals(rowGroupTypeParentId));
                        var parentGroupTypeList = new List <GroupType>();
                        parentGroupTypeList.Add(parentGroupType);
                        newGroupType.ParentGroupTypes = parentGroupTypeList;
                    }

                    // Set Self Reference
                    bool selfRef;
                    TryParseBool(row[GroupTypeSelfReference], out selfRef);
                    if (selfRef)
                    {
                        var selfReferenceList = new List <GroupType>();
                        selfReferenceList.Add(newGroupType);
                        newGroupType.ChildGroupTypes = selfReferenceList;
                    }

                    // set default role
                    newGroupType.DefaultGroupRole = newGroupType.Roles.FirstOrDefault();

                    // save changes
                    lookupContext.SaveChanges();

                    // add these new groups to the global list
                    ImportedGroupTypes.AddRange(newGroupTypeList);

                    newGroupTypeList.Clear();

                    //
                    // Keep the user informed as to what is going on and save in batches.
                    //
                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, $"{completed:N0} groups imported.");
                    }

                    if (completed % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }
            }

            ReportProgress(0, $"Finished group type import: {completed:N0} group types added or updated.");

            return(completed);
        }
Example #14
0
        /// <summary>
        /// Handles the Click event of the btnDefault control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDefault_Click(object sender, EventArgs e)
        {
            var bioBlock = BlockCache.Get(Rock.SystemGuid.Block.BIO.AsGuid());

            // Record an exception if the stock Bio block has been deleted but continue processing
            // the remaining settings.
            if (bioBlock == null)
            {
                var errorMessage = string.Format("Stock Bio block ({0}) is missing.", Rock.SystemGuid.Block.BIO);
                ExceptionLogService.LogException(new Exception(errorMessage));
            }
            else
            {
                List <Guid> workflowActionGuidList = bioBlock.GetAttributeValues("WorkflowActions").AsGuidList();
                if (workflowActionGuidList == null || workflowActionGuidList.Count == 0)
                {
                    // Add to Bio Workflow Actions
                    bioBlock.SetAttributeValue("WorkflowActions", Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY);
                    ///BackgroundCheckContainer.Instance.Components
                }
                else
                {
                    //var workflowActionValues = workflowActionValue.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                    Guid guid = Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid();
                    if (!workflowActionGuidList.Any(w => w == guid))
                    {
                        // Add Checkr to Bio Workflow Actions
                        workflowActionGuidList.Add(guid);
                    }

                    // Remove PMM from Bio Workflow Actions
                    guid = CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid();
                    workflowActionGuidList.RemoveAll(w => w == guid);
                    bioBlock.SetAttributeValue("WorkflowActions", workflowActionGuidList.AsDelimited(","));
                }

                bioBlock.SaveAttributeValue("WorkflowActions");
            }

            string pmmTypeName  = (typeof(Rock.Security.BackgroundCheck.ProtectMyMinistry)).FullName;
            var    pmmComponent = BackgroundCheckContainer.Instance.Components.Values.FirstOrDefault(c => c.Value.TypeName == pmmTypeName);

            pmmComponent.Value.SetAttributeValue("Active", "True");
            pmmComponent.Value.SaveAttributeValue("Active");
            // Set as the default provider in the system setting
            SystemSettings.SetValue(Rock.SystemKey.SystemSetting.DEFAULT_BACKGROUND_CHECK_PROVIDER, pmmTypeName);

            using (var rockContext = new RockContext())
            {
                WorkflowTypeService workflowTypeService = new WorkflowTypeService(rockContext);
                // Rename PMM Workflow
                var pmmWorkflowAction = workflowTypeService.Get(Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid());
                pmmWorkflowAction.Name = "Background Check";

                var checkrWorkflowAction = workflowTypeService.Get(CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid());
                // Rename Checkr Workflow
                checkrWorkflowAction.Name = CheckrConstants.CHECKR_WORKFLOW_TYPE_NAME;

                rockContext.SaveChanges();

                // Enable PMM packages and disable Checkr packages
                DefinedValueService definedValueService = new DefinedValueService(rockContext);
                var packages = definedValueService
                               .GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.BACKGROUND_CHECK_TYPES.AsGuid())
                               .ToList();

                foreach (var package in packages)
                {
                    package.IsActive = package.ForeignId == 1;
                }

                rockContext.SaveChanges();
            }

            ShowDetail();
        }
Example #15
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap     = context.JobDetail.JobDataMap;
            var        rockContext = new RockContext();

            var hospitalWorkflow             = dataMap.GetString("HospitalAdmissionWorkflow").AsGuidOrNull();
            var nursingHomeAdmissionWorkflow = dataMap.GetString("NursingHomeResidentWorkflow").AsGuidOrNull();
            var homeBoundPersonWorkflow      = dataMap.GetString("HomeboundPersonWorkflow").AsGuidOrNull();

            var workflowService       = new WorkflowService(rockContext);
            var attributeService      = new AttributeService(rockContext);
            var attributeValueService = new AttributeValueService(rockContext);
            var personAliasService    = new PersonAliasService(rockContext);
            var personService         = new PersonService(rockContext);
            var definedValueService   = new DefinedValueService(rockContext);

            var workflowTypesIdAsStrings = new WorkflowTypeService(rockContext).Queryable()
                                           .Where(wt =>
                                                  wt.Guid == hospitalWorkflow ||
                                                  wt.Guid == nursingHomeAdmissionWorkflow ||
                                                  wt.Guid == homeBoundPersonWorkflow
                                                  )
                                           .ToList()
                                           .Select(wf => wf.Id.ToString())
                                           .ToList();

            var attributeIds = attributeService.Queryable()
                               .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && workflowTypesIdAsStrings.Contains(a.EntityTypeQualifierValue))
                               .Select(a => a.Id).ToList();

            var wfTmpqry = workflowService.Queryable().AsNoTracking()
                           .Where(w => (
                                      w.WorkflowType.Guid == hospitalWorkflow ||
                                      w.WorkflowType.Guid == nursingHomeAdmissionWorkflow ||
                                      w.WorkflowType.Guid == homeBoundPersonWorkflow
                                      ) && (w.Status == "Active"));

            var tqry = wfTmpqry.Join(attributeValueService.Queryable(),
                                     obj => obj.Id,
                                     av => av.EntityId.Value,
                                     (obj, av) => new { Workflow = obj, AttributeValue = av })
                       .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                       .GroupBy(obj => obj.Workflow)
                       .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });
            var qry = tqry.ToList();

            var newQry = qry.Select(w => new
            {
                Workflow = w.Workflow,
                Person   = GetPerson(personAliasService, w.AttributeValues)
            });

            var workflowsToClose = newQry
                                   .Where(cd => cd.Person.IsDeceased && cd.Workflow.CompletedDateTime == null)
                                   .Select(cd => cd.Workflow)
                                   .ToList();

            foreach (var workflow in workflowsToClose)
            {
                workflow.MarkComplete();
            }

            rockContext.SaveChanges();

            context.Result = string.Format("Closed {0} workflows.", workflowsToClose.Count());
        }
Example #16
0
        /// <summary>
        /// Shows the edit value.
        /// </summary>
        /// <param name="valueId">The value id.</param>
        protected void ShowEditValue(int valueId)
        {
            phAttrControl.Controls.Clear();

            AttributeValueService attributeValueService = new AttributeValueService();
            AttributeService      attributeService      = new AttributeService();

            var valueModel    = new DefinedValueService().Get(valueId);
            var value         = Rock.Web.Cache.DefinedValueCache.Read(valueModel);
            var attributeList = attributeService
                                .Get(_entityTypeId, _entityQualifier, hfIdType.Value)
                                .ToArray();

            //int i = 0;
            // add control for each attribute associated with the defined type
            foreach (var attribute in attributeList)
            {
                var fieldType = Rock.Web.Cache.FieldTypeCache.Read(attribute.FieldType);
                if (fieldType != null)
                {
                    var configControls = fieldType.Field.ConfigurationControls();

                    /*
                     *
                     * var ctrlGroup = new HtmlGenericControl( "div" );
                     * phAttrControl.Controls.Add( ctrlGroup );
                     * ctrlGroup.AddCssClass( "control-group" );
                     *
                     * var lbl = new Label();
                     * ctrlGroup.Controls.Add( lbl );
                     * lbl.AddCssClass( "control-label" );
                     * lbl.Text = attribute.Name;
                     *
                     * var ctrls = new HtmlGenericControl( "div" );
                     * ctrlGroup.Controls.Add( ctrls );
                     * ctrls.AddCssClass( "controls" );
                     *
                     * Control control = configControls[i];
                     * ctrls.Controls.Add( control );
                     * control.ID = "configControl_" + attribute.Key;
                     * i++;
                     *
                     *
                     */
                }
            }

            if (valueModel != null)
            {
                hfIdValue.Value         = valueId.ToString();
                tbValueName.Text        = value.Name;
                tbValueDescription.Text = value.Description;
            }
            else
            {
                hfIdValue.Value         = string.Empty;
                tbValueName.Text        = string.Empty;
                tbValueDescription.Text = string.Empty;
            }

            modalValues.Show();
        }
Example #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage"));
            var discPageReference  = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage"));

            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
            {
                //Load the person based on the FormId
                var personInUrl = PageParameter("FormId");
                SelectedPerson   = GetPersonFromForm(personInUrl);
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
            {
                //Load the person based on the PersonId
                SelectedPerson   = GetPersonFromId(PageParameter("PersonId"));
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else if (CurrentPerson != null)
            {
                //Load the person based on the currently logged in person
                SelectedPerson   = CurrentPerson;
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else
            {
                //Show Error Message
                nbNoPerson.Visible = true;
                Response.Redirect(shapePageReference.BuildUrl(), true);
                return;
            }



            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService   definedValueService   = new DefinedValueService(rockContext);



            string spiritualGift1  = "";
            string spiritualGift2  = "";
            string spiritualGift3  = "";
            string spiritualGift4  = "";
            string heartCategories = "";
            string heartCauses     = "";
            string heartPassion    = "";
            string ability1        = "";
            string ability2        = "";
            string people          = "";
            string places          = "";
            string events          = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            // Redirect if they haven't taken the Assessment
            if (spiritualGift1AttributeValue == null)
            {
                Response.Redirect(shapePageReference.BuildUrl(), true);
            }

            else
            {
                var spiritualGift2AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

                var spiritualGift3AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

                var spiritualGift4AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

                var ability1AttributeValue =
                    attributeValueService
                    .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

                var ability2AttributeValue =
                    attributeValueService
                    .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

                var peopleAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

                var placesAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

                var eventsAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

                var heartCategoriesAttributeValue = attributeValueService
                                                    .Queryable()
                                                    .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

                var heartCausesAttributeValue = attributeValueService
                                                .Queryable()
                                                .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

                var heartPassionAttributeValue = attributeValueService
                                                 .Queryable()
                                                 .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);


                if (spiritualGift1AttributeValue.Value != null)
                {
                    spiritualGift1 = spiritualGift1AttributeValue.Value;
                }
                if (spiritualGift2AttributeValue.Value != null)
                {
                    spiritualGift2 = spiritualGift2AttributeValue.Value;
                }
                if (spiritualGift3AttributeValue.Value != null)
                {
                    spiritualGift3 = spiritualGift3AttributeValue.Value;
                }
                if (spiritualGift4AttributeValue.Value != null)
                {
                    spiritualGift4 = spiritualGift4AttributeValue.Value;
                }
                if (heartCategoriesAttributeValue.Value != null)
                {
                    heartCategories = heartCategoriesAttributeValue.Value;
                }
                if (heartCausesAttributeValue.Value != null)
                {
                    heartCauses = heartCausesAttributeValue.Value;
                }
                if (heartPassionAttributeValue.Value != null)
                {
                    heartPassion = heartPassionAttributeValue.Value;
                }
                if (ability1AttributeValue.Value != null)
                {
                    ability1 = ability1AttributeValue.Value;
                }
                if (ability2AttributeValue.Value != null)
                {
                    ability2 = ability2AttributeValue.Value;
                }
                if (peopleAttributeValue.Value != null)
                {
                    people = peopleAttributeValue.Value;
                }
                if (placesAttributeValue.Value != null)
                {
                    places = placesAttributeValue.Value;
                }
                if (eventsAttributeValue.Value != null)
                {
                    events = eventsAttributeValue.Value;
                }

                string spiritualGift1Guid;
                string spiritualGift2Guid;
                string spiritualGift3Guid;
                string spiritualGift4Guid;
                string ability1Guid;
                string ability2Guid;


                // Check to see if there are already values saved as an ID.  If so, convert them to GUID
                if (spiritualGift1.ToString().Length < 5)
                {
                    if (spiritualGift1 != null)
                    {
                        SpiritualGift1 = Int32.Parse(spiritualGift1);
                    }
                    if (spiritualGift2 != null)
                    {
                        SpiritualGift2 = Int32.Parse(spiritualGift2);
                    }
                    if (spiritualGift3 != null)
                    {
                        SpiritualGift3 = Int32.Parse(spiritualGift3);
                    }
                    if (spiritualGift4 != null)
                    {
                        SpiritualGift4 = Int32.Parse(spiritualGift4);
                    }
                    if (ability1 != null)
                    {
                        Ability1 = Int32.Parse(ability1);
                    }
                    if (ability2 != null)
                    {
                        Ability2 = Int32.Parse(ability2);
                    }

                    var intsOfGifts =
                        definedValueService.GetByIds(new List <int>
                    {
                        SpiritualGift1,
                        SpiritualGift2,
                        SpiritualGift3,
                        SpiritualGift4,
                        Ability1,
                        Ability2
                    });

                    spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                    spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                    spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                    spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                    ability1Guid       = intsOfGifts.ToList()[Ability1].Guid.ToString();
                    ability2Guid       = intsOfGifts.ToList()[Ability2].Guid.ToString();
                }
                else
                {
                    spiritualGift1Guid = spiritualGift1;
                    spiritualGift2Guid = spiritualGift2;
                    spiritualGift3Guid = spiritualGift3;
                    spiritualGift4Guid = spiritualGift4;
                    ability1Guid       = ability1;
                    ability2Guid       = ability2;
                }



                // Get all of the data about the assiciated gifts and ability categories
                var shapeGift1Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift1Guid)
                }).FirstOrDefault();
                var shapeGift2Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift2Guid)
                }).FirstOrDefault();
                var shapeGift3Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift3Guid)
                }).FirstOrDefault();
                var shapeGift4Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift4Guid)
                }).FirstOrDefault();
                var ability1Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(ability1Guid)
                }).FirstOrDefault();
                var ability2Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(ability2Guid)
                }).FirstOrDefault();


                shapeGift1Object.LoadAttributes();
                shapeGift2Object.LoadAttributes();
                shapeGift3Object.LoadAttributes();
                shapeGift4Object.LoadAttributes();
                ability1Object.LoadAttributes();
                ability2Object.LoadAttributes();


                // Get heart choices Values from Guids
                string heartCategoriesString = "";
                if (!heartCategories.IsNullOrWhiteSpace())
                {
                    string[] heartCategoryArray = heartCategories.Split(',');
                    foreach (string category in heartCategoryArray)
                    {
                        var definedValueObject =
                            definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                        if (category.Equals(heartCategoryArray.Last()))
                        {
                            heartCategoriesString += definedValueObject.Value;
                        }
                        else
                        {
                            heartCategoriesString += definedValueObject.Value + ", ";
                        }
                    }
                }


                // Get Volunteer Opportunities

                string gift1AssociatedVolunteerOpportunities =
                    shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift2AssociatedVolunteerOpportunities =
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List <int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary <int, int> VolunteerOpportunities = new Dictionary <int, int>();


                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                            into g
                            let count = g.Count()
                                        orderby count descending
                                        select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List <ConnectionOpportunity> connectionOpportunityList    = new List <ConnectionOpportunity>();

                    foreach (KeyValuePair <int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List <int> {
                            entry.Value
                        }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }
                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }



                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);


                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible   = true;
                    NoDISCResults.Visible = false;
                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary <string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }


                // Build the UI

                lbPersonName.Text = SelectedPerson.FullName;

                lbGift1Title.Text    = shapeGift1Object.Value;
                lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

                lbGift2Title.Text    = shapeGift2Object.Value;
                lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

                lbGift3Title.Text    = shapeGift3Object.Value;
                lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

                lbGift4Title.Text    = shapeGift4Object.Value;
                lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

                lbAbility1Title.Text    = ability1Object.Value;
                lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

                lbAbility2Title.Text    = ability2Object.Value;
                lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

                lbPeople.Text = people;
                lbPlaces.Text = places;
                lbEvents.Text = events;

                lbHeartCategories.Text = heartCategoriesString;
                lbHeartCauses.Text     = heartCauses;
                lbHeartPassion.Text    = heartPassion;

                if (spiritualGift1AttributeValue.ModifiedDateTime != null)
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
                }
                else
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
                }


                // Show create account panel if this person doesn't have an account
                if (SelectedPerson.Users.Count == 0)
                {
                    pnlAccount.Visible = true;
                }
            }
        }
Example #18
0
        /// <summary>Process all transactions (payments) from Service Reef.</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();
            FinancialBatchService       financialBatchService       = new FinancialBatchService(dbContext);
            PersonService               personService               = new PersonService(dbContext);
            PersonAliasService          personAliasService          = new PersonAliasService(dbContext);
            FinancialAccountService     financialAccountService     = new FinancialAccountService(dbContext);
            FinancialAccountService     accountService              = new FinancialAccountService(dbContext);
            FinancialTransactionService financialTransactionService = new FinancialTransactionService(dbContext);
            FinancialGatewayService     financialGatewayService     = new FinancialGatewayService(dbContext);
            DefinedValueService         definedValueService         = new DefinedValueService(dbContext);
            DefinedTypeService          definedTypeService          = new DefinedTypeService(dbContext);
            TransactionService          transactionService          = new TransactionService(new PayPalReporting.Data.PayPalReportingContext());

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

            String warnings = string.Empty;

            FinancialBatch batch       = null;
            Double         totalAmount = 0;
            var            total       = 1;
            var            processed   = 0;

            try
            {
                DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||");

                String            SRApiKey          = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey"));
                String            SRApiSecret       = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret"));
                String            SRApiUrl          = dataMap.GetString("ServiceReefAPIURL");
                DefinedValueCache transactionSource = DefinedValueCache.Get(dataMap.GetString("TransactionSource").AsGuid(), dbContext);
                DefinedValueCache connectionStatus  = DefinedValueCache.Get(dataMap.GetString("ConnectionStatus").AsGuid(), dbContext);
                DefinedValueCache contribution      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION);

                // Setup some lookups
                DefinedTypeCache        creditCards = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid(), dbContext);
                DefinedTypeCache        tenderType  = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid(), dbContext);
                FinancialAccount        specialFund = accountService.Get(dataMap.GetString("Account").AsGuid());
                FinancialGateway        gateway     = financialGatewayService.Get(dataMap.GetString("FinancialGateway").AsGuid());
                List <FinancialAccount> trips       = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();

                // Get the trips
                DefinedValueCache serviceReefAccountType = DefinedValueCache.Get(dataMap.Get("ServiceReefAccountType").ToString().AsGuid());

                // Setup the ServiceReef API Client
                var client = new RestClient(SRApiUrl);
                client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret);

                // Get all payments from ServiceReef
                var request = new RestRequest("v1/payments", Method.GET);
                request.AddParameter("pageSize", 100);
                if (dateRange.Start.HasValue)
                {
                    request.AddParameter("startDate", dateRange.Start.Value.ToString("o"));
                }
                if (dateRange.End.HasValue)
                {
                    request.AddParameter("endDate", dateRange.End.Value.ToString("o"));
                }
                request.AddParameter("page", 1);

                while (total > processed)
                {
                    var response = client.Execute <Contracts.Payments>(request);
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                    }
                    if (response.Data != null && response.Data.PageInfo != null)
                    {
                        total = response.Data.PageInfo.TotalRecords;
                        foreach (Contracts.Payments.Result result in response.Data.Results)
                        {
                            // Process the transaction
                            if (result.PaymentProcessorTransactionId != null)
                            {
                                if (result.FirstName == null || result.LastName == null)
                                {
                                    warnings += "Missing Firstname/Lastname for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                    processed++;
                                    continue;
                                }

                                FinancialTransaction tran = financialTransactionService.Queryable().Where(tx => tx.TransactionCode == result.PaymentProcessorTransactionId).FirstOrDefault();

                                // We haven't processed this before so get busy!
                                if (tran == null)
                                {
                                    var glCode = result.EventCode;

                                    glCode = glCode.IsNotNullOrWhiteSpace() ? glCode : "[No GL Code]";

                                    if (glCode.Length > 50)
                                    {
                                        glCode = glCode.Substring(0, 50);
                                    }

                                    FinancialAccount trip = null;
                                    // Make sure we have a sub-account to go with this transaction
                                    if (result.EventId > 0)
                                    {
                                        trip = trips.Where(t => t.GlCode == glCode && t.Url == result.EventUrl).FirstOrDefault();
                                    }
                                    if (trip == null)
                                    {
                                        if (result.EventCode == null)
                                        {
                                            warnings += "Event Code is missing on the Service Reef Trip for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                            processed++;
                                            continue;
                                        }

                                        // Create the trip subaccount
                                        FinancialAccount tripFA = new FinancialAccount();
                                        tripFA.Name = result.EventName;
                                        // Name is limited to 50
                                        if (tripFA.Name.Length > 50)
                                        {
                                            tripFA.Name = tripFA.Name.Substring(0, 50);
                                        }
                                        tripFA.Description = "Service Reef Event.  Name: " + result.EventName + " ID: " + result.EventId;

                                        tripFA.GlCode     = glCode;
                                        tripFA.Url        = result.EventUrl;
                                        tripFA.PublicName = result.EventName;
                                        // Public Name is limited to 50
                                        if (tripFA.PublicName.Length > 50)
                                        {
                                            tripFA.PublicName = tripFA.PublicName.Substring(0, 50);
                                        }
                                        tripFA.IsTaxDeductible    = true;
                                        tripFA.IsPublic           = false;
                                        tripFA.ParentAccountId    = specialFund.Id;
                                        tripFA.Order              = specialFund.Order + 1;
                                        tripFA.AccountTypeValueId = serviceReefAccountType.Id;
                                        // Figure out what order it should be;
                                        foreach (FinancialAccount tmpTrip in trips)
                                        {
                                            if (tmpTrip.Name.CompareTo(tripFA.Name) < 0)
                                            {
                                                tripFA.Order++;
                                            }
                                        }

                                        financialAccountService.Add(tripFA);

                                        // Now save the trip
                                        dbContext.SaveChanges();
                                        // Increment all the rest of the Orders
                                        financialAccountService.Queryable().Where(fa => fa.Order >= tripFA.Order && fa.Id != tripFA.Id).ToList().ForEach(c => c.Order++);
                                        dbContext.SaveChanges();
                                        trips = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();
                                        trip  = tripFA;
                                    }

                                    tran = new FinancialTransaction();
                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    if (result.Type == "CreditCard")
                                    {
                                        tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }
                                    else
                                    {
                                        tran.TransactionTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }

                                    Person person = null;
                                    // Find the person this transaction belongs to
                                    // 1. First start by determining whether this was a person
                                    //    paying their application fee or contributing to themselves
                                    //    because then we can just use their member info
                                    if (result.UserId > 0 &&
                                        result.DonatedToUserId == result.UserId &&
                                        result.DonatedToFirstName == result.FirstName &&
                                        result.DonatedToLastName == result.LastName)
                                    {
                                        var memberRequest = new RestRequest("v1/members/{userId}", Method.GET);
                                        memberRequest.AddUrlSegment("userId", result.UserId.ToString());
                                        var memberResult = client.Execute <Contracts.Member>(memberRequest);
                                        if (memberResult.Data != null && memberResult.Data.ArenaId > 0)
                                        {
                                            try
                                            {
                                                Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault();
                                                if (personMatch == null)
                                                {
                                                    throw new Exception("Person not found: " + memberResult.Data.ArenaId);
                                                }
                                                person = personMatch;
                                            }
                                            catch (Exception e)
                                            {
                                                warnings += "Loading the person failed transaction id " + result.TransactionId + " for " + result.FirstName + " " + result.LastName + " with the following error: " + e.Message + Environment.NewLine;
                                                processed++;
                                                continue;
                                            }
                                        }
                                    }
                                    // 2. If we didn't get a person match via their Alias Id
                                    //    then just use the standard person match logic
                                    if (person == null)
                                    {
                                        String street1    = null;
                                        String postalCode = null;
                                        if (result.Address != null)
                                        {
                                            street1    = result.Address.Address1;
                                            postalCode = result.Address.Zip;
                                        }
                                        List <Person> matches = personService.GetByMatch(result.FirstName.Trim(), result.LastName.Trim(), null, result.Email, null, street1, postalCode).ToList();

                                        if (matches.Count > 1)
                                        {
                                            // Find the oldest member record in the list
                                            person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();
                                            if (person == null)
                                            {
                                                // Find the oldest attendee record in the list
                                                person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                                if (person == null)
                                                {
                                                    person = matches.OrderBy(p => p.Id).First();
                                                }
                                            }
                                        }
                                        else if (matches.Count == 1)
                                        {
                                            person = matches.First();
                                        }
                                        else
                                        {
                                            // Create the person
                                            person           = new Person();
                                            person.FirstName = result.FirstName.Trim();
                                            person.LastName  = result.LastName.Trim();
                                            if (result.Email.IsValidEmail())
                                            {
                                                person.Email = result.Email.Trim();
                                            }
                                            person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                            person.ConnectionStatusValueId = connectionStatus.Id;
                                            person.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                            Group         family   = PersonService.SaveNewPerson(person, dbContext);
                                            GroupLocation location = new GroupLocation();
                                            location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                            location.Location = new Location()
                                            {
                                                Street1    = result.Address.Address1,
                                                Street2    = result.Address.Address2,
                                                City       = result.Address.City,
                                                State      = result.Address.State,
                                                PostalCode = result.Address.Zip,
                                                Country    = result.Address.Country
                                            };
                                            family.CampusId = CampusCache.All().FirstOrDefault().Id;
                                            family.GroupLocations.Add(location);
                                            dbContext.SaveChanges();
                                        }
                                    }

                                    // Get details about the transaction from our PayPal report table
                                    Transaction tx = transactionService.Get(result.PaymentProcessorTransactionId);
                                    if (tx != null)
                                    {
                                        if (tx.TenderType.Contains("ACH"))
                                        {
                                            result.Type   = "ACH";
                                            result.Method = null;
                                        }
                                        else
                                        {
                                            result.Type   = "Credit Card";
                                            result.Method = tx.TenderType;
                                        }
                                    }
                                    else
                                    {
                                        // Defaults
                                        result.Type   = "Credit Card";
                                        result.Method = "Visa";

                                        warnings += "Unable to find transaction in _org_secc_PaypalReporting_Transaction table: " + result.TransactionId + Environment.NewLine;
                                    }

                                    // If we don't have a batch, create one
                                    if (batch == null)
                                    {
                                        batch = new FinancialBatch();
                                        batch.BatchStartDateTime = result.Date;
                                        batch.BatchEndDateTime   = DateTime.Now;
                                        batch.Name   = "Service Reef Payments";
                                        batch.Status = BatchStatus.Open;
                                        financialBatchService.Add(batch);
                                        dbContext.SaveChanges();
                                    }

                                    // Complete the FinancialTransaction
                                    tran.AuthorizedPersonAliasId = person.PrimaryAliasId;
                                    tran.BatchId             = batch.Id;
                                    tran.Summary             = "F" + specialFund.Id + ":$" + result.Amount.ToString();
                                    tran.TransactionDateTime = result.Date;
                                    tran.FinancialGatewayId  = gateway.Id;

                                    FinancialTransactionDetail financialTransactionDetail = new FinancialTransactionDetail();
                                    financialTransactionDetail.AccountId = trip.Id;
                                    financialTransactionDetail.Amount    = result.Amount.ToString().AsDecimal();
                                    tran.TransactionDetails.Add(financialTransactionDetail);
                                    tran.TransactionTypeValueId = contribution.Id;

                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(type => type.Value.ToLower() == result.Type.ToLower()).FirstOrDefault().Id;
                                    if (result.Method != null)
                                    {
                                        tran.FinancialPaymentDetail.CreditCardTypeValueId = creditCards.DefinedValues.Where(card => card.Value.ToLower() == result.Method.ToLower()).FirstOrDefault().Id;
                                    }
                                    tran.TransactionCode   = result.PaymentProcessorTransactionId;
                                    tran.SourceTypeValueId = transactionSource.Id;

                                    financialTransactionService.Add(tran);
                                    dbContext.SaveChanges();

                                    totalAmount += result.Amount;
                                }
                            }
                            processed++;
                        }
                    }
                    else
                    {
                        total = 0;
                    }
                    // Update the page number for the next request
                    var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault();
                    pageParam.Value = ( int )pageParam.Value + 1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ServiceReef Job Failed", ex);
            }
            finally
            {
                if (batch != null && totalAmount > 0)
                {
                    batch.ControlAmount = ( Decimal )totalAmount;
                }
                dbContext.SaveChanges();
            }
            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " transactions.";
        }
Example #19
0
        private IQueryable <CommunionData> getQuery <T>()
        {
            using (var rockContext = new RockContext())
            {
                var workflowService       = new WorkflowService(rockContext);
                var attributeService      = new AttributeService(rockContext);
                var attributeValueService = new AttributeValueService(rockContext);
                var personAliasService    = new PersonAliasService(rockContext);
                var personService         = new PersonService(rockContext);
                var definedValueService   = new DefinedValueService(rockContext);

                Guid hospitalWorkflow             = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid();
                Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid();
                Guid homeBoundPersonWorkflow      = GetAttributeValue("HomeboundPersonWorkflow").AsGuid();
                Guid hospitalList    = GetAttributeValue("HospitalList").AsGuid();
                Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid();

                var workflowTypesIdAsStrings = new WorkflowTypeService(rockContext).Queryable()
                                               .Where(wt =>
                                                      wt.Guid == hospitalWorkflow ||
                                                      wt.Guid == nursingHomeAdmissionWorkflow ||
                                                      wt.Guid == homeBoundPersonWorkflow
                                                      )
                                               .ToList()
                                               .Select(wf => wf.Id.ToString())
                                               .ToList();

                var attributeIds = attributeService.Queryable()
                                   .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && workflowTypesIdAsStrings.Contains(a.EntityTypeQualifierValue))
                                   .Select(a => a.Id).ToList();

                var wfTmpqry = workflowService.Queryable().AsNoTracking()
                               .Where(w => (
                                          w.WorkflowType.Guid == hospitalWorkflow ||
                                          w.WorkflowType.Guid == nursingHomeAdmissionWorkflow ||
                                          w.WorkflowType.Guid == homeBoundPersonWorkflow
                                          ) && (w.Status == "Active"));

                var tqry = wfTmpqry.Join(attributeValueService.Queryable(),
                                         obj => obj.Id,
                                         av => av.EntityId.Value,
                                         (obj, av) => new { Workflow = obj, AttributeValue = av })
                           .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(obj => obj.Workflow)
                           .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });
                var qry = tqry.ToList();


                List <DefinedValueCache> facilities = DefinedTypeCache.All().Where(dv => dv.Guid == hospitalList || dv.Guid == nursingHomeList).SelectMany(dv => dv.DefinedValues).ToList();

                var newQry = qry.Select(w => new CommunionData
                {
                    Campus = new Func <Campus>(() =>
                    {
                        Campus campus = null;
                        AttributeValue personAliasAV = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "PersonToVisit" || av.AttributeKey == "HomeboundPerson").FirstOrDefault();
                        if (personAliasAV != null)
                        {
                            PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid());
                            if (pa != null)
                            {
                                campus = pa.Person.GetCampus();
                            }
                        }
                        if (campus == null)
                        {
                            campus = new Campus()
                            {
                                Name = "Unknown"
                            };
                        }
                        return(campus);
                    })(),
                    Person      = GetPerson(personAliasService, w.AttributeValues),
                    Age         = GetPerson(personAliasService, w.AttributeValues).Age,
                    Description = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "VisitationRequestDescription" || av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Location    = new Func <string>(() =>
                    {
                        return(w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "NursingHome" || av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).DefaultIfEmpty("Home").FirstOrDefault());
                    })(),
                    Address        = GetLocation(personService, w.AttributeValues, facilities).Street1 + " " + GetLocation(personService, w.AttributeValues, facilities).Street2,
                    City           = GetLocation(personService, w.AttributeValues, facilities).City,
                    State          = GetLocation(personService, w.AttributeValues, facilities).State,
                    PostalCode     = GetLocation(personService, w.AttributeValues, facilities).PostalCode,
                    FacilityNumber = GetFacilityNumber(personService, w.AttributeValues, facilities),
                    Room           = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                    AdmitDate      = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "AdmitDate" || av.AttributeKey == "StartDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Status         = w.Workflow.Status,
                    Communion      = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Communion").FirstOrDefault().ValueFormatted,
                    Route          = (int?)w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "CommunionRoute").Select(av => av.ValueAsNumeric).FirstOrDefault()
                })
                             .Where(o => o.Communion.AsBoolean() && !o.Person.IsDeceased)
                             .OrderBy(a => a.PostalCode)
                             .ThenBy(a => a.Address)
                             .ToList()
                             .AsQueryable();


                List <COMMUNION_STATES> states = cblState.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => ( COMMUNION_STATES )int.Parse(i.Value)).ToList();

                if (states.Count > 0)
                {
                    newQry = newQry.Where(o => (states.Contains(COMMUNION_STATES.KY) && o.State == "KY") ||
                                          (states.Contains(COMMUNION_STATES.IN) && o.State == "IN") ||
                                          ((states.Contains(COMMUNION_STATES.Other) && o.State != "IN" && o.State != "KY")));
                }
                List <int> campuses = cpCampus.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => int.Parse(i.Value)).ToList();

                if (campuses.Count > 0)
                {
                    newQry = newQry.Where(o => campuses.Contains(o.Campus.Id));
                }

                if (nreRoute.LowerValue.HasValue)
                {
                    newQry = newQry.Where(o => o.Route >= nreRoute.LowerValue.Value);
                }

                if (nreRoute.UpperValue.HasValue)
                {
                    newQry = newQry.Where(o => o.Route <= nreRoute.UpperValue.Value);
                }

                //AddGridColumns( newQry.FirstOrDefault() );

                SortProperty sortProperty = gReport.SortProperty;
                if (sortProperty != null)
                {
                    newQry = newQry.Sort(sortProperty);
                }

                return(newQry);
            }
        }
Example #20
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (new UnitOfWorkScope())
            {
                GroupType        groupType;
                GroupTypeService groupTypeService = new GroupTypeService();
                AttributeService attributeService = new AttributeService();

                int groupTypeId = int.Parse(hfGroupTypeId.Value);

                if (groupTypeId == 0)
                {
                    groupType = new GroupType();
                    groupTypeService.Add(groupType, CurrentPersonId);
                }
                else
                {
                    groupType = groupTypeService.Get(groupTypeId);
                }

                groupType.Name = tbName.Text;

                groupType.Description            = tbDescription.Text;
                groupType.GroupTerm              = tbGroupTerm.Text;
                groupType.GroupMemberTerm        = tbGroupMemberTerm.Text;
                groupType.DefaultGroupRoleId     = ddlDefaultGroupRole.SelectedValueAsInt();
                groupType.ShowInGroupList        = cbShowInGroupList.Checked;
                groupType.ShowInNavigation       = cbShowInNavigation.Checked;
                groupType.IconCssClass           = tbIconCssClass.Text;
                groupType.IconSmallFileId        = imgIconSmall.ImageId;
                groupType.IconLargeFileId        = imgIconLarge.ImageId;
                groupType.TakesAttendance        = cbTakesAttendance.Checked;
                groupType.AttendanceRule         = ddlAttendanceRule.SelectedValueAsEnum <AttendanceRule>();
                groupType.AttendancePrintTo      = ddlAttendancePrintTo.SelectedValueAsEnum <PrintTo>();
                groupType.LocationSelectionMode  = ddlLocationSelectionMode.SelectedValueAsEnum <LocationPickerMode>();
                groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked;
                groupType.InheritedGroupTypeId   = gtpInheritedGroupType.SelectedGroupTypeId;

                groupType.ChildGroupTypes = new List <GroupType>();
                groupType.ChildGroupTypes.Clear();
                foreach (var item in ChildGroupTypesDictionary)
                {
                    var childGroupType = groupTypeService.Get(item.Key);
                    if (childGroupType != null)
                    {
                        groupType.ChildGroupTypes.Add(childGroupType);
                    }
                }

                DefinedValueService definedValueService = new DefinedValueService();

                groupType.LocationTypes = new List <GroupTypeLocationType>();
                groupType.LocationTypes.Clear();
                foreach (var item in LocationTypesDictionary)
                {
                    var locationType = definedValueService.Get(item.Key);
                    if (locationType != null)
                    {
                        groupType.LocationTypes.Add(new GroupTypeLocationType {
                            LocationTypeValueId = locationType.Id
                        });
                    }
                }

                if (!groupType.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                RockTransactionScope.WrapTransaction(() =>
                {
                    groupTypeService.Save(groupType, CurrentPersonId);

                    // get it back to make sure we have a good Id for it for the Attributes
                    groupType = groupTypeService.Get(groupType.Guid);

                    /* Take care of Group Type Attributes */

                    // delete GroupTypeAttributes that are no longer configured in the UI
                    var groupTypeAttributesQry = attributeService.Get(new GroupType().TypeId, "Id", groupType.Id.ToString());
                    var selectedAttributes     = GroupTypeAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupTypeAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    string qualifierValue = groupType.Id.ToString();

                    // add/update the GroupTypeAttributes that are assigned in the UI
                    foreach (var attributeState in GroupTypeAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupTypeAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(GroupType)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }

                    /* Take care of Group Attributes */

                    // delete GroupAttributes that are no longer configured in the UI
                    var groupAttributesQry = attributeService.Get(new Group().TypeId, "GroupTypeId", groupType.Id.ToString());
                    selectedAttributes     = GroupAttributesState.Select(a => a.Guid);
                    foreach (var attr in groupAttributesQry.Where(a => !selectedAttributes.Contains(a.Guid)))
                    {
                        Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                        attributeService.Delete(attr, CurrentPersonId);
                        attributeService.Save(attr, CurrentPersonId);
                    }

                    // add/update the GroupAttributes that are assigned in the UI
                    foreach (var attributeState in GroupAttributesState
                             .Where(a =>
                                    a.EntityTypeQualifierValue == null ||
                                    a.EntityTypeQualifierValue.Trim() == string.Empty ||
                                    a.EntityTypeQualifierValue.Equals(qualifierValue)))
                    {
                        // remove old qualifiers in case they changed
                        var qualifierService = new AttributeQualifierService();
                        foreach (var oldQualifier in qualifierService.GetByAttributeId(attributeState.Id).ToList())
                        {
                            qualifierService.Delete(oldQualifier, CurrentPersonId);
                            qualifierService.Save(oldQualifier, CurrentPersonId);
                        }

                        Attribute attribute = groupAttributesQry.FirstOrDefault(a => a.Guid.Equals(attributeState.Guid));
                        if (attribute == null)
                        {
                            attribute = attributeState.Clone() as Rock.Model.Attribute;
                            attributeService.Add(attribute, CurrentPersonId);
                        }
                        else
                        {
                            attributeState.Id = attribute.Id;
                            attribute.FromDictionary(attributeState.ToDictionary());

                            foreach (var qualifier in attributeState.AttributeQualifiers)
                            {
                                attribute.AttributeQualifiers.Add(qualifier.Clone() as AttributeQualifier);
                            }
                        }

                        attribute.EntityTypeQualifierColumn = "GroupTypeId";
                        attribute.EntityTypeQualifierValue  = qualifierValue;
                        attribute.EntityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(Group)).Id;
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Save(attribute, CurrentPersonId);
                    }
                });
            }
            NavigateToParentPage();
        }
        /// <summary>
        /// Handles the Click event of the btnDefault control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDefault_Click(object sender, EventArgs e)
        {
            var         bioBlock = BlockCache.Get(Rock.SystemGuid.Block.BIO.AsGuid());
            List <Guid> workflowActionGuidList = bioBlock.GetAttributeValues("WorkflowActions").AsGuidList();

            if (workflowActionGuidList == null || workflowActionGuidList.Count == 0)
            {
                // Add Checkr to Bio Workflow Actions
                bioBlock.SetAttributeValue("WorkflowActions", Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY);
                ///BackgroundCheckContainer.Instance.Components
            }
            else
            {
                //var workflowActionValues = workflowActionValue.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                Guid guid = Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid();
                if (!workflowActionGuidList.Any(w => w == guid))
                {
                    // Add Checkr to Bio Workflow Actions
                    workflowActionGuidList.Add(guid);
                }

                // Remove PMM from Bio Workflow Actions
                guid = CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid();
                workflowActionGuidList.RemoveAll(w => w == guid);
                bioBlock.SetAttributeValue("WorkflowActions", workflowActionGuidList.AsDelimited(","));
                string pmmTypeName  = (typeof(Rock.Security.BackgroundCheck.ProtectMyMinistry)).FullName;
                var    pmmComponent = BackgroundCheckContainer.Instance.Components.Values.FirstOrDefault(c => c.Value.TypeName == pmmTypeName);
                // pmmComponent.Value.GetAttributeValue( "Active" );
                pmmComponent.Value.SetAttributeValue("Active", "True");
                pmmComponent.Value.SaveAttributeValue("Active");
            }

            bioBlock.SaveAttributeValue("WorkflowActions");

            using (var rockContext = new RockContext())
            {
                WorkflowTypeService workflowTypeService = new WorkflowTypeService(rockContext);
                // Rename PMM Workflow
                var pmmWorkflowAction = workflowTypeService.Get(Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid());
                pmmWorkflowAction.Name = "Background Check";

                var checkrWorkflowAction = workflowTypeService.Get(CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid());
                // Rename Checkr Workflow
                checkrWorkflowAction.Name = CheckrConstants.CHECKR_WORKFLOW_TYPE_NAME;

                rockContext.SaveChanges();

                // Enable PMM packages and disable Checkr packages
                DefinedValueService definedValueService = new DefinedValueService(rockContext);
                var packages = definedValueService
                               .GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.BACKGROUND_CHECK_TYPES.AsGuid())
                               .ToList();

                foreach (var package in packages)
                {
                    package.IsActive = package.ForeignId == 1;
                }

                rockContext.SaveChanges();
            }

            ShowDetail();
        }
        /// <summary>
        /// Shows the settings.
        /// </summary>
        protected override void ShowSettings()
        {
            pnlSettings.Visible = true;
            ddlContentChannel.Items.Clear();
            ddlContentChannel.Items.Add(new ListItem());
            foreach (var contentChannel in ContentChannelCache.All().OrderBy(a => a.Name))
            {
                ddlContentChannel.Items.Add(new ListItem(contentChannel.Name, contentChannel.Guid.ToString()));
            }

            ddlLaunchWorkflowCondition.Items.Clear();
            foreach (LaunchWorkflowCondition launchWorkflowCondition in Enum.GetValues(typeof(LaunchWorkflowCondition)))
            {
                ddlLaunchWorkflowCondition.Items.Add(new ListItem(launchWorkflowCondition.ConvertToString(true), launchWorkflowCondition.ConvertToInt().ToString()));
            }

            var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull();

            ddlContentChannel.SetValue(channelGuid);
            UpdateSocialMediaDropdowns(channelGuid);

            cblStatus.BindToEnum <ContentChannelItemStatus>();
            foreach (string status in GetAttributeValue("Status").SplitDelimitedValues())
            {
                var li = cblStatus.Items.FindByValue(status);
                if (li != null)
                {
                    li.Selected = true;
                }
            }

            var ppFieldType = new PageReferenceFieldType();

            ppFieldType.SetEditValue(ppDetailPage, null, GetAttributeValue("DetailPage"));
            tbContentChannelQueryParameter.Text = this.GetAttributeValue("ContentChannelQueryParameter");
            ceLavaTemplate.Text        = this.GetAttributeValue("LavaTemplate");
            nbOutputCacheDuration.Text = this.GetAttributeValue("OutputCacheDuration");
            nbItemCacheDuration.Text   = this.GetAttributeValue("ItemCacheDuration");

            DefinedValueService definedValueService = new DefinedValueService(new RockContext());

            cblCacheTags.DataSource = definedValueService.GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.CACHE_TAGS.AsGuid()).Select(v => v.Value).ToList();
            cblCacheTags.DataBind();
            string[] selectedCacheTags = this.GetAttributeValue("CacheTags").SplitDelimitedValues();
            foreach (ListItem cacheTag in cblCacheTags.Items)
            {
                cacheTag.Selected = selectedCacheTags.Contains(cacheTag.Value);
            }

            cbSetPageTitle.Checked = this.GetAttributeValue("SetPageTitle").AsBoolean();
            cbMergeContent.Checked = GetAttributeValue("MergeContent").AsBoolean();

            if (this.GetAttributeValue("LogInteractions").AsBoolean())
            {
                cbLogInteractions.Checked = true;
                cbWriteInteractionOnlyIfIndividualLoggedIn.Visible = true;
                cbWriteInteractionOnlyIfIndividualLoggedIn.Checked = this.GetAttributeValue("WriteInteractionOnlyIfIndividualLoggedIn").AsBoolean();
            }
            else
            {
                cbLogInteractions.Checked = false;
                cbWriteInteractionOnlyIfIndividualLoggedIn.Visible = false;
                cbWriteInteractionOnlyIfIndividualLoggedIn.Checked = false;
            }

            var rockContext = new RockContext();

            // Workflow
            Guid?workflowTypeGuid = this.GetAttributeValue("WorkflowType").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                wtpWorkflowType.SetValue(new WorkflowTypeService(rockContext).GetNoTracking(workflowTypeGuid.Value));
            }
            else
            {
                wtpWorkflowType.SetValue(null);
            }

            ShowHideControls();

            cbLaunchWorkflowOnlyIfIndividualLoggedIn.Checked = this.GetAttributeValue("LaunchWorkflowOnlyIfIndividualLoggedIn").AsBoolean();
            ddlLaunchWorkflowCondition.SetValue(this.GetAttributeValue("LaunchWorkflowCondition"));

            // Social Media
            ddlMetaDescriptionAttribute.SetValue(this.GetAttributeValue("MetaDescriptionAttribute"));
            ddlOpenGraphType.SetValue(this.GetAttributeValue("OpenGraphType"));
            ddlOpenGraphTitleAttribute.SetValue(this.GetAttributeValue("OpenGraphTitleAttribute"));
            ddlOpenGraphDescriptionAttribute.SetValue(this.GetAttributeValue("OpenGraphDescriptionAttribute"));
            ddlOpenGraphImageAttribute.SetValue(this.GetAttributeValue("OpenGraphImageAttribute"));

            ddlTwitterTitleAttribute.SetValue(this.GetAttributeValue("TwitterTitleAttribute"));
            ddlTwitterDescriptionAttribute.SetValue(this.GetAttributeValue("TwitterDescriptionAttribute"));
            ddlTwitterImageAttribute.SetValue(this.GetAttributeValue("TwitterImageAttribute"));
            ddlTwitterCard.SetValue(this.GetAttributeValue("TwitterCard"));

            mdSettings.Show();
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            Rock.Data.RockTransactionScope.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                var business      = new Person();
                if (int.Parse(hfBusinessId.Value) != 0)
                {
                    business = personService.Get(int.Parse(hfBusinessId.Value));
                }

                // int? orphanedPhotoId = null;
                // if ( business.PhotoId != imgPhoto.BinaryFileId )
                // {
                // orphanedPhotoId = business.PhotoId;
                // business.PhotoId = imgPhoto.BinaryFileId;

                // if ( orphanedPhotoId.HasValue )
                // {
                // if ( business.PhotoId.HasValue )
                // {
                // changes.Add( "Modified the photo." );
                // }
                // else
                // {
                // changes.Add( "Deleted the photo." );
                // }
                // }
                // else if ( business.PhotoId.HasValue )
                // {
                // changes.Add( "Added a photo." );
                // }
                // }

                // Business Name
                History.EvaluateChange(changes, "First Name", business.FirstName, tbBusinessName.Text);
                business.FirstName = tbBusinessName.Text;

                // Phone Number
                var phoneNumberTypeIds = new List <int>();
                var homePhoneTypeId    = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME)).Id;

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    var phoneNumber       = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == homePhoneTypeId);
                    string oldPhoneNumber = string.Empty;
                    if (phoneNumber == null)
                    {
                        phoneNumber = new PhoneNumber {
                            NumberTypeValueId = homePhoneTypeId
                        };
                        business.PhoneNumbers.Add(phoneNumber);
                    }
                    else
                    {
                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                    }

                    phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted         = cbUnlisted.Checked;
                    phoneNumberTypeIds.Add(homePhoneTypeId);

                    History.EvaluateChange(
                        changes,
                        string.Format("{0} Phone", DefinedValueCache.GetName(homePhoneTypeId)),
                        oldPhoneNumber,
                        phoneNumber.NumberFormattedWithCountryCode);
                }

                // Remove any blank numbers
                var phoneNumberService = new PhoneNumberService(rockContext);
                foreach (var phoneNumber in business.PhoneNumbers
                         .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
                         .ToList())
                {
                    History.EvaluateChange(
                        changes,
                        string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                        phoneNumber.NumberFormatted,
                        string.Empty);

                    business.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                // Record Status
                int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int?newRecordStatusReasonId = null;
                if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text);
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference);
                business.EmailPreference = newEmailPreference;

                if (business.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes);
                        }

                        // if ( orphanedPhotoId.HasValue )
                        // {
                        // BinaryFileService binaryFileService = new BinaryFileService( personService.RockContext );
                        // var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        // if ( binaryFile != null )
                        // {
                        // // marked the old images as IsTemporary so they will get cleaned up later
                        // binaryFile.IsTemporary = true;
                        // binaryFileService.Save( binaryFile, CurrentPersonAlias );
                        // }
                        // }

                        // Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                    }
                }

                // Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                var groupService    = new GroupService(rockContext);
                var businessGroup   = new Group();
                if (business.GivingGroupId != null)
                {
                    businessGroup = groupService.Get((int)business.GivingGroupId);
                }

                businessGroup.GroupTypeId    = familyGroupType.Id;
                businessGroup.Name           = tbBusinessName.Text + " Business";
                businessGroup.CampusId       = ddlCampus.SelectedValueAsInt();
                var knownRelationshipGroup   = new Group();
                var impliedRelationshipGroup = new Group();
                if (business.GivingGroupId == null)
                {
                    groupService.Add(businessGroup);

                    // If there isn't a Giving Group then there aren't any other groups.
                    // We also need to add the Known Relationship and Implied Relationship groups for this business.
                    var knownRelationshipGroupTypeId   = new GroupTypeService(rockContext).Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS)).Id;
                    knownRelationshipGroup.GroupTypeId = knownRelationshipGroupTypeId;
                    knownRelationshipGroup.Name        = "Known Relationship";
                    groupService.Add(knownRelationshipGroup);

                    var impliedRelationshipGroupTypeId   = new GroupTypeService(rockContext).Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS)).Id;
                    impliedRelationshipGroup.GroupTypeId = impliedRelationshipGroupTypeId;
                    impliedRelationshipGroup.Name        = "Implied Relationship";
                    groupService.Add(impliedRelationshipGroup);
                }

                rockContext.SaveChanges();

                // Giving Group
                int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId();
                if (business.GivingGroupId != newGivingGroupId)
                {
                    string oldGivingGroupName = business.GivingGroup != null ? business.GivingGroup.Name : string.Empty;
                    string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty;
                    History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName);
                }

                business.GivingGroup = businessGroup;

                // GroupMember
                var groupMemberService = new GroupMemberService(rockContext);
                int?adultRoleId        = new GroupTypeRoleService(rockContext).Queryable()
                                         .Where(r =>
                                                r.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)))
                                         .Select(r => r.Id)
                                         .FirstOrDefault();
                var groupMember = businessGroup.Members.Where(role => role.GroupRoleId == adultRoleId).FirstOrDefault();
                if (groupMember == null)
                {
                    groupMember = new GroupMember();
                    businessGroup.Members.Add(groupMember);

                    // If we're in here, then this is a new business.
                    // Add the known relationship and implied relationship GroupMember entries.
                    var knownRelationshipGroupMember         = new GroupMember();
                    knownRelationshipGroupMember.Person      = business;
                    knownRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()).Id;
                    knownRelationshipGroupMember.GroupId     = knownRelationshipGroup.Id;
                    knownRelationshipGroup.Members.Add(knownRelationshipGroupMember);

                    var impliedRelationshipGroupMember         = new GroupMember();
                    impliedRelationshipGroupMember.Person      = business;
                    impliedRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()).Id;
                    impliedRelationshipGroupMember.GroupId     = impliedRelationshipGroup.Id;
                    impliedRelationshipGroup.Members.Add(impliedRelationshipGroupMember);
                }

                groupMember.Person            = business;
                groupMember.GroupRoleId       = new GroupTypeRoleService(rockContext).Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                // GroupLocation & Location
                var groupLocationService = new GroupLocationService(rockContext);
                var groupLocation        = businessGroup.GroupLocations.FirstOrDefault();
                if (groupLocation == null)
                {
                    groupLocation = new GroupLocation();
                    businessGroup.GroupLocations.Add(groupLocation);
                }

                groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;

                var locationService = new LocationService(rockContext);
                var location        = groupLocation.Location;
                if (location == null)
                {
                    location = new Location();
                    groupLocation.Location = location;
                }

                location.Street1 = tbStreet1.Text.Trim();
                location.Street2 = tbStreet2.Text.Trim();
                location.City    = tbCity.Text.Trim();
                location.State   = ddlState.SelectedValue;
                location.Zip     = tbZipCode.Text.Trim();

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();

                // Set the Known Relationships between the Owner and the Business.
                if (ppOwner.PersonId != null)
                {
                    SetOwner(business);
                }
            });

            NavigateToParentPage();
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                Person business   = null;

                if (int.Parse(hfBusinessId.Value) != 0)
                {
                    business = personService.Get(int.Parse(hfBusinessId.Value));
                }

                if (business == null)
                {
                    business = new Person();
                    personService.Add(business);
                    tbBusinessName.Text = tbBusinessName.Text.FixCase();
                }

                // Business Name
                History.EvaluateChange(changes, "Last Name", business.LastName, tbBusinessName.Text);
                business.LastName = tbBusinessName.Text;

                // Phone Number
                var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);
                if (phoneNumber != null)
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    if (phoneNumber == null)
                    {
                        phoneNumber = new PhoneNumber {
                            NumberTypeValueId = businessPhoneTypeId
                        };
                        business.PhoneNumbers.Add(phoneNumber);
                    }
                    phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted         = cbUnlisted.Checked;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if (phoneNumber != null)
                    {
                        business.PhoneNumbers.Remove(phoneNumber);
                        new PhoneNumberService(rockContext).Delete(phoneNumber);
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", DefinedValueCache.GetName(businessPhoneTypeId)),
                    oldPhoneNumber,
                    newPhoneNumber);

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                // Record Status
                int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int?newRecordStatusReasonId = null;
                if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text);
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference);
                business.EmailPreference = newEmailPreference;

                if (business.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes);
                        }
                    }
                }

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                        History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty);
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);

                    if (workLocation != null)
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;

                    History.EvaluateChange(changes, "Address", oldValue, newLocation.ToString());
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

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

            queryParams.Add("businessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get person
            Person person        = null;
            int    personAliasId = 1;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Guid.Equals(personAliasGuid))
                                     .Select(a => a.Person)
                                     .FirstOrDefault();
                            if (person == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            if (person != null)
            {
                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                personAliasId = person.PrimaryAliasId ?? default(int);
            }



            //Get DateTime
            DateTime currentDateTime = DateTime.Now;



            //Get Stars Value
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            var  type     = GetAttributeValue(action, "Type");
            Guid typeGuid = type.AsGuid();

            var definedValue = definedValueService.GetByGuid(typeGuid);

            definedValue.LoadAttributes();
            var value      = definedValue.GetAttributeValue("StarValue");
            var starsValue = Convert.ToDecimal(value);


            //Save Stars
            SaveStars(currentDateTime, personAliasId, starsValue, definedValue.Value);



            return(true);
        }