예제 #1
0
        /// <summary>
        /// Handles the Click event of the bbtnCheckin 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 bbtnCheckin_Click(object sender, EventArgs e)
        {
            UpdateConfigurationFromBlockSettings();

            // checkin status might have changed after the Checkin Button was displayed, so make sure the kiosk is still active
            var checkinStatus = CheckinConfigurationHelper.GetCheckinStatus(CurrentCheckInState);

            if (checkinStatus != CheckinConfigurationHelper.CheckinStatus.Active)
            {
                RefreshCheckinStatusInformation(checkinStatus);
                return;
            }

            var latitude  = hfLatitude.Value.AsDoubleOrNull();
            var longitude = hfLongitude.Value.AsDoubleOrNull();

            if (latitude == null || longitude == null)
            {
                // shouldn't happen
                return;
            }

            var device = GetFirstMatchingKioskByGeoFencing(latitude.Value, longitude.Value);

            if (device == null)
            {
                // shouldn't happen
                return;
            }

            LocalDeviceConfig.CurrentKioskId = device.Id;
            SaveState();

            var checkInState = CurrentCheckInState;

            checkInState.CheckIn            = new CheckInStatus();
            checkInState.CheckIn.SearchType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_FAMILY_ID);

            var mobilePerson = this.GetMobilePerson();

            if (mobilePerson == null)
            {
                // shouldn't happen
                return;
            }

            var family = mobilePerson.GetFamily();

            var familyMembers = mobilePerson.GetFamilyMembers(true);

            var firstNames = familyMembers
                             .OrderBy(m => m.GroupRole.Order)
                             .ThenBy(m => m.Person.BirthYear)
                             .ThenBy(m => m.Person.BirthMonth)
                             .ThenBy(m => m.Person.BirthDay)
                             .ThenBy(m => m.Person.Gender)
                             .Select(m => m.Person.NickName)
                             .ToList();

            var checkInFamily = new CheckInFamily();

            checkInFamily.Group           = family.Clone(false);
            checkInFamily.Caption         = family.ToString();
            checkInFamily.FirstNames      = firstNames;
            checkInFamily.SubCaption      = firstNames.AsDelimited(", ");
            checkInFamily.Selected        = true;
            checkInState.CheckIn.Families = new List <CheckInFamily>();
            checkInState.CheckIn.Families.Add(checkInFamily);

            var rockContext = new RockContext();

            SaveState();

            var noMatchingPeopleMessage = this.GetAttributeValue(AttributeKey.NoPeopleMessage);

            Func <bool> doNotProceedCondition = () =>
            {
                var noMatchingFamilies =
                    (
                        CurrentCheckInState.CheckIn.Families.All(f => f.People.Count == 0) &&
                        CurrentCheckInState.CheckIn.Families.All(f => f.Action == CheckinAction.CheckIn)   // not sure this is needed
                    )
                    &&
                    (
                        !CurrentCheckInState.AllowCheckout ||
                        (
                            CurrentCheckInState.AllowCheckout &&
                            CurrentCheckInState.CheckIn.Families.All(f => f.CheckOutPeople.Count == 0)
                        )
                    );

                if (noMatchingFamilies)
                {
                    maWarning.Show(noMatchingPeopleMessage, Rock.Web.UI.Controls.ModalAlertType.None);
                    return(true);
                }
                else
                {
                    return(false);
                }
            };

            ProcessSelection(maWarning, doNotProceedCondition, noMatchingPeopleMessage);
        }
예제 #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>
        /// <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 RockEmailMessageRecipient(person, mergeFields));
                    emailMessage.AppRoot   = ResolveRockUrl("~/");
                    emailMessage.ThemeRoot = ResolveRockUrl("~~/");
                    emailMessage.Send();
                }
            }
            else
            {
                ShowInvalidResults(financialPledge.ValidationResults);
            }
        }
예제 #3
0
        public HttpResponseMessage Family(string param)
        {
            try
            {
                var session = HttpContext.Current.Session;

                var localDeviceConfigCookie = HttpContext.Current.Request.Cookies[CheckInCookieKey.LocalDeviceConfig].Value;
                var localDevice             = localDeviceConfigCookie.FromJsonOrNull <LocalDeviceConfiguration>();

                var  currentKioskId      = localDevice.CurrentKioskId.Value;
                Guid blockGuid           = ( Guid )session["BlockGuid"];
                var  currentCheckInState = new CheckInState(currentKioskId, localDevice.CurrentCheckinTypeId, localDevice.CurrentGroupTypeIds);
                currentCheckInState.CheckIn.UserEnteredSearch   = true;
                currentCheckInState.CheckIn.ConfirmSingleFamily = true;
                currentCheckInState.CheckIn.SearchType          = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                currentCheckInState.CheckIn.SearchValue         = param;

                var    rockContext      = new Rock.Data.RockContext();
                var    block            = BlockCache.Get(blockGuid);
                string workflowActivity = block.GetAttributeValue("WorkflowActivity");
                Guid?  workflowGuid     = block.GetAttributeValue("WorkflowType").AsGuidOrNull();

                List <string> errors;
                var           workflowService = new WorkflowService(rockContext);
                var           workflowType    = WorkflowTypeCache.Get(workflowGuid.Value);

                var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, currentCheckInState.Kiosk.Device.Name, rockContext);

                var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                if (activityType != null)
                {
                    WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                    if (workflowService.Process(CurrentWorkflow, currentCheckInState, out errors))
                    {
                        if (errors.Any())
                        {
                            var innerException = new Exception(string.Join(" -- ", errors));
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException));
                        }

                        // Keep workflow active for continued processing
                        CurrentWorkflow.CompletedDateTime = null;
                        SaveState(session, currentCheckInState);
                        List <CheckInFamily> families = currentCheckInState.CheckIn.Families;
                        families = families.OrderBy(f => f.Caption).ToList();
                        return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, families));
                    }
                    else
                    {
                        if (errors.Any())
                        {
                            var innerException = new Exception(string.Join(" -- ", errors));
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException));
                        }
                        else
                        {
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details."));
                        }
                    }
                }
                else
                {
                    return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity)));
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"));
            }
        }
예제 #4
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)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GroupType groupType = null;

            var rockContext = new RockContext();
            GroupTypeService          groupTypeService          = new GroupTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int?groupTypeId = hfGroupTypeId.ValueAsInt();

            if (groupTypeId.HasValue && groupTypeId.Value > 0)
            {
                groupType = groupTypeService.Get(groupTypeId.Value);
            }

            bool newGroupType = false;

            if (groupType == null)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType);

                var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                newGroupType = true;
            }

            if (groupType != null)
            {
                groupType.Name         = tbName.Text;
                groupType.Description  = tbDescription.Text;
                groupType.IconCssClass = tbIconCssClass.Text;
                groupType.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType);

                groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text);
                groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text);
                groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text);
                groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString());

                var searchType = DefinedValueCache.Get(ddlSearchType.SelectedValueAsInt() ?? 0);
                if (searchType != null)
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString());
                }
                else
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                }

                groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AllowCheckout", cbAllowCheckout.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text);
                groupType.SetAttributeValue("core_checkin_AutoSelectOptions", ddlAutoSelectOptions.SelectedValueAsInt());

                // Registration Settings

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS, cbRegistrationDisplayAlternateIdFieldForAdults.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN, cbRegistrationDisplayAlternateIdFieldForChildren.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON, cbRegistrationDisplaySmsEnabled.Checked.ToTrueFalse());
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED, cbRegistrationSmsEnabledByDefault.Checked.ToTrueFalse());

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS,
                    lbRegistrationRequiredAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS,
                    lbRegistrationOptionalAttributesForAdults.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN,
                    lbRegistrationRequiredAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN,
                    lbRegistrationOptionalAttributesForChildren.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES,
                    lbRegistrationRequiredAttributesForFamilies.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES,
                    lbRegistrationOptionalAttributesForFamilies.SelectedValues.AsDelimited(","));

                Guid?defaultPersonConnectionStatusValueGuid = null;
                var  defaultPersonConnectionStatusValueId   = dvpRegistrationDefaultPersonConnectionStatus.SelectedValue.AsIntegerOrNull();
                if (defaultPersonConnectionStatusValueId.HasValue)
                {
                    var defaultPersonConnectionStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueId.Value);
                    if (defaultPersonConnectionStatusValue != null)
                    {
                        defaultPersonConnectionStatusValueGuid = defaultPersonConnectionStatusValue.Guid;
                    }
                }

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS,
                    defaultPersonConnectionStatusValueGuid.ToString());

                var workflowTypeService = new WorkflowTypeService(rockContext);

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddFamilyWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(
                    Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES,
                    workflowTypeService.GetByIds(wftpRegistrationAddPersonWorkflowTypes.SelectedValuesAsInt().ToList()).Select(a => a.Guid).ToList().AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION, cbEnableCheckInAfterRegistration.Checked.ToTrueFalse());

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES, lbKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES, lbSameFamilyKnownRelationshipTypes.SelectedValues.AsDelimited(","));
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES, lbCanCheckInKnownRelationshipTypes.SelectedValues.AsDelimited(","));

                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE, ceStartTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE, ceFamilySelectTemplate.Text);
                groupType.SetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE, ceSuccessTemplate.Text);

                // Save group type and attributes
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    groupType.SaveAttributeValues(rockContext);
                });

                if (newGroupType)
                {
                    var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
                    pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString());
                    NavigateToPage(pageRef);
                }
                else
                {
                    groupType = groupTypeService.Get(groupType.Id);
                    ShowReadonlyDetails(groupType);
                }

                Rock.CheckIn.KioskDevice.Clear();
            }
        }
예제 #5
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="groupType">The groupType.</param>
        private void ShowEditDetails(GroupType groupType)
        {
            if (groupType != null)
            {
                if (groupType.Id == 0)
                {
                    lReadOnlyTitle.Text = ActionTitle.Add("Check-in Configuration").FormatAsHtmlTitle();
                }
                else
                {
                    lReadOnlyTitle.Text = groupType.ToString().FormatAsHtmlTitle();
                }

                SetEditMode(true);

                tbName.Text         = groupType.Name;
                tbDescription.Text  = groupType.Description;
                tbIconCssClass.Text = groupType.IconCssClass;
                var rockContext = new RockContext();

                groupType.LoadAttributes(rockContext);

                cbAgeRequired.Checked             = groupType.GetAttributeValue("core_checkin_AgeRequired").AsBoolean(true);
                cbGradeRequired.Checked           = groupType.GetAttributeValue("core_checkin_GradeRequired").AsBoolean(true);
                cbHidePhotos.Checked              = groupType.GetAttributeValue("core_checkin_HidePhotos").AsBoolean(true);
                cbPreventDuplicateCheckin.Checked = groupType.GetAttributeValue("core_checkin_PreventDuplicateCheckin").AsBoolean(true);
                cbPreventInactivePeople.Checked   = groupType.GetAttributeValue("core_checkin_PreventInactivePeople").AsBoolean(true);
                ddlType.SetValue(groupType.GetAttributeValue("core_checkin_CheckInType"));
                cbDisplayLocCount.Checked = groupType.GetAttributeValue("core_checkin_DisplayLocationCount").AsBoolean(true);
                cbEnableManager.Checked   = groupType.GetAttributeValue("core_checkin_EnableManagerOption").AsBoolean(true);
                cbEnableOverride.Checked  = groupType.GetAttributeValue("core_checkin_EnableOverride").AsBoolean(true);
                nbMaxPhoneLength.Text     = groupType.GetAttributeValue("core_checkin_MaximumPhoneSearchLength");
                nbMaxResults.Text         = groupType.GetAttributeValue("core_checkin_MaxSearchResults");
                nbMinPhoneLength.Text     = groupType.GetAttributeValue("core_checkin_MinimumPhoneSearchLength");
                cbUseSameOptions.Checked  = groupType.GetAttributeValue("core_checkin_UseSameOptions").AsBoolean(false);
                ddlPhoneSearchType.SetValue(groupType.GetAttributeValue("core_checkin_PhoneSearchType"));
                nbRefreshInterval.Text = groupType.GetAttributeValue("core_checkin_RefreshInterval");
                tbSearchRegex.Text     = groupType.GetAttributeValue("core_checkin_RegularExpressionFilter");
                cbReuseCode.Checked    = groupType.GetAttributeValue("core_checkin_ReuseSameCode").AsBoolean(false);

                var searchType = DefinedValueCache.Get(groupType.GetAttributeValue("core_checkin_SearchType").AsGuid());
                if (searchType != null)
                {
                    ddlSearchType.SetValue(searchType.Id.ToString());
                }

                nbCodeAlphaNumericLength.Text = groupType.GetAttributeValue("core_checkin_SecurityCodeLength");
                nbCodeAlphaLength.Text        = groupType.GetAttributeValue("core_checkin_SecurityCodeAlphaLength");
                nbCodeNumericLength.Text      = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericLength");
                cbCodeRandom.Checked          = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericRandom").AsBoolean(true);
                cbAllowCheckout.Checked       = groupType.GetAttributeValue("core_checkin_AllowCheckout").AsBoolean(true);
                nbAutoSelectDaysBack.Text     = groupType.GetAttributeValue("core_checkin_AutoSelectDaysBack");
                ddlAutoSelectOptions.SetValue(groupType.GetAttributeValue("core_checkin_AutoSelectOptions"));

                // Registration Settings
                cbRegistrationDisplayAlternateIdFieldForAdults.Checked   = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS).AsBoolean();
                cbRegistrationDisplayAlternateIdFieldForChildren.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN).AsBoolean();

                cbRegistrationDisplaySmsEnabled.Checked   = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON).AsBoolean();
                cbRegistrationSmsEnabledByDefault.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBoolean();

                lbRegistrationRequiredAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS).SplitDelimitedValues());

                lbRegistrationRequiredAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN).SplitDelimitedValues());

                lbRegistrationRequiredAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES).SplitDelimitedValues());
                lbRegistrationOptionalAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES).SplitDelimitedValues());

                int? defaultPersonConnectionStatusValueId   = null;
                Guid?defaultPersonConnectionStatusValueGuid = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS).AsGuidOrNull();
                if (defaultPersonConnectionStatusValueGuid.HasValue)
                {
                    var defaultPersonRecordStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueGuid.Value);
                    if (defaultPersonRecordStatusValue != null)
                    {
                        defaultPersonConnectionStatusValueId = defaultPersonRecordStatusValue.Id;
                    }
                }

                dvpRegistrationDefaultPersonConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid()).Id;
                dvpRegistrationDefaultPersonConnectionStatus.SetValue(defaultPersonConnectionStatusValueId);

                var workflowTypeService = new WorkflowTypeService(rockContext);
                wftpRegistrationAddFamilyWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES).SplitDelimitedValues().AsGuidList()));
                wftpRegistrationAddPersonWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES).SplitDelimitedValues().AsGuidList()));

                cbEnableCheckInAfterRegistration.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION).AsBoolean();

                lbKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES).SplitDelimitedValues());
                lbSameFamilyKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES).SplitDelimitedValues());
                lbCanCheckInKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES).SplitDelimitedValues());

                ceStartTemplate.Text        = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE);
                ceFamilySelectTemplate.Text = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE);
                ceSuccessTemplate.Text      = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE);

                // Other GroupType Attributes
                BuildAttributeEdits(groupType, true);

                SetFieldVisibility();
            }
        }
예제 #6
0
        /// <summary>
        /// Scores the test.
        /// </summary>
        /// <param name="assessmentResponse">The assessment response.</param>
        /// <returns>returns a AssessmentResults object</returns>
        public static AssessmentResults GetResult(Dictionary <string, int> assessmentResponse)
        {
            var assessmentResults   = new AssessmentResults();
            var motivatorThemeScore = new Dictionary <Guid, List <decimal> >();
            var motivatorScore      = new Dictionary <DefinedValueCache, decimal>();
            var grandTotal          = assessmentResponse.Sum(a => Convert.ToDouble(a.Value));

            foreach (var motivatorDefinedValueGuid in constructData.Keys)
            {
                var    conflictProfile = constructData[( Guid )motivatorDefinedValueGuid];
                double totalResponse   = 0;
                var    assessmentData  = new Dictionary <string, string>();
                foreach (var construct in questionData.Where((Func <MotivatorQuestion, bool>)(a => a.MotivatorId.AsGuid() == motivatorDefinedValueGuid)))
                {
                    if (assessmentResponse.ContainsKey(construct.Id))
                    {
                        totalResponse += assessmentResponse[construct.Id];
                        assessmentData.AddOrReplace(construct.Id, assessmentResponse[construct.Id].ToString());
                    }
                }

                var     zScore = Math.Round((totalResponse - conflictProfile.Mean) / conflictProfile.StandardDeviation, 1);
                decimal score  = GetPercentFromScore(zScore);

                // The Growth Propensity score needs to be stored in its own property for Lava merge.
                // Also needs to be a number and not a percentage.
                if (motivatorDefinedValueGuid == SystemGuid.DefinedValue.MOTIVATOR_GROWTH_PROPENSITY.AsGuid())
                {
                    assessmentResults.GrowthScore = score * 100;
                }

                var motivatorDefinedValue = DefinedValueCache.Get(( Guid )motivatorDefinedValueGuid);
                motivatorScore.AddOrReplace(motivatorDefinedValue, score);

                assessmentResults.AssessmentData.AddOrReplace(motivatorDefinedValue.Value, assessmentData);
            }

            assessmentResults.MotivatorScores = motivatorScore
                                                .OrderByDescending(a => a.Value)
                                                .Select(a => new MotivatorScore()
            {
                DefinedValue = a.Key,
                Value        = a.Value
            })
                                                .ToList();

            assessmentResults.TopFiveMotivatorScores = assessmentResults.MotivatorScores.Take(5).ToList();

            foreach (var m in assessmentResults.MotivatorScores)
            {
                var themeGuid = m.DefinedValue.GetAttributeValue("Theme").AsGuidOrNull();
                if (themeGuid.HasValue)
                {
                    if (!motivatorThemeScore.ContainsKey(themeGuid.Value))
                    {
                        motivatorThemeScore[themeGuid.Value] = new List <decimal>();
                    }

                    motivatorThemeScore[themeGuid.Value].Add(m.Value);
                }
            }

            foreach (var themeDefinedValueGuid in motivatorThemeScore.Keys)
            {
                var themeScore        = motivatorThemeScore[themeDefinedValueGuid].Sum() / motivatorThemeScore[themeDefinedValueGuid].Count();
                var themeDefinedValue = DefinedValueCache.Get(( Guid )themeDefinedValueGuid);
                assessmentResults.MotivatorThemeScores.Add(
                    new MotivatorScore()
                {
                    DefinedValue = themeDefinedValue,
                    Value        = themeScore
                });
            }

            return(assessmentResults);
        }
예제 #7
0
        private Dictionary <string, string> BuildFilter()
        {
            Dictionary <string, string> Filter = new Dictionary <string, string>();

            System.Text.StringBuilder StatusSB = new System.Text.StringBuilder();

            foreach (ListItem item in cbListStatus.Items)
            {
                if (item.Selected)
                {
                    StatusSB.Append(item.Value + ",");
                }
            }
            StatusSB.Append("0");
            Filter.Add("StatusLUID", StatusSB.ToString());

            System.Text.StringBuilder RequisitionTypeSB = new System.Text.StringBuilder();
            foreach (ListItem item in cbListType.Items)
            {
                if (item.Selected)
                {
                    StatusSB.Append(item.Value + ",");
                }
            }
            StatusSB.Append("0");
            Filter.Add("TypeLUID", StatusSB.ToString());

            foreach (ListItem item in cbShow.Items)
            {
                Filter.Add(string.Format("Show_{0}", item.Value), item.Selected.ToString());
            }

            int poNumber;

            if (int.TryParse(txtPONumber.Text, out poNumber) && poNumber > 0)
            {
                Filter.Add("PONumber", poNumber.ToString());
            }

            if (txtFilterSubmitted.LowerValue.HasValue)
            {
                Filter.Add("SubmitOnStart", txtFilterSubmitted.LowerValue.Value.ToShortDateString());
            }

            if (txtFilterSubmitted.UpperValue.HasValue)
            {
                Filter.Add("SubmitOnEnd", txtFilterSubmitted.UpperValue.Value.ToShortDateString());
            }

            if (hfFilterSubmittedBy.Visible && hfFilterSubmittedBy.StaffPersonAliasId.HasValue)
            {
                Filter.Add("RequesterID", hfFilterSubmittedBy.StaffPersonAliasId.ToString());
            }

            int MinistryID = 0;

            if (ddlMinistry.Visible && int.TryParse(ddlMinistry.SelectedValue, out MinistryID))
            {
                Filter.Add("MinistryLUID", MinistryID.ToString());
            }

            int LocationID = 0;

            if (ddlLocation.Visible && int.TryParse(ddlLocation.SelectedValue, out LocationID))
            {
                Filter.Add("LocationLUID", LocationID.ToString());
            }

            bool ShowInactive = false;

            if (chkShowInactive.Visible)
            {
                ShowInactive = chkShowInactive.Checked;
            }

            Filter.Add("ShowInactive", ShowInactive.ToString());


            Filter.Add("PersonID", CurrentPerson.Id.ToString());
            UserLoginService loginService = new UserLoginService(new RockContext());

            Filter.Add("UserName", string.Join(",", loginService.GetByPersonId(CurrentPerson.Id).Select(l => l.UserName)));
            CurrentPerson.LoadAttributes();
            bool skipLocation = false;

            if (MinistryAreaAttributeIDSetting != null)
            {
                List <Guid> ministryGuids  = CurrentPerson.AttributeValues[AttributeCache.Get(MinistryAreaAttributeIDSetting).Key].Value.Split(',').AsGuidList();
                var         ministryValues = DefinedValueCache.All().Where(dv => ministryGuids.Contains(dv.Guid));
                if (ministryValues.Count() > 0)
                {
                    Filter.Add("MyMinistryIDs", ministryValues.Select(mv => mv.Id.ToString()).JoinStrings(","));
                }

                // If the current person is in the security group, skip the location lookup
                foreach (var ministryValue in ministryValues)
                {
                    var groupGuid = ministryValue.GetAttributeValue("ChurchWidePurchasingSecurityGroup").AsGuidOrNull();
                    if (groupGuid.HasValue)
                    {
                        GroupService groupService = new GroupService(new RockContext());
                        Group        group        = groupService.Get(groupGuid.Value);
                        skipLocation = skipLocation || group.Members.Where(gm => gm.PersonId == CurrentPerson.Id).Any();
                    }
                }
            }

            if (MinistryLocationAttributeIDSetting != null && !skipLocation)
            {
                var locationValue = DefinedValueCache.Get(CurrentPerson.AttributeValues[AttributeCache.Get(MinistryLocationAttributeIDSetting).Key].Value);

                if (locationValue != null)
                {
                    Filter.Add("MyLocationID", locationValue.Id.ToString());
                }
            }
            return(Filter);
        }
예제 #8
0
        protected void CreateUser()
        {
            var rockContext      = new RockContext();
            var userLoginService = new UserLoginService(rockContext);

            if (!IsUserAuthorized(Authorization.ADMINISTRATE))
            {
                return;
            }
            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var restUser      = new Person();

                personService.Add(restUser);
                rockContext.SaveChanges();

                // the rest user name gets saved as the last name on a person
                restUser.LastName            = "apollos";
                restUser.RecordTypeValueId   = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid()).Id;
                restUser.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;


                if (restUser.IsValid)
                {
                    rockContext.SaveChanges();
                }

                // the description gets saved as a system note for the person
                var noteType = NoteTypeCache.Get(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE.AsGuid());
                if (noteType != null)
                {
                    var noteService = new NoteService(rockContext);
                    var note        = noteService.Get(noteType.Id, restUser.Id).FirstOrDefault();
                    if (note == null)
                    {
                        note = new Note();
                        noteService.Add(note);
                    }
                    note.NoteTypeId = noteType.Id;
                    note.EntityId   = restUser.Id;
                    note.Text       = "Apollos API User - used for authenticating Apollos Server with Rock";
                }
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService(rockContext)
                                 .Get("Rock.Security.Authentication.Database");

                var userLogin = new UserLogin();
                userLoginService.Add(userLogin);

                userLogin.UserName = Guid.NewGuid().ToString();

                userLogin.IsConfirmed  = true;
                userLogin.ApiKey       = GenerateKey();
                userLogin.PersonId     = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();

                var groupMemberService        = new GroupMemberService(rockContext);
                var groupMember               = new GroupMember();
                groupMember.PersonId          = restUser.Id;
                var adminGroup                = new GroupService(rockContext).Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                groupMember.GroupId           = adminGroup.Id;
                var securityGroupMember       = adminGroup.GroupType.Roles.Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_SECURITY_GROUP_MEMBER.AsGuid())).First();
                groupMember.GroupRoleId       = securityGroupMember.Id;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
            });
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var contributionType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            if (contributionType != null)
            {
                var rockContext = new RockContext();
                var transactionDetailService = new FinancialTransactionDetailService(rockContext);
                var qry = transactionDetailService.Queryable().AsNoTracking()
                          .Where(a =>
                                 a.Transaction.TransactionTypeValueId == contributionType.Id &&
                                 a.Transaction.TransactionDateTime.HasValue);

                var targetPerson = this.ContextEntity <Person>();
                if (targetPerson != null)
                {
                    qry = qry.Where(t => t.Transaction.AuthorizedPersonAlias.Person.GivingId == targetPerson.GivingId);
                }

                // Filter to configured Accounts.
                var accountGuids = GetAttributeValue("Accounts").SplitDelimitedValues().AsGuidList();
                if (accountGuids.Any())
                {
                    qry = qry.Where(t => accountGuids.Contains(t.Account.Guid));
                }

                List <SummaryRecord> summaryList;

                using (new Rock.Data.QueryHintScope(rockContext, QueryHintType.RECOMPILE))
                {
                    summaryList = qry
                                  .GroupBy(a => new { a.Transaction.TransactionDateTime.Value.Year, a.AccountId })
                                  .Select(t => new SummaryRecord
                    {
                        Year        = t.Key.Year,
                        AccountId   = t.Key.AccountId,
                        TotalAmount = t.Sum(d => d.Amount)
                    }).OrderByDescending(a => a.Year)
                                  .ToList();
                }

                var mergeFields       = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                var financialAccounts = new FinancialAccountService(rockContext).Queryable().Select(a => new { a.Id, a.Name }).ToDictionary(k => k.Id, v => v.Name);

                var yearsMergeObjects = new List <Dictionary <string, object> >();
                foreach (var item in summaryList.GroupBy(a => a.Year))
                {
                    var year         = item.Key;
                    var accountsList = new List <object>();
                    foreach (var a in item)
                    {
                        var accountDictionary = new Dictionary <string, object>();
                        accountDictionary.Add("Account", financialAccounts.ContainsKey(a.AccountId) ? financialAccounts[a.AccountId] : string.Empty);
                        accountDictionary.Add("TotalAmount", a.TotalAmount);
                        accountsList.Add(accountDictionary);
                    }

                    var yearDictionary = new Dictionary <string, object>();
                    yearDictionary.Add("Year", year);
                    yearDictionary.Add("SummaryRows", accountsList);

                    yearsMergeObjects.Add(yearDictionary);
                }

                mergeFields.Add("Rows", yearsMergeObjects);

                lLavaOutput.Text = string.Empty;

                string template = GetAttributeValue("LavaTemplate");

                lLavaOutput.Text += template.ResolveMergeFields(mergeFields).ResolveClientIds(upnlContent.ClientID);
            }
        }
예제 #10
0
        /// <summary>
        /// Checks the settings.  If false is returned, it's expected that the caller will make
        /// the nbNotice visible to inform the user of the "settings" error.
        /// </summary>
        /// <returns>true if settings are valid; false otherwise</returns>
        private bool CheckSettings()
        {
            _rockContext = _rockContext ?? new RockContext();

            _mode = GetAttributeValue("Mode");

            _autoFill = GetAttributeValue("AutoFillForm").AsBoolean();

            string registerButtonText = GetAttributeValue("RegisterButtonAltText");

            if (string.IsNullOrWhiteSpace(registerButtonText))
            {
                registerButtonText = "Register";
            }
            btnRegister.Text = registerButtonText;

            var  groupService         = new GroupService(_rockContext);
            bool groupIsFromQryString = true;

            Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull();

            if (groupGuid.HasValue)
            {
                _group = groupService.Get(groupGuid.Value);
                groupIsFromQryString = false;
            }

            if (_group == null)
            {
                groupGuid = PageParameter("GroupGuid").AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    _group = groupService.Get(groupGuid.Value);
                }
            }

            if (_group == null && GetAttributeValue("EnablePassingGroupId").AsBoolean(false))
            {
                int?groupId = PageParameter("GroupId").AsIntegerOrNull();
                if (groupId.HasValue)
                {
                    _group = groupService.Get(groupId.Value);
                }
            }

            if (_group == null)
            {
                nbNotice.Heading = "Unknown Group";
                nbNotice.Text    = "<p>This page requires a valid group identifying parameter and there was not one provided.</p>";
                return(false);
            }
            else
            {
                var groupTypeGuids = this.GetAttributeValue("AllowedGroupTypes").SplitDelimitedValues().AsGuidList();

                if (groupIsFromQryString && groupTypeGuids.Any() && !groupTypeGuids.Contains(_group.GroupType.Guid))
                {
                    _group           = null;
                    nbNotice.Heading = "Invalid Group";
                    nbNotice.Text    = "<p>The selected group is a restricted group type therefore this block cannot be used to add people to these groups (unless configured to allow).</p>";
                    return(false);
                }
                else
                {
                    _defaultGroupRole = _group.GroupType.DefaultGroupRole;
                }
            }

            _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
            if (_dvcConnectionStatus == null)
            {
                nbNotice.Heading = "Invalid Connection Status";
                nbNotice.Text    = "<p>The selected Connection Status setting does not exist.</p>";
                return(false);
            }

            _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());
            if (_dvcRecordStatus == null)
            {
                nbNotice.Heading = "Invalid Record Status";
                nbNotice.Text    = "<p>The selected Record Status setting does not exist.</p>";
                return(false);
            }

            _married         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid());
            _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
            _familyType      = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            _adultRole       = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

            if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null)
            {
                nbNotice.Heading = "Missing System Value";
                nbNotice.Text    = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>";
                return(false);
            }

            return(true);
        }
예제 #11
0
파일: Google.cs 프로젝트: ewin66/rockrms
        /// <summary>
        /// Gets the name of the Google user.
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetGoogleUser(GoogleUser googleUser, string accessToken = "")
        {
            // accessToken is required
            if (accessToken.IsNullOrWhiteSpace())
            {
                return(null);
            }

            string username   = string.Empty;
            string googleId   = googleUser.id;
            string googleLink = googleUser.link;

            string    userName = "******" + googleId;
            UserLogin user     = null;

            using (var rockContext = new RockContext())
            {
                // Query for an existing user
                var userLoginService = new UserLoginService(rockContext);
                user = userLoginService.GetByUserName(userName);

                // If no user was found, see if we can find a match in the person table
                if (user == null)
                {
                    // Get name/email from Google login
                    string lastName  = googleUser.family_name.ToString();
                    string firstName = googleUser.given_name.ToString();
                    string email     = string.Empty;
                    try { email = googleUser.email.ToString(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        var personService = new PersonService(rockContext);
                        person = personService.FindPerson(firstName, lastName, email, true);
                    }

                    var personRecordTypeId  = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPending = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                    rockContext.WrapTransaction(() =>
                    {
                        if (person == null)
                        {
                            person                     = new Person();
                            person.IsSystem            = false;
                            person.RecordTypeValueId   = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName           = firstName;
                            person.LastName            = lastName;
                            person.Email               = email;
                            person.IsEmailActive       = true;
                            person.EmailPreference     = EmailPreference.EmailAllowed;
                            try
                            {
                                if (googleUser.gender.ToString() == "male")
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if (googleUser.gender.ToString() == "female")
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if (person != null)
                            {
                                PersonService.SaveNewPerson(person, rockContext, null, false);
                            }
                        }

                        if (person != null)
                        {
                            int typeId = EntityTypeCache.Get(typeof(Google)).Id;
                            user       = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", true);
                        }
                    });
                }
                if (user != null)
                {
                    username = user.UserName;

                    if (user.PersonId.HasValue)
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService(rockContext);
                        var person        = personService.Get(user.PersonId.Value);
                    }
                }

                return(username);
            }
        }
예제 #12
0
        /// <summary>
        /// Shows the details.
        /// </summary>
        private void ShowDetails()
        {
            _rockContext = _rockContext ?? new RockContext();

            if (_group != null)
            {
                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Group", _group);

                string template = GetAttributeValue("LavaTemplate");
                lLavaOverview.Text = template.ResolveMergeFields(mergeFields);

                // Set visibility based on selected mode
                if (IsFullWithSpouse)
                {
                    pnlCol1.RemoveCssClass("col-md-12").AddCssClass("col-md-6");
                }
                else
                {
                    pnlCol1.RemoveCssClass("col-md-6").AddCssClass("col-md-12");
                }
                pnlCol2.Visible = IsFullWithSpouse;

                tbEmail.Required = GetAttributeValue(REQUIRE_EMAIL_KEY).AsBoolean();
                pnCell.Required  = GetAttributeValue(REQUIRE_MOBILE_KEY).AsBoolean();

                pnlHomePhone.Visible = !IsSimple;
                pnlCellPhone.Visible = !IsSimple;
                acAddress.Visible    = !IsSimple;

                string phoneLabel = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Value;
                phoneLabel         = phoneLabel.Trim().EndsWith("Phone") ? phoneLabel : phoneLabel + " Phone";
                pnCell.Label       = phoneLabel;
                pnSpouseCell.Label = "Spouse " + phoneLabel;

                if (CurrentPersonId.HasValue && _autoFill)
                {
                    var    personService = new PersonService(_rockContext);
                    Person person        = personService
                                           .Queryable("PhoneNumbers.NumberTypeValue").AsNoTracking()
                                           .FirstOrDefault(p => p.Id == CurrentPersonId.Value);

                    tbFirstName.Text = CurrentPerson.FirstName;
                    tbLastName.Text  = CurrentPerson.LastName;
                    tbEmail.Text     = CurrentPerson.Email;

                    if (!IsSimple)
                    {
                        Guid homePhoneType = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid();
                        var  homePhone     = person.PhoneNumbers
                                             .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(homePhoneType));
                        if (homePhone != null)
                        {
                            pnHome.Text = homePhone.Number;
                        }

                        Guid cellPhoneType = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid();
                        var  cellPhone     = person.PhoneNumbers
                                             .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(cellPhoneType));
                        if (cellPhone != null)
                        {
                            pnCell.Text   = cellPhone.Number;
                            cbSms.Checked = cellPhone.IsMessagingEnabled;
                        }

                        var homeAddress = person.GetHomeLocation();
                        if (homeAddress != null)
                        {
                            acAddress.SetValues(homeAddress);
                        }

                        if (IsFullWithSpouse)
                        {
                            var spouse = person.GetSpouse(_rockContext);
                            if (spouse != null)
                            {
                                tbSpouseFirstName.Text = spouse.FirstName;
                                tbSpouseLastName.Text  = spouse.LastName;
                                tbSpouseEmail.Text     = spouse.Email;

                                var spouseCellPhone = spouse.PhoneNumbers
                                                      .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(cellPhoneType));
                                if (spouseCellPhone != null)
                                {
                                    pnSpouseCell.Text   = spouseCellPhone.Number;
                                    cbSpouseSms.Checked = spouseCellPhone.IsMessagingEnabled;
                                }
                            }
                        }
                    }
                }

                if (GetAttributeValue("PreventOvercapacityRegistrations").AsBoolean())
                {
                    int openGroupSpots = 2;
                    int openRoleSpots  = 2;

                    // If the group has a GroupCapacity, check how far we are from hitting that.
                    if (_group.GroupCapacity.HasValue)
                    {
                        openGroupSpots = _group.GroupCapacity.Value - _group.ActiveMembers().Count();
                    }

                    // When someone registers for a group on the front-end website, they automatically get added with the group's default
                    // GroupTypeRole. If that role exists and has a MaxCount, check how far we are from hitting that.
                    if (_defaultGroupRole != null && _defaultGroupRole.MaxCount.HasValue)
                    {
                        openRoleSpots = _defaultGroupRole.MaxCount.Value - _group.Members
                                        .Where(m => m.GroupRoleId == _defaultGroupRole.Id && m.GroupMemberStatus == GroupMemberStatus.Active)
                                        .Count();
                    }

                    // Between the group's GroupCapacity and DefaultGroupRole.MaxCount, grab the one we're closest to hitting, and how close we are to
                    // hitting it.
                    int openSpots = Math.Min(openGroupSpots, openRoleSpots);

                    // If there's only one spot open, disable the spouse fields and display a warning message.
                    if (openSpots == 1)
                    {
                        tbSpouseFirstName.Enabled = false;
                        tbSpouseLastName.Enabled  = false;
                        pnSpouseCell.Enabled      = false;
                        cbSpouseSms.Enabled       = false;
                        tbSpouseEmail.Enabled     = false;
                        nbWarning.Text            = "This group is near its capacity. Only one individual can register.";
                        nbWarning.Visible         = true;
                    }

                    // If no spots are open, display a message that says so.
                    if (openSpots <= 0)
                    {
                        nbNotice.Text    = "This group is at or exceeds capacity.";
                        nbNotice.Visible = true;
                        pnlView.Visible  = false;
                    }
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        /// <remarks>Multiple methods depend on the GroupMember object type</remarks>
        /// <param name="isExporting">if set to <c>true</c> [is exporting].</param>
        protected void BindGroupMembersGrid(bool isExporting = false)
        {
            if (_group != null && _group.GroupType.Roles.Any())
            {
                pnlGroupMembers.Visible = true;

                using (var rockContext = new RockContext())
                {
                    // Start query for group members
                    var qry = new GroupMemberService(rockContext)
                              .Queryable("Person,GroupRole", true)
                              .Where(m => m.GroupId == _group.Id && m.Person != null);

                    // Sort the query
                    IOrderedQueryable <GroupMember> orderedQry = null;
                    var sortProperty = pnlGroupMembers.SortProperty;
                    if (sortProperty != null)
                    {
                        orderedQry = qry.Sort(sortProperty);
                    }
                    else
                    {
                        orderedQry = qry
                                     .OrderBy(r => r.Person.LastName)
                                     .ThenBy(r => r.Person.NickName);
                    }

                    // increase the timeout just in case. A complex filter on the grid might slow things down
                    rockContext.Database.CommandTimeout = 180;

                    // Set the grids LinqDataSource which will run query and set results for current page
                    pnlGroupMembers.SetLinqDataSource(orderedQry);

                    var homePhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                    var cellPhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);

                    var groupAttributes = GetGroupAttributes();
                    if (groupAttributes.Any())
                    {
                        // Get the query results for the current page
                        var currentGroupMembers = pnlGroupMembers.DataSource as List <GroupMember>;
                        if (currentGroupMembers != null)
                        {
                            // Get all the person ids in current page of query results
                            var personIds = currentGroupMembers
                                            .Select(r => r.PersonId)
                                            .Distinct()
                                            .ToList();

                            var groupMemberIds = currentGroupMembers
                                                 .Select(r => r.Id)
                                                 .Distinct()
                                                 .ToList();

                            var groupMemberAttributesIds = groupAttributes.Select(a => a.Id).Distinct().ToList();

                            // If there are any attributes that were selected to be displayed, we're going
                            // to try and read all attribute values in one query and then put them into a
                            // custom grid ObjectList property so that the AttributeField columns don't need
                            // to do the LoadAttributes and querying of values for each row/column
                            if (groupMemberAttributesIds.Any())
                            {
                                // Query the attribute values for all rows and attributes
                                var attributeValues = new AttributeValueService(rockContext)
                                                      .Queryable("Attribute").AsNoTracking()
                                                      .Where(v =>
                                                             v.EntityId.HasValue &&
                                                             groupMemberAttributesIds.Contains(v.AttributeId) &&
                                                             groupMemberIds.Contains(v.EntityId.Value)
                                                             )
                                                      .ToList();

                                // Get the attributes to add to each row's object
                                var attributes = new Dictionary <string, AttributeCache>();
                                groupAttributes.ForEach(a =>
                                                        attributes.Add(a.Id + a.Key, a));

                                // Initialize the grid's object list
                                pnlGroupMembers.ObjectList   = new Dictionary <string, object>();
                                pnlGroupMembers.EntityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id;

                                // Loop through each of the current group's members and build an attribute
                                // field object for storing attributes and the values for each of the members
                                foreach (var groupMember in currentGroupMembers)
                                {
                                    // Create a row attribute object
                                    var attributeFieldObject = new AttributeFieldObject
                                    {
                                        // Add the attributes to the attribute object
                                        Attributes = attributes
                                    };

                                    // Add any group member attribute values to object
                                    if (groupMember.Id > 0)
                                    {
                                        attributeValues
                                        .Where(v =>
                                               groupMemberAttributesIds.Contains(v.AttributeId) &&
                                               v.EntityId.Value == groupMember.Id)
                                        .ToList()
                                        .ForEach(v => attributeFieldObject.AttributeValues
                                                 .Add(v.AttributeId + v.Attribute.Key, new AttributeValueCache(v)));
                                    }

                                    // Add row attribute object to grid's object list
                                    pnlGroupMembers.ObjectList.Add(groupMember.Id.ToString(), attributeFieldObject);
                                }
                            }
                        }
                    }

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

            var attribute = AttributeCache.Get(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                var      createNameless     = GetAttributeValue(action, "CreateNamelessPerson").AsBoolean();
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (!createNameless && (   //If we cannot create a namless person we must have a minimum set of values to match
                        string.IsNullOrWhiteSpace(firstName) ||
                        string.IsNullOrWhiteSpace(lastName) ||
                        (string.IsNullOrWhiteSpace(email) &&
                         string.IsNullOrWhiteSpace(phone) &&
                         !dateofBirth.HasValue &&
                         (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1))))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else if (createNameless &&  //Else if we can create a nameless person we at least need email and phone
                         string.IsNullOrWhiteSpace(email) &&
                         string.IsNullOrWhiteSpace(phone))
                {
                    errorMessages.Add("Email or Phone is required to create a nameless person. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);

                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode, createNameless).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }

                        // Save/update the phone number
                        if (!string.IsNullOrWhiteSpace(phone))
                        {
                            List <string> changes    = new List <string>();
                            var           numberType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneNumberType").AsGuid());
                            if (numberType != null)
                            {
                                // gets value indicating if phone number is unlisted
                                string unlistedValue     = GetAttributeValue(action, "Unlisted");
                                Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                                if (unlistedValueGuid.HasValue)
                                {
                                    unlistedValue = action.GetWorkflowAttributeValue(unlistedValueGuid.Value);
                                }
                                else
                                {
                                    unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                                }
                                bool unlisted = unlistedValue.AsBoolean();

                                // gets value indicating if messaging should be enabled for phone number
                                string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                                Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                                if (smsEnabledValueGuid.HasValue)
                                {
                                    smsEnabledValue = action.GetWorkflowAttributeValue(smsEnabledValueGuid.Value);
                                }
                                else
                                {
                                    smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                                }
                                bool smsEnabled = smsEnabledValue.AsBoolean();


                                var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                                string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                                string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                                if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                                {
                                    if (phoneModel == null)
                                    {
                                        phoneModel = new PhoneNumber();
                                        person.PhoneNumbers.Add(phoneModel);
                                        phoneModel.NumberTypeValueId = numberType.Id;
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                    }
                                    phoneModel.Number             = newPhoneNumber;
                                    phoneModel.IsUnlisted         = unlisted;
                                    phoneModel.IsMessagingEnabled = smsEnabled;
                                }
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                if (GetAttributeValue(action, "ContinueOnError").AsBoolean())
                {
                    errorMessages.Clear();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #15
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(DefinedValueCache.Get(this.Id));
 }
        /// <summary>
        /// Sends a background request to Protect My Ministry
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the PMM background check request
        ///     RequestStatus:          The request status returned by PMM request
        ///     RequestMessage:         Any error messages returned by PMM request
        ///     ReportStatus:           The report status returned by PMM
        ///     ReportLink:             The location of the background report on PMM server
        ///     ReportRecommendation:   PMM's recommendation
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest(RockContext rockContext, Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid workflow.");
                    return(false);
                }

                // Get the person that the request is for
                Person person = null;
                if (personAttribute != null)
                {
                    Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                    if (personAliasGuid.HasValue)
                    {
                        person = new PersonAliasService(rockContext).Queryable()
                                 .Where(p => p.Guid.Equals(personAliasGuid.Value))
                                 .Select(p => p.Person)
                                 .FirstOrDefault();
                        person.LoadAttributes(rockContext);
                    }
                }

                if (person == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                    return(false);
                }

                string password = Encryption.DecryptString(GetAttributeValue("Password"));

                XElement rootElement = new XElement("OrderXML",
                                                    new XElement("Method", "SEND ORDER"),
                                                    new XElement("Authentication",
                                                                 new XElement("Username", GetAttributeValue("UserName")),
                                                                 new XElement("Password", password)
                                                                 )
                                                    );

                rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL")));

                XElement orderElement = new XElement("Order");
                rootElement.Add(orderElement);

                if (billingCodeAttribute != null)
                {
                    string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key);
                    Guid?  campusGuid  = billingCode.AsGuidOrNull();
                    if (campusGuid.HasValue)
                    {
                        var campus = CampusCache.Get(campusGuid.Value);
                        if (campus != null)
                        {
                            billingCode = campus.Name;
                        }
                    }
                    orderElement.Add(new XElement("BillingReferenceCode", billingCode));
                }

                XElement subjectElement = new XElement("Subject",
                                                       new XElement("FirstName", person.FirstName),
                                                       new XElement("MiddleName", person.MiddleName),
                                                       new XElement("LastName", person.LastName)
                                                       );
                orderElement.Add(subjectElement);

                if (person.SuffixValue != null)
                {
                    subjectElement.Add(new XElement("Generation", person.SuffixValue.Value));
                }
                if (person.BirthDate.HasValue)
                {
                    subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy")));
                }

                if (ssnAttribute != null)
                {
                    string ssn = Field.Types.SSNFieldType.UnencryptAndClean(workflow.GetAttributeValue(ssnAttribute.Key));
                    if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9)
                    {
                        subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-")));
                    }
                }

                if (person.Gender == Gender.Male)
                {
                    subjectElement.Add(new XElement("Gender", "Male"));
                }
                if (person.Gender == Gender.Female)
                {
                    subjectElement.Add(new XElement("Gender", "Female"));
                }

                string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber");
                if (!string.IsNullOrWhiteSpace(dlNumber))
                {
                    subjectElement.Add(new XElement("DLNumber", dlNumber));
                }

                if (!string.IsNullOrWhiteSpace(person.Email))
                {
                    subjectElement.Add(new XElement("EmailAddress", person.Email));
                }

                var homelocation = person.GetHomeLocation();
                if (homelocation != null)
                {
                    subjectElement.Add(new XElement("CurrentAddress",
                                                    new XElement("StreetAddress", homelocation.Street1),
                                                    new XElement("City", homelocation.City),
                                                    new XElement("State", homelocation.State),
                                                    new XElement("Zipcode", homelocation.PostalCode)
                                                    ));
                }

                XElement aliasesElement = new XElement("Aliases");
                if (person.NickName != person.FirstName)
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName)));
                }

                foreach (var previousName in person.GetPreviousNames())
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName)));
                }

                if (aliasesElement.HasElements)
                {
                    subjectElement.Add(aliasesElement);
                }

                DefinedValueCache pkgTypeDefinedValue = null;
                string            packageName         = "BASIC";
                string            county          = string.Empty;
                string            state           = string.Empty;
                string            mvrJurisdiction = string.Empty;
                string            mvrState        = string.Empty;

                if (requestTypeAttribute != null)
                {
                    pkgTypeDefinedValue = DefinedValueCache.Get(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid());
                    if (pkgTypeDefinedValue != null)
                    {
                        if (pkgTypeDefinedValue.Attributes == null)
                        {
                            // shouldn't happen since pkgTypeDefinedValue is a ModelCache<,> type
                            return(false);
                        }

                        packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName");
                        county      = pkgTypeDefinedValue.GetAttributeValue("DefaultCounty");
                        state       = pkgTypeDefinedValue.GetAttributeValue("DefaultState");
                        Guid?mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue("MVRJurisdiction").AsGuidOrNull();
                        if (mvrJurisdictionGuid.HasValue)
                        {
                            var mvrJurisdictionDv = DefinedValueCache.Get(mvrJurisdictionGuid.Value);
                            if (mvrJurisdictionDv != null)
                            {
                                mvrJurisdiction = mvrJurisdictionDv.Value;
                                if (mvrJurisdiction.Length >= 2)
                                {
                                    mvrState = mvrJurisdiction.Left(2);
                                }
                            }
                        }

                        if (homelocation != null)
                        {
                            if (!string.IsNullOrWhiteSpace(homelocation.County) &&
                                pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean())
                            {
                                county = homelocation.County;
                            }

                            if (!string.IsNullOrWhiteSpace(homelocation.State))
                            {
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeState").AsBoolean())
                                {
                                    state = homelocation.State;
                                }
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeStateMVR").AsBoolean())
                                {
                                    mvrState = homelocation.State;
                                }
                            }
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(packageName))
                {
                    orderElement.Add(new XElement("PackageServiceCode", packageName,
                                                  new XAttribute("OrderId", workflow.Id.ToString())));

                    if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) ||
                        packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase))
                    {
                        orderElement.Add(new XElement("OrderDetail",
                                                      new XAttribute("OrderId", workflow.Id.ToString()),
                                                      new XAttribute("ServiceCode", "combo")));
                    }
                }

                if (!string.IsNullOrWhiteSpace(county) ||
                    !string.IsNullOrWhiteSpace(state))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim"),
                                                  new XElement("County", county),
                                                  new XElement("State", state),
                                                  new XElement("YearsToSearch", 7),
                                                  new XElement("CourtDocsRequested", "NO"),
                                                  new XElement("RushRequested", "NO"),
                                                  new XElement("SpecialInstructions", ""))
                                     );
                }

                if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", "MVR"),
                                                  new XElement("JurisdictionCode", mvrJurisdiction),
                                                  new XElement("State", mvrState))
                                     );
                }

                XDocument xdoc            = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement);
                var       requestDateTime = RockDateTime.Now;

                XDocument xResult          = PostToWebService(xdoc, GetAttributeValue("RequestURL"));
                var       responseDateTime = RockDateTime.Now;

                int?personAliasId = person.PrimaryAliasId;
                if (personAliasId.HasValue)
                {
                    // Create a background check file
                    using (var newRockContext = new RockContext())
                    {
                        var backgroundCheckService = new BackgroundCheckService(newRockContext);
                        var backgroundCheck        = backgroundCheckService.Queryable()
                                                     .Where(c =>
                                                            c.WorkflowId.HasValue &&
                                                            c.WorkflowId.Value == workflow.Id)
                                                     .FirstOrDefault();

                        if (backgroundCheck == null)
                        {
                            backgroundCheck = new Rock.Model.BackgroundCheck();
                            backgroundCheck.PersonAliasId = personAliasId.Value;
                            backgroundCheck.WorkflowId    = workflow.Id;
                            backgroundCheck.ForeignId     = 1;
                            backgroundCheckService.Add(backgroundCheck);
                        }

                        backgroundCheck.RequestDate = RockDateTime.Now;

                        // Clear any SSN nodes before saving XML to record
                        foreach (var xSSNElement in xdoc.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }
                        foreach (var xSSNElement in xResult.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }

                        backgroundCheck.ResponseData = string.Format(@"
Request XML ({0}): 
------------------------ 
{1}

Response XML ({2}): 
------------------------ 
{3}

", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString());
                        newRockContext.SaveChanges();
                    }
                }

                using (var newRockContext = new RockContext())
                {
                    var handledErrorMessages = new List <string>();

                    if (_httpStatusCode == HttpStatusCode.OK)
                    {
                        var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault();
                        if (xOrderXML != null)
                        {
                            var xStatus = xOrderXML.Elements("Status").FirstOrDefault();
                            if (xStatus != null)
                            {
                                if (SaveAttributeValue(workflow, "RequestStatus", xStatus.Value,
                                                       FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                                {
                                }
                            }

                            handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            var xErrors = xOrderXML.Elements("Errors").FirstOrDefault();
                            if (xErrors != null)
                            {
                                handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            }

                            if (xResult.Root.Descendants().Count() > 0)
                            {
                                SaveResults(xResult, workflow, rockContext, false);
                            }
                        }
                    }
                    else
                    {
                        handledErrorMessages.Add("Invalid HttpStatusCode: " + _httpStatusCode.ToString());
                    }

                    if (handledErrorMessages.Any())
                    {
                        if (SaveAttributeValue(workflow, "RequestMessage", handledErrorMessages.AsDelimited(Environment.NewLine),
                                               FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                        {
                        }
                    }

                    newRockContext.SaveChanges();

                    return(true);
                }
            }

            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                return(false);
            }
        }
예제 #17
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            // Get the From value
            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Get(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            // Get the recipients
            var    recipients = new List <RockSMSMessageRecipient>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            var smsNumber = toAttributeValue;
                            recipients.Add(RockSMSMessageRecipient.CreateAnonymous(smsNumber, mergeFields));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);

                                    var recipient = new RockSMSMessageRecipient(person, smsNumber, mergeFields);
                                    recipients.Add(recipient);
                                    recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RockSMSMessageRecipient(person, smsNumber, recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockSMSMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

            // Get the message from the Message attribute.
            // NOTE: Passing 'true' as the checkWorkflowAttributeValue will also check the workflow AttributeValue
            // which allows us to remove the unneeded code.
            string message = GetAttributeValue(action, "Message", checkWorkflowAttributeValue: true);

            // Add the attachment (if one was specified)
            var        attachmentBinaryFileGuid = GetAttributeValue(action, "Attachment", true).AsGuidOrNull();
            BinaryFile binaryFile = null;

            if (attachmentBinaryFileGuid.HasValue && attachmentBinaryFileGuid != Guid.Empty)
            {
                binaryFile = new BinaryFileService(rockContext).Get(attachmentBinaryFileGuid.Value);
            }

            // Send the message
            if (recipients.Any() && (!string.IsNullOrWhiteSpace(message) || binaryFile != null))
            {
                var smsMessage = new RockSMSMessage();
                smsMessage.SetRecipients(recipients);
                smsMessage.FromNumber = DefinedValueCache.Get(fromId.Value);
                smsMessage.Message    = message;
                smsMessage.CreateCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();
                smsMessage.communicationName         = action.ActionTypeCache.Name;

                if (binaryFile != null)
                {
                    smsMessage.Attachments.Add(binaryFile);
                }

                smsMessage.Send();
            }
            else
            {
                action.AddLogEntry("Warning: No text or attachment was supplied so nothing was sent.", true);
            }

            return(true);
        }
예제 #18
0
        /// <summary>
        /// Sets the name of the person.
        /// </summary>
        private void SetPersonName()
        {
            // Check if this record represents a Business.
            bool isBusiness = false;

            if (Person.RecordTypeValueId.HasValue)
            {
                int recordTypeValueIdBusiness = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                isBusiness = (Person.RecordTypeValueId.Value == recordTypeValueIdBusiness);
            }

            // Get the Display Name.
            string nameText;

            if (isBusiness)
            {
                nameText = Person.LastName;
            }
            else
            {
                if (GetAttributeValue(AttributeKey.DisplayMiddleName).AsBoolean() && !String.IsNullOrWhiteSpace(Person.MiddleName))
                {
                    nameText = string.Format("<span class='first-word nickname'>{0}</span> <span class='middlename'>{1}</span> <span class='lastname'>{2}</span>", Person.NickName, Person.MiddleName, Person.LastName);
                }
                else
                {
                    nameText = string.Format("<span class='first-word nickname'>{0}</span> <span class='lastname'>{1}</span>", Person.NickName, Person.LastName);
                }

                // Prefix with Title if they have a Title with IsFormal=True
                if (Person.TitleValueId.HasValue)
                {
                    var personTitleValue = DefinedValueCache.Get(Person.TitleValueId.Value);
                    if (personTitleValue != null && personTitleValue.GetAttributeValue("IsFormal").AsBoolean())
                    {
                        nameText = string.Format("<span class='title'>{0}</span> ", personTitleValue.Value) + nameText;
                    }
                }

                // Add First Name if different from NickName.
                if (Person.NickName != Person.FirstName)
                {
                    if (!string.IsNullOrWhiteSpace(Person.FirstName))
                    {
                        nameText += string.Format(" <span class='firstname'>({0})</span>", Person.FirstName);
                    }
                }

                // Add Suffix.
                if (Person.SuffixValueId.HasValue)
                {
                    var suffix = DefinedValueCache.Get(Person.SuffixValueId.Value);
                    if (suffix != null)
                    {
                        nameText += " " + suffix.Value;
                    }
                }

                // Add Previous Names.
                using (var rockContext = new RockContext())
                {
                    var previousNames = Person.GetPreviousNames(rockContext).Select(a => a.LastName);

                    if (previousNames.Any())
                    {
                        nameText += string.Format(Environment.NewLine + "<span class='previous-names'>(Previous Names: {0})</span>", previousNames.ToList().AsDelimited(", "));
                    }
                }
            }

            lName.Text = nameText;
        }
예제 #19
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="groupId">The group identifier.</param>
        /// <param name="groupMemberId">The group member identifier.</param>
        protected void ShowView(int groupId, int groupMemberId)
        {
            pnlView.Visible            = true;
            pnlMain.Visible            = true;
            pnlEditPreferences.Visible = false;
            hfGroupId.Value            = groupId.ToString();
            hfGroupMemberId.Value      = groupMemberId.ToString();
            var rockContext = new RockContext();

            var group = new GroupService(rockContext).Get(groupId);

            if (group == null)
            {
                pnlView.Visible = false;
                return;
            }

            var groupMember = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == groupId && a.Id == groupMemberId).FirstOrDefault();

            if (groupMember == null)
            {
                pnlView.Visible = false;
                return;
            }

            group.LoadAttributes(rockContext);

            // set page title to the trip name
            RockPage.Title        = group.GetAttributeValue("OpportunityTitle");
            RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle");
            RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle");

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Group", group);

            groupMember.LoadAttributes(rockContext);
            mergeFields.Add("GroupMember", groupMember);

            // Left Top Sidebar
            var photoGuid = group.GetAttributeValue("OpportunityPhoto");

            imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid);

            // Top Main
            string profileLavaTemplate = this.GetAttributeValue("ProfileLavaTemplate");

            if (groupMember.PersonId == this.CurrentPersonId)
            {
                // show a warning about missing Photo or Intro if the current person is viewing their own profile
                var warningItems = new List <string>();
                if (!groupMember.Person.PhotoId.HasValue)
                {
                    warningItems.Add("photo");
                }
                if (groupMember.GetAttributeValue("PersonalOpportunityIntroduction").IsNullOrWhiteSpace())
                {
                    warningItems.Add("personal opportunity introduction");
                }

                nbProfileWarning.Text    = "<stong>Tip!</strong> Edit your profile to add a " + warningItems.AsDelimited(", ", " and ") + ".";
                nbProfileWarning.Visible = warningItems.Any();
            }
            else
            {
                nbProfileWarning.Visible = false;
            }

            btnEditProfile.Visible = groupMember.PersonId == this.CurrentPersonId;

            lMainTopContentHtml.Text = profileLavaTemplate.ResolveMergeFields(mergeFields);

            bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean();

            // only show Contribution stuff if the current person is the participant and contribution requests haven't been disabled
            bool showContributions = !disablePublicContributionRequests && (groupMember.PersonId == this.CurrentPersonId);

            btnContributionsTab.Visible = showContributions;

            // Progress
            var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

            var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                    .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                           d.EntityId == groupMemberId)
                                    .Sum(a => (decimal?)a.Amount) ?? 0.00M;

            var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();

            if (!individualFundraisingGoal.HasValue)
            {
                individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
            }

            var amountLeft = individualFundraisingGoal - contributionTotal;
            var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100;

            mergeFields.Add("AmountLeft", amountLeft);
            mergeFields.Add("PercentMet", percentMet);

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

            queryParams.Add("GroupId", hfGroupId.Value);
            queryParams.Add("GroupMemberId", hfGroupMemberId.Value);
            mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams));

            var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid());

            string makeDonationButtonText = null;

            if (groupMember.PersonId == this.CurrentPersonId)
            {
                makeDonationButtonText = "Make Payment";
            }
            else
            {
                makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType);
            }

            mergeFields.Add("MakeDonationButtonText", makeDonationButtonText);

            var progressLavaTemplate = this.GetAttributeValue("ProgressLavaTemplate");

            lProgressHtml.Text = progressLavaTemplate.ResolveMergeFields(mergeFields);

            // set text on the return button
            btnMainPage.Text = opportunityType.Value + " Page";

            // Tab:Updates
            btnUpdatesTab.Visible = false;
            bool showContentChannelUpdates = false;
            var  updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull();

            if (updatesContentChannelGuid.HasValue)
            {
                var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value);
                if (contentChannel != null)
                {
                    showContentChannelUpdates = true;

                    // only show the UpdatesTab if there is another Tab option
                    btnUpdatesTab.Visible = btnContributionsTab.Visible;

                    string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate");
                    var    contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList();

                    mergeFields.Add("ContentChannelItems", contentChannelItems);
                    lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields);
                    btnUpdatesTab.Text            = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count());
                }
            }

            if (showContentChannelUpdates)
            {
                SetActiveTab("Updates");
            }
            else if (showContributions)
            {
                SetActiveTab("Contributions");
            }
            else
            {
                SetActiveTab("");
            }

            // Tab: Contributions
            BindContributionsGrid();

            // Tab:Comments
            var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid());

            if (noteType != null)
            {
                notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> {
                    noteType
                });
            }

            notesCommentsTimeline.NoteOptions.EntityId = groupMember.Id;

            // show the Add button on comments for any logged in person
            notesCommentsTimeline.AddAllowed = true;

            var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean();

            if (CurrentPerson == null)
            {
                notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0);
                lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0;
                pnlComments.Visible           = enableCommenting;
                btnLoginToComment.Visible     = enableCommenting;
            }
            else
            {
                lNoLoginNoCommentsYet.Visible = false;
                notesCommentsTimeline.Visible = enableCommenting;
                pnlComments.Visible           = enableCommenting;
                btnLoginToComment.Visible     = false;
            }

            // if btnContributionsTab is the only visible tab, hide the tab since there is nothing else to tab to
            if (!btnUpdatesTab.Visible && btnContributionsTab.Visible)
            {
                SetActiveTab("Contributions");
                btnContributionsTab.Visible = false;
            }
        }
예제 #20
0
        /// <summary>
        /// Does cleanup of Person Aliases and Metaphones
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PersonCleanup(JobDataMap dataMap)
        {
            // Add any missing person aliases
            using (var personRockContext = new Rock.Data.RockContext())
            {
                PersonService      personService      = new PersonService(personRockContext);
                PersonAliasService personAliasService = new PersonAliasService(personRockContext);
                var personAliasServiceQry             = personAliasService.Queryable();
                foreach (var person in personService.Queryable("Aliases")
                         .Where(p => !p.Aliases.Any() && !personAliasServiceQry.Any(pa => pa.AliasPersonId == p.Id))
                         .Take(300))
                {
                    person.Aliases.Add(new PersonAlias {
                        AliasPersonId = person.Id, AliasPersonGuid = person.Guid
                    });
                }

                personRockContext.SaveChanges();
            }

            AddMissingAlternateIds();

            using (var personRockContext = new Rock.Data.RockContext())
            {
                PersonService personService = new PersonService(personRockContext);
                // Add any missing metaphones
                int namesToProcess = dataMap.GetString("MaxMetaphoneNames").AsIntegerOrNull() ?? 500;
                if (namesToProcess > 0)
                {
                    var firstNameQry = personService.Queryable().Select(p => p.FirstName).Where(p => p != null);
                    var nickNameQry  = personService.Queryable().Select(p => p.NickName).Where(p => p != null);
                    var lastNameQry  = personService.Queryable().Select(p => p.LastName).Where(p => p != null);
                    var nameQry      = firstNameQry.Union(nickNameQry.Union(lastNameQry));

                    var metaphones    = personRockContext.Metaphones;
                    var existingNames = metaphones.Select(m => m.Name).Distinct();

                    // Get the names that have not yet been processed
                    var namesToUpdate = nameQry
                                        .Where(n => !existingNames.Contains(n))
                                        .Take(namesToProcess)
                                        .ToList();

                    foreach (string name in namesToUpdate)
                    {
                        string mp1 = string.Empty;
                        string mp2 = string.Empty;
                        Rock.Utility.DoubleMetaphone.doubleMetaphone(name, ref mp1, ref mp2);

                        var metaphone = new Metaphone();
                        metaphone.Name       = name;
                        metaphone.Metaphone1 = mp1;
                        metaphone.Metaphone2 = mp2;

                        metaphones.Add(metaphone);
                    }

                    personRockContext.SaveChanges(disablePrePostProcessing: true);
                }
            }

            // Ensures the PrimaryFamily is correct for all person records in the database
            using (var personRockContext = new Rock.Data.RockContext())
            {
                int primaryFamilyUpdates = PersonService.UpdatePrimaryFamilyAll(personRockContext);
            }

            // update any updated or incorrect age classifications on persons
            using (var personRockContext = new Rock.Data.RockContext())
            {
                int ageClassificationUpdates = PersonService.UpdatePersonAgeClassificationAll(personRockContext);
            }

            //// Add any missing Implied/Known relationship groups
            // Known Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS), Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid());

            // Implied Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK), Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid());

            // Find family groups that have no members or that have only 'inactive' people (record status) and mark the groups inactive.
            using (var familyRockContext = new Rock.Data.RockContext())
            {
                int familyGroupTypeId           = GroupTypeCache.GetFamilyGroupType().Id;
                int recordStatusInactiveValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()).Id;

                var activeFamilyWithNoActiveMembers = new GroupService(familyRockContext).Queryable()
                                                      .Where(a => a.GroupTypeId == familyGroupTypeId && a.IsActive == true)
                                                      .Where(a => !a.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveValueId).Any());

                var currentDateTime = RockDateTime.Now;

                familyRockContext.BulkUpdate(activeFamilyWithNoActiveMembers, x => new Rock.Model.Group
                {
                    IsActive = false
                });
            }
        }
        /// <summary>
        /// Show and prepare the content panel, or show the error panel.
        /// </summary>
        protected void ShowContent()
        {
            var            rockContext         = new RockContext();
            var            deviceService       = new DeviceService(rockContext);
            var            digitalDisplayId    = DefinedValueCache.Get(SystemGuid.DefinedValue.DEVICE_TYPE_DIGITAL_DISPLAY.AsGuid()).Id;
            var            ipAddress           = Request.UserHostAddress;
            bool           enableReverseLookup = GetAttributeValue("EnableReverseLookup").AsBoolean(true);
            Device         device         = null;
            ContentChannel contentChannel = null;

            if (!string.IsNullOrWhiteSpace(PageParameter("deviceId")))
            {
                device = deviceService.Get(PageParameter("deviceId").AsInteger());
            }
            else
            {
                device = deviceService.Queryable()
                         .Where(d => d.DeviceTypeValueId == digitalDisplayId && d.IPAddress == ipAddress)
                         .FirstOrDefault();

                if (device == null && enableReverseLookup)
                {
                    try
                    {
                        var hostName = System.Net.Dns.GetHostEntry(ipAddress).HostName;
                        device = deviceService.Queryable()
                                 .Where(d => d.DeviceTypeValueId == digitalDisplayId && d.IPAddress == hostName)
                                 .FirstOrDefault();
                    }
                    catch
                    {
                        /* Intentionally ignored. */
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("ContentChannelOverride")))
            {
                contentChannel = new ContentChannelService(rockContext).Get(GetAttributeValue("ContentChannelOverride").AsGuid());
            }

            //
            // If we have a valid device then show the content panel. Othrwise show an error.
            //
            if (device != null || contentChannel != null)
            {
                if (device != null)
                {
                    hfDevice.Value = device.Id.ToString();
                }

                if (GetAttributeValue("SlideInterval").AsInteger() >= 4)
                {
                    hfSlideInterval.Value = (GetAttributeValue("SlideInterval").AsInteger() * 1000).ToString();
                }

                if (GetAttributeValue("UpdateInterval").AsInteger() >= 10)
                {
                    hfUpdateInterval.Value = (GetAttributeValue("UpdateInterval").AsInteger() * 1000).ToString();
                }

                if (!string.IsNullOrWhiteSpace(GetAttributeValue("Transitions")))
                {
                    hfTransitions.Value = GetAttributeValue("Transitions");
                }

                if (contentChannel != null)
                {
                    hfContentChannel.Value = contentChannel.Id.ToString();
                }

                hfAudio.Value = PageParameter("Audio").AsBoolean(true).ToString().ToLower();

                pnlError.Visible   = false;
                pnlContent.Visible = true;
            }
            else
            {
                pnlContent.Visible = false;
                pnlError.Visible   = true;

                nbError.Text = string.Format("This kiosk has not been configured in the system.<br />IP address: {0}",
                                             ipAddress);
            }
        }
        /// <summary>
        /// Handles the Click event of the btnRegister 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 btnRegister_Click(object sender, EventArgs e)
        {
            // Check _isValidSettings in case the form was showing and they clicked the visible register button.
            if (Page.IsValid && _isValidSettings)
            {
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);

                Person        person       = null;
                Person        spouse       = null;
                Group         family       = null;
                GroupLocation homeLocation = null;
                bool          isMatch      = false;

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if (_autoFill)
                {
                    if (CurrentPerson != null && CurrentPerson.NickName.IsNotNullOrWhiteSpace() && CurrentPerson.LastName.IsNotNullOrWhiteSpace() &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.NickName.Trim(), StringComparison.OrdinalIgnoreCase) &&
                        tbLastName.Text.Trim().Equals(CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        person  = personService.Get(CurrentPerson.Id);
                        isMatch = true;
                    }
                }

                // Try to find person by name/email
                if (person == null)
                {
                    var personQuery = new PersonService.PersonMatchQuery(tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim(), pnCell.Text.Trim());
                    person = personService.FindPerson(personQuery, true);
                    if (person != null)
                    {
                        isMatch = true;
                    }
                }

                // Check to see if this is a new person
                if (person == null)
                {
                    var people = personService.GetByMatch(
                        tbFirstName.Text.Trim(),
                        tbLastName.Text.Trim(),
                        dppDOB.SelectedDate,
                        tbEmail.Text.Trim(),
                        pnCell.Text.Trim(),
                        acAddress.Street1,
                        acAddress.PostalCode);
                    if (people.Count() == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(tbEmail.Text.Trim()) ||
                         (people.First().Email != null &&
                          tbEmail.Text.ToLower().Trim() == people.First().Email.ToLower().Trim())) &&

                        // Make sure their DOB matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (!dppDOB.SelectedDate.HasValue ||
                         (people.First().BirthDate != null &&
                          dppDOB.SelectedDate.Value == people.First().BirthDate))
                        )
                    {
                        person = people.First();
                    }
                    else
                    {
                        // If so, create the person and family record for the new person
                        person           = new Person();
                        person.FirstName = tbFirstName.Text.Trim();
                        person.LastName  = tbLastName.Text.Trim();
                        person.Email     = tbEmail.Text.Trim();
                        if (dppDOB.SelectedDate.HasValue)
                        {
                            person.BirthDay   = dppDOB.SelectedDate.Value.Day;
                            person.BirthMonth = dppDOB.SelectedDate.Value.Month;
                            person.BirthYear  = dppDOB.SelectedDate.Value.Year;
                        }
                        person.IsEmailActive           = true;
                        person.EmailPreference         = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                        person.RecordStatusValueId     = _dvcRecordStatus.Id;
                        person.Gender = Gender.Unknown;

                        family = PersonService.SaveNewPerson(person, rockContext, _publishGroup.Group.CampusId, false);
                    }
                }
                else
                {
                    // updating current existing person
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies(rockContext);

                    // If address can being entered, look for first family with a home location

                    foreach (var aFamily in families)
                    {
                        homeLocation = aFamily.GroupLocations
                                       .Where(l =>
                                              l.GroupLocationTypeValueId == _homeAddressType.Id)
                                       .FirstOrDefault();
                        if (homeLocation != null)
                        {
                            family = aFamily;
                            break;
                        }
                    }


                    // If a family wasn't found with a home location, use the person's first family
                    if (family == null)
                    {
                        family = families.FirstOrDefault();
                    }
                }


                if (!isMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                {
                    SetPhoneNumber(rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                }
                if (!isMatch || !string.IsNullOrWhiteSpace(pnCell.Number))
                {
                    SetPhoneNumber(rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                }

                if (!isMatch || !string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    string oldLocation = homeLocation != null?homeLocation.Location.ToString() : string.Empty;

                    string newLocation = string.Empty;

                    var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (location != null)
                    {
                        if (homeLocation == null)
                        {
                            homeLocation = new GroupLocation();
                            homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                            homeLocation.IsMappedLocation         = true;
                            family.GroupLocations.Add(homeLocation);
                        }
                        else
                        {
                            oldLocation = homeLocation.Location.ToString();
                        }

                        homeLocation.Location = location;
                        newLocation           = location.ToString();
                    }
                    else
                    {
                        if (homeLocation != null)
                        {
                            homeLocation.Location = null;
                            family.GroupLocations.Remove(homeLocation);
                            new GroupLocationService(rockContext).Delete(homeLocation);
                        }
                    }
                }

                // Check for the spouse
                if (cbRegisterSpouse.Checked && _showSpouse && tbSpouseFirstName.Text.IsNotNullOrWhiteSpace() && tbSpouseLastName.Text.IsNotNullOrWhiteSpace())
                {
                    spouse = person.GetSpouse(rockContext);
                    bool isSpouseMatch = true;

                    if (spouse == null ||
                        !tbSpouseFirstName.Text.Trim().Equals(spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                        !tbSpouseLastName.Text.Trim().Equals(spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(tbSpouseEmail.Text.Trim()) ||
                         (spouse.Email != null &&
                          tbSpouseEmail.Text.ToLower().Trim() != spouse.Email.ToLower().Trim())) &&

                        // Make sure their DOB matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (!dppSpouseDOB.SelectedDate.HasValue ||
                         (spouse.BirthDate != null &&
                          dppSpouseDOB.SelectedDate.Value != spouse.BirthDate))
                        )
                    {
                        spouse        = new Person();
                        isSpouseMatch = false;

                        spouse.FirstName = tbSpouseFirstName.Text.FixCase();
                        spouse.LastName  = tbSpouseLastName.Text.FixCase();

                        if (dppSpouseDOB.SelectedDate.HasValue)
                        {
                            spouse.BirthDay   = dppSpouseDOB.SelectedDate.Value.Day;
                            spouse.BirthMonth = dppSpouseDOB.SelectedDate.Value.Month;
                            spouse.BirthYear  = dppSpouseDOB.SelectedDate.Value.Year;
                        }

                        spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                        spouse.RecordStatusValueId     = _dvcRecordStatus.Id;
                        spouse.Gender = Gender.Unknown;

                        spouse.IsEmailActive   = true;
                        spouse.EmailPreference = EmailPreference.EmailAllowed;

                        var groupMember = new GroupMember();
                        groupMember.GroupRoleId = _adultRole.Id;
                        groupMember.Person      = spouse;

                        family.Members.Add(groupMember);

                        spouse.MaritalStatusValueId = _married.Id;
                        person.MaritalStatusValueId = _married.Id;
                    }

                    spouse.Email = tbSpouseEmail.Text;

                    if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                    {
                        SetPhoneNumber(rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                    }

                    if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnSpouseCell.Number))
                    {
                        SetPhoneNumber(rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                    }
                }


                // Save the person/spouse and change history
                rockContext.SaveChanges();

                // Check to see if a workflow should be launched for each person
                WorkflowTypeCache workflowType = null;
                Guid?workflowTypeGuid          = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List <GroupMember>();
                AddPersonToGroup(rockContext, person, workflowType, newGroupMembers);
                AddPersonToGroup(rockContext, spouse, workflowType, newGroupMembers);

                // Show the results
                pnlView.Visible   = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("PublishGroup", _publishGroup);
                mergeFields.Add("Group", _publishGroup.Group);
                mergeFields.Add("GroupMembers", newGroupMembers);

                string template = GetAttributeValue("ResultLavaTemplate");
                lResult.Text = template.ResolveMergeFields(mergeFields);

                SendConfirmation(person);
                SendConfirmation(spouse);

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
예제 #23
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="groupTypeId">The groupType identifier.</param>
        public void ShowDetail(int groupTypeId)
        {
            pnlDetails.Visible = false;

            bool editAllowed = true;

            GroupType groupType = null;

            if (!groupTypeId.Equals(0))
            {
                groupType = new GroupTypeService(new RockContext()).Get(groupTypeId);
                pdAuditDetails.SetEntity(groupType, ResolveRockUrl("~"));
            }

            if (groupType == null)
            {
                groupType = new GroupType {
                    Id = 0
                };
                var templatePurpose = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if (groupType != null)
            {
                editAllowed = groupType.IsAuthorized(Authorization.EDIT, CurrentPerson);

                pnlDetails.Visible  = true;
                hfGroupTypeId.Value = groupType.Id.ToString();

                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                if (!editAllowed || !IsUserAuthorized(Authorization.EDIT))
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(GroupType.FriendlyTypeName);
                }

                if (readOnly)
                {
                    btnEdit.Visible   = false;
                    btnDelete.Visible = false;
                    ShowReadonlyDetails(groupType);
                }
                else
                {
                    btnEdit.Visible   = true;
                    btnDelete.Visible = true;

                    if (groupType.Id > 0)
                    {
                        ShowReadonlyDetails(groupType);
                    }
                    else
                    {
                        ShowEditDetails(groupType);
                    }
                }
            }
        }
        /// <summary>
        /// Shows the details.
        /// </summary>
        private void ShowDetails()
        {
            _rockContext = _rockContext ?? new RockContext();

            if (_publishGroup != null)
            {
                if ((_publishGroup.RegistrationRequirement != RegistrationRequirement.RegistrationAvailable &&
                     _publishGroup.RegistrationRequirement != RegistrationRequirement.RegistrationRequired) ||
                    _publishGroup.StartDateTime > Rock.RockDateTime.Now ||
                    _publishGroup.EndDateTime < Rock.RockDateTime.Now)
                {
                    pnlForm.Visible = false;
                }

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("PublishGroup", _publishGroup);
                mergeFields.Add("Group", _publishGroup.Group);

                string template = GetAttributeValue("LavaTemplate");
                lLavaOverview.Text = template.ResolveMergeFields(mergeFields);

                pnlCol2.Visible = _showSpouse;

                tbEmail.Required      = GetAttributeValue(REQUIRE_EMAIL_KEY).AsBoolean();
                pnCell.Required       = GetAttributeValue(REQUIRE_MOBILE_KEY).AsBoolean();
                dppDOB.Required       = GetAttributeValue(REQUIRE_DOB).AsBoolean();
                dppSpouseDOB.Required = GetAttributeValue(REQUIRE_DOB).AsBoolean();

                string phoneLabel = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Value;
                phoneLabel         = phoneLabel.Trim().EndsWith("Phone") ? phoneLabel : phoneLabel + " Phone";
                pnCell.Label       = phoneLabel;
                pnSpouseCell.Label = "Spouse " + phoneLabel;

                if (CurrentPersonId.HasValue && _autoFill)
                {
                    var    personService = new PersonService(_rockContext);
                    Person person        = personService
                                           .Queryable("PhoneNumbers.NumberTypeValue").AsNoTracking()
                                           .FirstOrDefault(p => p.Id == CurrentPersonId.Value);

                    tbFirstName.Text    = CurrentPerson.FirstName;
                    tbLastName.Text     = CurrentPerson.LastName;
                    dppDOB.SelectedDate = CurrentPerson.BirthDate;
                    tbEmail.Text        = CurrentPerson.Email;


                    Guid homePhoneType = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid();
                    var  homePhone     = person.PhoneNumbers
                                         .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(homePhoneType));
                    if (homePhone != null)
                    {
                        pnHome.Text = homePhone.Number;
                    }

                    Guid cellPhoneType = Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid();
                    var  cellPhone     = person.PhoneNumbers
                                         .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(cellPhoneType));
                    if (cellPhone != null)
                    {
                        pnCell.Text   = cellPhone.Number;
                        cbSms.Checked = cellPhone.IsMessagingEnabled;
                    }

                    Location homeAddress = null;

                    var families = person.GetFamilies();

                    // If address can being entered, look for first family with a home location

                    foreach (var aFamily in families)
                    {
                        homeAddress = aFamily.GroupLocations
                                      .Where(l =>
                                             l.GroupLocationTypeValueId == _homeAddressType.Id)
                                      .FirstOrDefault()?.Location;
                    }

                    if (homeAddress != null)
                    {
                        acAddress.SetValues(homeAddress);
                    }

                    if (_showSpouse)
                    {
                        var spouse = person.GetSpouse(_rockContext);
                        if (spouse != null)
                        {
                            tbSpouseFirstName.Text    = spouse.FirstName;
                            tbSpouseLastName.Text     = spouse.LastName;
                            tbSpouseEmail.Text        = spouse.Email;
                            dppSpouseDOB.SelectedDate = spouse.BirthDate;

                            var spouseCellPhone = spouse.PhoneNumbers
                                                  .FirstOrDefault(n => n.NumberTypeValue.Guid.Equals(cellPhoneType));
                            if (spouseCellPhone != null)
                            {
                                pnSpouseCell.Text   = spouseCellPhone.Number;
                                cbSpouseSms.Checked = spouseCellPhone.IsMessagingEnabled;
                            }
                        }
                    }
                }

                if (GetAttributeValue("PreventOvercapacityRegistrations").AsBoolean())
                {
                    int openGroupSpots = 2;
                    int openRoleSpots  = 2;

                    // If the group has a GroupCapacity, check how far we are from hitting that.
                    if (_publishGroup.Group.GroupCapacity.HasValue)
                    {
                        openGroupSpots = _publishGroup.Group.GroupCapacity.Value - _publishGroup.Group.ActiveMembers().Count();
                    }

                    // When someone registers for a group on the front-end website, they automatically get added with the group's default
                    // GroupTypeRole. If that role exists and has a MaxCount, check how far we are from hitting that.
                    if (_defaultGroupRole != null && _defaultGroupRole.MaxCount.HasValue)
                    {
                        openRoleSpots = _defaultGroupRole.MaxCount.Value - _publishGroup.Group.Members
                                        .Where(m => m.GroupRoleId == _defaultGroupRole.Id && m.GroupMemberStatus == GroupMemberStatus.Active)
                                        .Count();
                    }

                    // Between the group's GroupCapacity and DefaultGroupRole.MaxCount, grab the one we're closest to hitting, and how close we are to
                    // hitting it.
                    int openSpots = Math.Min(openGroupSpots, openRoleSpots);

                    // If there's only one spot open, disable the spouse fields and display a warning message.
                    if (openSpots == 1)
                    {
                        tbSpouseFirstName.Enabled = false;
                        tbSpouseLastName.Enabled  = false;
                        pnSpouseCell.Enabled      = false;
                        cbSpouseSms.Enabled       = false;
                        tbSpouseEmail.Enabled     = false;
                        nbWarning.Text            = "This group is near its capacity. Only one individual can register.";
                        nbWarning.Visible         = true;
                    }

                    // If no spots are open, display a message that says so.
                    if (openSpots <= 0)
                    {
                        nbNotice.Text    = "This group is at or exceeds capacity.";
                        nbNotice.Visible = true;
                        pnlView.Visible  = false;
                    }
                }
            }
        }
예제 #25
0
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="location">The location.</param>
        private void ShowReadonlyDetails(Location location)
        {
            SetEditMode(false);

            hfLocationId.SetValue(location.Id);

            lReadOnlyTitle.Text = location.ToString(true).FormatAsHtmlTitle();

            hlInactive.Visible = !location.IsActive;
            if (location.LocationTypeValue != null)
            {
                hlType.Text    = location.LocationTypeValue.Value;
                hlType.Visible = true;
            }
            else
            {
                hlType.Visible = false;
            }

            string imgTag = GetImageTag(location.ImageId, 150, 150);

            if (location.ImageId.HasValue)
            {
                string imageUrl = ResolveRockUrl(String.Format("~/GetImage.ashx?id={0}", location.ImageId.Value));
                lImage.Text = string.Format("<a href='{0}'>{1}</a>", imageUrl, imgTag);
            }
            else
            {
                lImage.Text = imgTag;
            }

            DescriptionList descriptionList = new DescriptionList();

            if (location.ParentLocation != null)
            {
                descriptionList.Add("Parent Location", location.ParentLocation.Name);
            }

            if (location.LocationTypeValue != null)
            {
                descriptionList.Add("Location Type", location.LocationTypeValue.Value);
            }

            if (location.PrinterDevice != null)
            {
                descriptionList.Add("Printer", location.PrinterDevice.Name);
            }

            if (location.SoftRoomThreshold.HasValue)
            {
                descriptionList.Add("Threshold", location.SoftRoomThreshold.Value.ToString("N0"));
            }

            if (location.FirmRoomThreshold.HasValue)
            {
                descriptionList.Add("Threshold (Absolute)", location.FirmRoomThreshold.Value.ToString("N0"));
            }

            string fullAddress = location.GetFullStreetAddress().ConvertCrLfToHtmlBr();

            if (!string.IsNullOrWhiteSpace(fullAddress))
            {
                descriptionList.Add("Address", fullAddress);
            }

            lblMainDetails.Text = descriptionList.Html;

            location.LoadAttributes();
            Rock.Attribute.Helper.AddDisplayControls(location, phAttributes);

            phMaps.Controls.Clear();
            var mapStyleValue = DefinedValueCache.Get(GetAttributeValue(AttributeKey.MapStyle));
            var googleAPIKey  = GlobalAttributesCache.Get().GetValue("GoogleAPIKey");

            if (mapStyleValue == null)
            {
                mapStyleValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.MAP_STYLE_ROCK);
            }

            if (mapStyleValue != null && !string.IsNullOrWhiteSpace(googleAPIKey))
            {
                string mapStyle = mapStyleValue.GetAttributeValue("StaticMapStyle");

                if (!string.IsNullOrWhiteSpace(mapStyle))
                {
                    if (location.GeoPoint != null)
                    {
                        string markerPoints = string.Format("{0},{1}", location.GeoPoint.Latitude, location.GeoPoint.Longitude);
                        string mapLink      = System.Text.RegularExpressions.Regex.Replace(mapStyle, @"\{\s*MarkerPoints\s*\}", markerPoints);
                        mapLink  = System.Text.RegularExpressions.Regex.Replace(mapLink, @"\{\s*PolygonPoints\s*\}", string.Empty);
                        mapLink += "&sensor=false&size=350x200&zoom=13&format=png&key=" + googleAPIKey;
                        phMaps.Controls.Add(new LiteralControl(string.Format("<div class='group-location-map'><img class='img-thumbnail' src='{0}'/></div>", mapLink)));
                    }

                    if (location.GeoFence != null)
                    {
                        string polygonPoints = "enc:" + location.EncodeGooglePolygon();
                        string mapLink       = System.Text.RegularExpressions.Regex.Replace(mapStyle, @"\{\s*MarkerPoints\s*\}", string.Empty);
                        mapLink  = System.Text.RegularExpressions.Regex.Replace(mapLink, @"\{\s*PolygonPoints\s*\}", polygonPoints);
                        mapLink += "&sensor=false&size=350x200&format=png&key=" + googleAPIKey;
                        phMaps.Controls.Add(new LiteralControl(string.Format("<div class='group-location-map'><img class='img-thumbnail' src='{0}'/></div>", mapLink)));
                    }
                }
            }

            btnSecurity.Visible  = location.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
            btnSecurity.Title    = location.Name;
            btnSecurity.EntityId = location.Id;
        }
        /// <summary>
        /// Checks the settings.  If false is returned, it's expected that the caller will make
        /// the nbNotice visible to inform the user of the "settings" error.
        /// </summary>
        /// <returns>true if settings are valid; false otherwise</returns>
        private bool CheckSettings()
        {
            _rockContext = _rockContext ?? new RockContext();


            _autoFill = GetAttributeValue("AutoFillForm").AsBoolean();

            string registerButtonText = GetAttributeValue("RegisterButtonAltText");

            if (string.IsNullOrWhiteSpace(registerButtonText))
            {
                registerButtonText = "Register";
            }
            btnRegister.Text = registerButtonText;

            var publishGroupService = new PublishGroupService(_rockContext);

            if (_publishGroup == null)
            {
                var publishGroupGuid = PageParameter("PublishGroup").AsGuidOrNull();
                if (publishGroupGuid.HasValue)
                {
                    _publishGroup = publishGroupService.Get(publishGroupGuid.Value);
                }
                else
                {
                    var slug = PageParameter("PublishGroup").ToLower();
                    _publishGroup = publishGroupService.Queryable().Where(pg => pg.Slug == slug).FirstOrDefault();
                }
            }

            if (_publishGroup == null || _publishGroup.Group == null || _publishGroup.PublishGroupStatus != PublishGroupStatus.Approved)
            {
                nbNotice.Heading = "Unknown Group";
                nbNotice.Text    = "<p>This page requires a valid group identifying parameter and there was not one provided.</p>";
                nbNotice.Visible = true;
                return(false);
            }

            if (_publishGroup.RegistrationLink.IsNotNullOrWhiteSpace())
            {
                Response.Redirect(_publishGroup.RegistrationLink, false);
                Context.ApplicationInstance.CompleteRequest();
                return(false);
            }

            _showSpouse       = _publishGroup.AllowSpouseRegistration;
            _defaultGroupRole = _publishGroup.Group.GroupType.DefaultGroupRole;


            _dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
            if (_dvcConnectionStatus == null)
            {
                nbNotice.Heading = "Invalid Connection Status";
                nbNotice.Text    = "<p>The selected Connection Status setting does not exist.</p>";
                return(false);
            }

            _dvcRecordStatus = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());
            if (_dvcRecordStatus == null)
            {
                nbNotice.Heading = "Invalid Record Status";
                nbNotice.Text    = "<p>The selected Record Status setting does not exist.</p>";
                return(false);
            }

            _married         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid());
            _homeAddressType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
            _familyType      = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            _adultRole       = _familyType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

            if (_married == null || _homeAddressType == null || _familyType == null || _adultRole == null)
            {
                nbNotice.Heading = "Missing System Value";
                nbNotice.Text    = "<p>There is a missing or invalid system value. Check the settings for Marital Status of 'Married', Location Type of 'Home', Group Type of 'Family', and Family Group Role of 'Adult'.</p>";
                return(false);
            }

            return(true);
        }
예제 #27
0
        private void BuildForm(bool setValues)
        {
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("Action", _action);
            mergeFields.Add("Activity", _activity);
            mergeFields.Add("Workflow", _workflow);

            var form = _actionType.WorkflowForm;

            if (setValues)
            {
                lheadingText.Text = form.Header.ResolveMergeFields(mergeFields);
                lFootingText.Text = form.Footer.ResolveMergeFields(mergeFields);
            }

            if (_workflow != null && _workflow.CreatedDateTime.HasValue)
            {
                hlblDateAdded.Text = String.Format("Added: {0}", _workflow.CreatedDateTime.Value.ToShortDateString());
            }
            else
            {
                hlblDateAdded.Visible = false;
            }

            phAttributes.Controls.Clear();

            foreach (var formAttribute in form.FormAttributes.OrderBy(a => a.Order))
            {
                if (formAttribute.IsVisible)
                {
                    var attribute = AttributeCache.Get(formAttribute.AttributeId);

                    string value = attribute.DefaultValue;
                    if (_workflow != null && _workflow.AttributeValues.ContainsKey(attribute.Key) && _workflow.AttributeValues[attribute.Key] != null)
                    {
                        value = _workflow.AttributeValues[attribute.Key].Value;
                    }
                    // Now see if the key is in the activity attributes so we can get it's value
                    else if (_activity != null && _activity.AttributeValues.ContainsKey(attribute.Key) && _activity.AttributeValues[attribute.Key] != null)
                    {
                        value = _activity.AttributeValues[attribute.Key].Value;
                    }

                    if (!string.IsNullOrWhiteSpace(formAttribute.PreHtml))
                    {
                        phAttributes.Controls.Add(new LiteralControl(formAttribute.PreHtml.ResolveMergeFields(mergeFields)));
                    }

                    if (formAttribute.IsReadOnly)
                    {
                        var field = attribute.FieldType.Field;

                        string formattedValue = null;

                        // get formatted value
                        if (attribute.FieldType.Class == typeof(Rock.Field.Types.ImageFieldType).FullName)
                        {
                            formattedValue = attribute.FieldType.Field.FormatValueAsHtml(phAttributes, attribute.EntityTypeId, _activity.Id, value, attribute.QualifierValues, true);
                        }
                        else
                        {
                            formattedValue = field.FormatValueAsHtml(phAttributes, attribute.EntityTypeId, _activity.Id, value, attribute.QualifierValues);
                        }

                        if (formAttribute.HideLabel)
                        {
                            phAttributes.Controls.Add(new LiteralControl(formattedValue));
                        }
                        else
                        {
                            RockLiteral lAttribute = new RockLiteral();
                            lAttribute.ID    = "lAttribute_" + formAttribute.Id.ToString();
                            lAttribute.Label = attribute.Name;

                            if (field is Rock.Field.ILinkableFieldType)
                            {
                                string url = ((Rock.Field.ILinkableFieldType)field).UrlLink(value, attribute.QualifierValues);
                                url             = ResolveRockUrl("~").EnsureTrailingForwardslash() + url;
                                lAttribute.Text = string.Format("<a href='{0}' target='_blank'>{1}</a>", url, formattedValue);
                            }
                            else
                            {
                                lAttribute.Text = formattedValue;
                            }

                            phAttributes.Controls.Add(lAttribute);
                        }
                    }
                    else
                    {
                        attribute.AddControl(phAttributes.Controls, value, BlockValidationGroup, setValues, true, formAttribute.IsRequired,
                                             (formAttribute.HideLabel ? string.Empty : attribute.Name));
                    }

                    if (!string.IsNullOrWhiteSpace(formAttribute.PostHtml))
                    {
                        phAttributes.Controls.Add(new LiteralControl(formAttribute.PostHtml.ResolveMergeFields(mergeFields)));
                    }
                }
            }

            if (form.AllowNotes.HasValue && form.AllowNotes.Value && _workflow != null && _workflow.Id != 0)
            {
                ncWorkflowNotes.NoteOptions.EntityId = _workflow.Id;
                ShowNotes(true);
            }
            else
            {
                ShowNotes(false);
            }

            phActions.Controls.Clear();
            foreach (var action in form.Actions.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var details = action.Split(new char[] { '^' });
                if (details.Length > 0)
                {
                    // Get the button html
                    string buttonHtml = string.Empty;
                    if (details.Length > 1)
                    {
                        var definedValue = DefinedValueCache.Get(details[1].AsGuid());
                        if (definedValue != null)
                        {
                            buttonHtml = definedValue.GetAttributeValue("ButtonHTML");
                        }
                    }

                    if (string.IsNullOrWhiteSpace(buttonHtml))
                    {
                        buttonHtml = "<a href=\"{{ ButtonLink }}\" onclick=\"{{ ButtonClick }}\" class='btn btn-primary' data-loading-text='<i class=\"fa fa-refresh fa-spin\"></i> {{ ButtonText }}'>{{ ButtonText }}</a>";
                    }

                    var buttonMergeFields = new Dictionary <string, object>();
                    buttonMergeFields.Add("ButtonText", details[0].EncodeHtml());
                    buttonMergeFields.Add("ButtonClick",
                                          string.Format("if ( Page_ClientValidate('{0}') ) {{ $(this).button('loading'); return true; }} else {{ return false; }}",
                                                        BlockValidationGroup));
                    buttonMergeFields.Add("ButtonLink", Page.ClientScript.GetPostBackClientHyperlink(this, details[0]));

                    buttonHtml = buttonHtml.ResolveMergeFields(buttonMergeFields);

                    phActions.Controls.Add(new LiteralControl(buttonHtml));
                    phActions.Controls.Add(new LiteralControl(" "));
                }
            }
        }
예제 #28
0
        /// <summary>
        /// Saves the family and persons to the database
        /// </summary>
        /// <param name="kioskCampusId">The kiosk campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext)
        {
            SaveResult saveResult = new SaveResult();

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

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

            Group primaryFamily = null;

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

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

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

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

                person.SaveAttributeValues(rockContext);

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

                rockContext.SaveChanges();
            }

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

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

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

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

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

            primaryFamily.SaveAttributeValues(rockContext);

            var groupMemberService = new GroupMemberService(rockContext);

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

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

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

                    groupMemberService.Add(currentFamilyMember);

                    rockContext.SaveChanges();
                }
            }

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

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

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

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

                    rockContext.SaveChanges();

                    familyPersonState.GroupId = relatedFamily.Id;

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

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

                    groupMemberService.Add(familyMember);
                }

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

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

            return(saveResult);
        }
예제 #29
0
        /// <summary>
        /// Handles the Click event of the lbConfigure control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void lbConfigure_Click(object sender, EventArgs e)
        {
            pnlContentComponentConfig.Visible = true;
            mdContentComponentConfig.Show();

            Guid?          contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
            ContentChannel contentChannel     = null;

            if (contentChannelGuid.HasValue)
            {
                contentChannel = new ContentChannelService(new RockContext()).Get(contentChannelGuid.Value);
            }

            if (contentChannel == null)
            {
                contentChannel = new ContentChannel {
                    ContentChannelTypeId = this.ContentChannelTypeId
                };
            }

            tbComponentName.Text = contentChannel.Name;
            contentChannel.LoadAttributes();
            avcContentChannelAttributes.NumberOfColumns = 2;
            avcContentChannelAttributes.ValidationGroup = mdContentComponentConfig.ValidationGroup;
            avcContentChannelAttributes.AddEditControls(contentChannel);

            nbItemCacheDuration.Text = this.GetAttributeValue("ItemCacheDuration");

            DefinedTypeCache contentComponentTemplateType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CONTENT_COMPONENT_TEMPLATE.AsGuid());

            if (contentComponentTemplateType != null)
            {
                dvpContentComponentTemplate.DefinedTypeId = contentComponentTemplateType.Id;
            }

            DefinedValueCache contentComponentTemplate = null;
            var contentComponentTemplateValueGuid      = this.GetAttributeValue("ContentComponentTemplate").AsGuidOrNull();

            if (contentComponentTemplateValueGuid.HasValue)
            {
                contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueGuid.Value);
            }

            dvpContentComponentTemplate.SetValue(contentComponentTemplate);

            cbAllowMultipleContentItems.Checked = this.GetAttributeValue("AllowMultipleContentItems").AsBoolean();

            nbOutputCacheDuration.Text = this.GetAttributeValue("OutputCacheDuration");

            // Cache Tags
            cblCacheTags.DataSource = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CACHE_TAGS.AsGuid()).DefinedValues.Select(v => v.Value).ToList();
            cblCacheTags.DataBind();
            cblCacheTags.Visible = cblCacheTags.Items.Count > 0;
            string[] selectedCacheTags = this.GetAttributeValue("CacheTags").SplitDelimitedValues();
            foreach (ListItem cacheTag in cblCacheTags.Items)
            {
                cacheTag.Selected = selectedCacheTags.Contains(cacheTag.Value);
            }

            cePreHtml.Text  = this.BlockCache.PreHtml;
            cePostHtml.Text = this.BlockCache.PostHtml;

            hfDataFilterId.Value = GetAttributeValue("FilterId");

            int?filterId    = hfDataFilterId.Value.AsIntegerOrNull();
            var rockContext = new RockContext();

            var            filterService = new DataViewFilterService(rockContext);
            DataViewFilter filter        = null;

            if (filterId.HasValue)
            {
                filter = filterService.Get(filterId.Value);
            }

            if (filter == null || filter.ExpressionType == FilterExpressionType.Filter)
            {
                filter                = new DataViewFilter();
                filter.Guid           = new Guid();
                filter.ExpressionType = FilterExpressionType.GroupAll;
            }

            CreateFilterControl(this.ContentChannelTypeId, filter, true, rockContext);
        }
        /// <summary>
        /// Gets the person control for this field's <see cref="PersonFieldType"/>
        /// </summary>
        /// <param name="setValue">if set to <c>true</c> [set value].</param>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="familyMemberSelected">if set to <c>true</c> [family member selected].</param>
        /// <param name="validationGroup">The validation group.</param>
        /// <returns></returns>
        public Control GetPersonControl(bool setValue, object fieldValue, bool familyMemberSelected, string validationGroup)
        {
            RegistrationTemplateFormField field = this;
            Control personFieldControl          = null;

            switch (field.PersonFieldType)
            {
            case RegistrationPersonFieldType.FirstName:
                var tbFirstName = new RockTextBox
                {
                    ID              = "tbFirstName",
                    Label           = "First Name",
                    Required        = field.IsRequired,
                    CssClass        = "js-first-name",
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbFirstName;
                break;

            case RegistrationPersonFieldType.LastName:
                var tbLastName = new RockTextBox
                {
                    ID              = "tbLastName",
                    Label           = "Last Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbLastName;
                break;

            case RegistrationPersonFieldType.MiddleName:
                var tbMiddleName = new RockTextBox
                {
                    ID              = "tbMiddleName",
                    Label           = "Middle Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbMiddleName;
                break;

            case RegistrationPersonFieldType.Campus:
                var cpHomeCampus = new CampusPicker
                {
                    ID               = "cpHomeCampus",
                    Label            = "Campus",
                    Required         = field.IsRequired,
                    ValidationGroup  = validationGroup,
                    Campuses         = CampusCache.All(false),
                    SelectedCampusId = setValue && fieldValue != null?fieldValue.ToString().AsIntegerOrNull() : null
                };

                personFieldControl = cpHomeCampus;
                break;

            case RegistrationPersonFieldType.Address:
                var acAddress = new AddressControl
                {
                    ID    = "acAddress",
                    Label = "Address",
                    UseStateAbbreviation   = true,
                    UseCountryAbbreviation = false,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                if (setValue && fieldValue != null)
                {
                    acAddress.SetValues(fieldValue as Location);
                }

                personFieldControl = acAddress;
                break;

            case RegistrationPersonFieldType.Email:
                var tbEmail = new EmailBox
                {
                    ID              = "tbEmail",
                    Label           = "Email",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbEmail;
                break;

            case RegistrationPersonFieldType.Birthdate:
                var bpBirthday = new BirthdayPicker
                {
                    ID              = "bpBirthday",
                    Label           = "Birthday",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = bpBirthday;
                break;

            case RegistrationPersonFieldType.Grade:
                var gpGrade = new GradePicker
                {
                    ID                    = "gpGrade",
                    Label                 = "Grade",
                    Required              = field.IsRequired,
                    ValidationGroup       = validationGroup,
                    UseAbbreviation       = true,
                    UseGradeOffsetAsValue = true,
                    CssClass              = "input-width-md"
                };

                personFieldControl = gpGrade;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsIntegerOrNull();
                    gpGrade.SetValue(Person.GradeOffsetFromGraduationYear(value));
                }

                break;

            case RegistrationPersonFieldType.Gender:
                var ddlGender = new RockDropDownList
                {
                    ID              = "ddlGender",
                    Label           = "Gender",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                };

                ddlGender.BindToEnum <Gender>(true, new Gender[1] {
                    Gender.Unknown
                });

                personFieldControl = ddlGender;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().ConvertToEnumOrNull <Gender>() ?? Gender.Unknown;
                    ddlGender.SetValue(value.ConvertToInt());
                }

                break;

            case RegistrationPersonFieldType.MaritalStatus:
                var dvpMaritalStatus = new DefinedValuePicker
                {
                    ID              = "dvpMaritalStatus",
                    Label           = "Marital Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpMaritalStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid()).Id;
                personFieldControl             = dvpMaritalStatus;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpMaritalStatus.SetValue(value);
                }

                break;

            case RegistrationPersonFieldType.AnniversaryDate:
                var dppAnniversaryDate = new DatePartsPicker
                {
                    ID              = "dppAnniversaryDate",
                    Label           = "Anniversary Date",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = dppAnniversaryDate;
                break;

            case RegistrationPersonFieldType.MobilePhone:
                var dvMobilePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                if (dvMobilePhone == null)
                {
                    break;
                }

                var ppMobile = new PhoneNumberBox
                {
                    ID              = "ppMobile",
                    Label           = dvMobilePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var mobilePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppMobile.CountryCode = mobilePhoneNumber != null ? mobilePhoneNumber.CountryCode : string.Empty;
                ppMobile.Number      = mobilePhoneNumber != null?mobilePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppMobile;
                break;

            case RegistrationPersonFieldType.HomePhone:
                var dvHomePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                if (dvHomePhone == null)
                {
                    break;
                }

                var ppHome = new PhoneNumberBox
                {
                    ID              = "ppHome",
                    Label           = dvHomePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var homePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppHome.CountryCode = homePhoneNumber != null ? homePhoneNumber.CountryCode : string.Empty;
                ppHome.Number      = homePhoneNumber != null?homePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppHome;
                break;

            case RegistrationPersonFieldType.WorkPhone:
                var dvWorkPhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK);
                if (dvWorkPhone == null)
                {
                    break;
                }

                var ppWork = new PhoneNumberBox
                {
                    ID              = "ppWork",
                    Label           = dvWorkPhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var workPhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppWork.CountryCode = workPhoneNumber != null ? workPhoneNumber.CountryCode : string.Empty;
                ppWork.Number      = workPhoneNumber != null?workPhoneNumber.ToString() : string.Empty;

                personFieldControl = ppWork;
                break;

            case RegistrationPersonFieldType.ConnectionStatus:
                var dvpConnectionStatus = new DefinedValuePicker
                {
                    ID              = "dvpConnectionStatus",
                    Label           = "Connection Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)).Id;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpConnectionStatus.SetValue(value);
                }

                personFieldControl = dvpConnectionStatus;
                break;
            }

            return(personFieldControl);
        }