public void PersonWithNoEmailShouldNotMatch()
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var personWithNoEmails = personService.Get(PersonGuid.PersonWithNoEmailsGuid);

            /* personWithNoEmails doesn't have an email address, so that should not be a match
             */

            var emailSearch = Email.PrimaryEmail;

            var personMatchQuery = new PersonService.PersonMatchQuery(personWithNoEmails.FirstName, personWithNoEmails.LastName, emailSearch, null)
            {
                MobilePhone   = null,
                Gender        = personWithNoEmails.Gender,
                BirthDate     = personWithNoEmails.BirthDate,
                SuffixValueId = personWithNoEmails.SuffixValueId
            };

            bool updatePrimaryEmail     = false;
            var  foundPersons           = personService.FindPersons(personMatchQuery, updatePrimaryEmail);
            bool foundPersonWithNoEmail = foundPersons.Any(a => a.Guid == PersonGuid.PersonWithNoEmailsGuid);

            Assert.That.IsFalse(foundPersonWithNoEmail);
        }
Exemple #2
0
        /// <summary>
        /// Adds the spouse to the group.
        /// </summary>
        /// <param name="primaryPerson">The primary person.</param>
        /// <param name="personDetails">The person to be added.</param>
        /// <param name="group">The group to add the person to.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>
        /// The <see cref="GroupMember" /> instance that identifies the person in the group.
        /// </returns>
        private GroupMember AddSpouseToGroup(Person primaryPerson, PersonDetail personDetails, Group group, RockContext rockContext)
        {
            var personService   = new PersonService(rockContext);
            var primaryFamilyId = primaryPerson.GetFamily(rockContext).Id;

            // Attempt to find the existing spouse.
            var spouse = primaryPerson?.GetSpouse(rockContext);

            // If no spouse found, try to match to existing person.
            if (spouse == null)
            {
                var matchQuery = new PersonService.PersonMatchQuery(personDetails.FirstName, personDetails.LastName, personDetails.Email, personDetails.MobilePhone);
                spouse = personService.FindPerson(matchQuery, true);

                // If the matched person isn't in the same family then don't
                // use this record.
                if (spouse != null && spouse.GetFamily(rockContext).Id != primaryFamilyId)
                {
                    spouse = null;
                }
            }

            // If we have an existing spouse, update their personal information.
            if (spouse != null)
            {
                spouse.FirstName = personDetails.FirstName;
                spouse.LastName  = personDetails.LastName;

                if (personDetails.Email.IsNotNullOrWhiteSpace())
                {
                    spouse.Email = personDetails.Email;
                }

                if (PhoneNumber.CleanNumber(personDetails.MobilePhone).IsNotNullOrWhiteSpace())
                {
                    int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                    spouse.UpdatePhoneNumber(phoneNumberTypeId, "+1", personDetails.MobilePhone, personDetails.IsMessagingEnabled, null, rockContext);
                }
            }
            else
            {
                spouse = CreateNewPerson(personDetails.FirstName, personDetails.LastName, personDetails.Email, personDetails.MobilePhone, personDetails.IsMessagingEnabled);

                var groupRoleId = GroupTypeCache.GetFamilyGroupType().Roles
                                  .First(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())
                                  .Id;

                PersonService.AddPersonToFamily(spouse, true, primaryFamilyId, groupRoleId, rockContext);
            }

            // Update the marital status if they don't have one set.
            var marriedId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED).Id;

            primaryPerson.MaritalStatusValueId = primaryPerson.MaritalStatusValueId ?? marriedId;
            spouse.MaritalStatusValueId        = spouse.MaritalStatusValueId ?? marriedId;

            return(AddPersonToGroup(spouse, group, rockContext));
        }
        public void PersonWithPrimaryEmailShouldHandleAccountProtectionProfileCorrectly(string personGuid, string emailSearch, int accountProtectionProfile)
        {
            if (!Bus.RockMessageBus.IsRockStarted)
            {
                Bus.RockMessageBus.IsRockStarted = true;
                Bus.RockMessageBus.StartAsync().Wait();
            }

            var securitySettingService = new SecuritySettingsService();

            securitySettingService.SecuritySettings.AccountProtectionProfilesForDuplicateDetectionToIgnore = new List <AccountProtectionProfile>();
            securitySettingService.Save();

            // Give time for cache to update.
            Thread.Sleep(50);

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);
                var person        = personService.Get(personGuid.AsGuid());

                var personMatchQuery = new PersonService.PersonMatchQuery(person.FirstName, person.LastName, emailSearch, null)
                {
                    MobilePhone   = null,
                    Gender        = person.Gender,
                    BirthDate     = person.BirthDate,
                    SuffixValueId = person.SuffixValueId
                };

                var foundPerson = personService.FindPerson(personMatchQuery, false);
                Assert.That.IsNotNull(foundPerson);
            }

            securitySettingService.SecuritySettings.AccountProtectionProfilesForDuplicateDetectionToIgnore = new List <AccountProtectionProfile> {
                ( AccountProtectionProfile )accountProtectionProfile
            };
            securitySettingService.Save();

            // Give time for cache to update.
            Thread.Sleep(50);

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);
                var person        = personService.Get(personGuid.AsGuid());

                var personMatchQuery = new PersonService.PersonMatchQuery(person.FirstName, person.LastName, emailSearch, null)
                {
                    MobilePhone   = null,
                    Gender        = person.Gender,
                    BirthDate     = person.BirthDate,
                    SuffixValueId = person.SuffixValueId
                };

                var foundPerson = personService.FindPerson(personMatchQuery, false);
                Assert.That.IsNull(foundPerson);
            }
        }
Exemple #4
0
        /// <summary>
        /// Try to link the device to a person and return the primary alias ID if successful
        /// </summary>
        /// <returns>true if device successfully linked to a person</returns>
        protected int?LinkDeviceToPerson()
        {
            // At this point the user is not logged in and not found by looking up the device
            // So lets try to find the user using entered info and then link them to the device.
            PersonService personService     = new PersonService(new RockContext());
            int           mobilePhoneTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
            Person        person            = null;
            string        mobilePhoneNumber = string.Empty;

            // Looking for a match using the first name, last name, and mobile number or email address information
            if (tbFirstName.Visible && tbLastName.Visible && (tbMobilePhone.Visible || tbEmail.Visible))
            {
                mobilePhoneNumber = tbMobilePhone.Text.RemoveAllNonAlphaNumericCharacters();

                var personQuery = new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, mobilePhoneNumber);
                person = personService.FindPerson(personQuery, true);

                if (person.IsNotNull())
                {
                    RockPage.LinkPersonAliasToDevice(person.PrimaryAlias.Id, hfMacAddress.Value);
                    return(person.PrimaryAliasId);
                }
                else
                {
                    // If no known person record then create one since we have the minimum info required
                    person = CreateAndSaveNewPerson();

                    // Link new device to person alias
                    RockPage.LinkPersonAliasToDevice(person.PrimaryAlias.Id, hfMacAddress.Value);
                    return(person.PrimaryAlias.Id);
                }
            }

            // Just match off phone number if no other fields are showing.
            if (tbMobilePhone.Visible && !tbFirstName.Visible && !tbLastName.Visible && !tbEmail.Visible)
            {
                mobilePhoneNumber = tbMobilePhone.Text.RemoveAllNonAlphaNumericCharacters();
                person            = personService.Queryable().Where(p => p.PhoneNumbers.Where(n => n.NumberTypeValueId == mobilePhoneTypeId).FirstOrDefault().Number == mobilePhoneNumber).FirstOrDefault();
                if (person != null)
                {
                    RockPage.LinkPersonAliasToDevice(person.PrimaryAlias.Id, hfMacAddress.Value);
                    return(person.PrimaryAliasId);
                }
            }

            // Unable to find an existing user and we don't have the minimium info to create one.
            // We'll let Rock.Page and the cookie created in OnLoad() link the device to a user when they are logged in.
            // This will not work if this page is loaded into a Captive Network Assistant page as the cookie will not persist.
            return(null);
        }
Exemple #5
0
        /// <summary>
        /// Finds the person if they're logged in, or by email and name. If not exactly one found, creates a new person (and family)
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private Person FindPerson(RockContext rockContext)
        {
            Person person;
            var    personService = new PersonService(rockContext);

            if (CurrentPerson != null)
            {
                person = CurrentPerson;
            }
            else
            {
                string firstName = tbFirstName.Text;
                if (GetAttributeValue("EnableSmartNames").AsBooleanOrNull() ?? true)
                {
                    // If they tried to specify first name as multiple first names, like "Steve and Judy" or "Bob & Sally", just take the first first name
                    var parts = firstName.Split(new string[] { " and ", " & " }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length > 0)
                    {
                        firstName = parts[0];
                    }
                }

                // Same logic as TransactionEntry.ascx.cs
                var personQuery = new PersonService.PersonMatchQuery(firstName, tbLastName.Text, tbEmail.Text, string.Empty);
                person = personService.FindPerson(personQuery, true);
            }

            if (person == null)
            {
                var definedValue = DefinedValueCache.Get(GetAttributeValue("NewConnectionStatus").AsGuidOrNull() ?? Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_PARTICIPANT.AsGuid());
                person = new Person
                {
                    FirstName               = tbFirstName.Text,
                    LastName                = tbLastName.Text,
                    Email                   = tbEmail.Text,
                    EmailPreference         = Rock.Model.EmailPreference.EmailAllowed,
                    ConnectionStatusValueId = definedValue.Id,
                };

                person.IsSystem            = false;
                person.RecordTypeValueId   = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                person.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                PersonService.SaveNewPerson(person, rockContext, null, false);
            }

            return(person);
        }
Exemple #6
0
        /// <summary>
        /// Adds the primary person to the group. This is the person that entered
        /// all the information on the screen.
        /// </summary>
        /// <param name="personDetails">The person to be added.</param>
        /// <param name="group">The group to add the person to.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>The <see cref="GroupMember"/> instance that identifies the person in the group.</returns>
        private GroupMember AddPrimaryPersonToGroup(PersonDetail personDetails, Group group, RockContext rockContext)
        {
            var    personService = new PersonService(rockContext);
            Person person        = null;

            // Need to re-load the person since we are going to modify and we
            // need control of the context the person is in.
            if (AutofillForm && RequestContext.CurrentPerson != null)
            {
                person = personService.Get(RequestContext.CurrentPerson.Id);
            }

            if (person == null)
            {
                // If not logged in, try to match to an existing person.
                var matchQuery = new PersonService.PersonMatchQuery(personDetails.FirstName, personDetails.LastName, personDetails.Email, personDetails.MobilePhone);
                person = personService.FindPerson(matchQuery, true);
            }

            // If we have an existing person, update their personal information.
            if (person != null)
            {
                person.FirstName = personDetails.FirstName;
                person.LastName  = personDetails.LastName;

                if (personDetails.Email.IsNotNullOrWhiteSpace())
                {
                    person.Email = personDetails.Email;
                }

                if (PhoneNumber.CleanNumber(personDetails.MobilePhone).IsNotNullOrWhiteSpace())
                {
                    int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                    person.UpdatePhoneNumber(phoneNumberTypeId, "+1", personDetails.MobilePhone, personDetails.IsMessagingEnabled, null, rockContext);
                }
            }
            else
            {
                person = CreateNewPerson(personDetails.FirstName, personDetails.LastName, personDetails.Email, personDetails.MobilePhone, personDetails.IsMessagingEnabled);
                PersonService.SaveNewPerson(person, rockContext, null, false);
            }

            return(AddPersonToGroup(person, group, rockContext));
        }
Exemple #7
0
        /// <summary>
        /// Finds the best matching person for the given account data. This will
        /// handle
        /// </summary>
        /// <param name="account">The account.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private Person FindMatchingPerson(AccountData account, RockContext rockContext)
        {
            var    personService = new PersonService(rockContext);
            Gender?gender        = ( Gender )account.Gender;

            // For matching purposes, treat "unknown" as not set.
            if (gender == Gender.Unknown)
            {
                gender = null;
            }

            // Try to find a matching person based on name, email address,
            // mobile phone, and birthday. If these were not provided they
            // are not considered.
            var personQuery = new PersonService.PersonMatchQuery(account.FirstName, account.LastName, account.Email, account.MobilePhone, gender: gender, birthDate: account.BirthDate?.DateTime);

            return(personService.FindPerson(personQuery, true));
        }
        public void PersonWithPrimaryEmailShouldNotMatchIfAccountProtectionProfileDisabled()
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);
            var personWithPrimaryAndPreviousEmails = personService.Get(PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid);
            var emailSearch = Email.PrimaryEmail;



            var personMatchQuery = new PersonService.PersonMatchQuery(personWithPrimaryAndPreviousEmails.FirstName, personWithPrimaryAndPreviousEmails.LastName, emailSearch, null)
            {
                MobilePhone   = null,
                Gender        = personWithPrimaryAndPreviousEmails.Gender,
                BirthDate     = personWithPrimaryAndPreviousEmails.BirthDate,
                SuffixValueId = personWithPrimaryAndPreviousEmails.SuffixValueId
            };

            bool updatePrimaryEmail = false;
            var  foundPerson        = personService.FindPerson(personMatchQuery, updatePrimaryEmail);

            Assert.That.IsNotNull(foundPerson);
        }
        public void PersonWithPrimaryEmailButDifferentNameShouldNotMatch()
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);
            var personWithPrimaryEmailButDifferentName = personService.Get(PersonGuid.PersonWithPrimaryEmailButDifferentNameGuid);
            var personWithPrimaryEmail = personService.Get(PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid);

            var emailSearch = Email.PrimaryEmail;

            var personMatchQuery = new PersonService.PersonMatchQuery(personWithPrimaryEmail.FirstName, personWithPrimaryEmail.LastName, emailSearch, null)
            {
                MobilePhone   = null,
                Gender        = personWithPrimaryEmail.Gender,
                BirthDate     = personWithPrimaryEmail.BirthDate,
                SuffixValueId = personWithPrimaryEmail.SuffixValueId
            };

            bool updatePrimaryEmail = false;
            var  foundPersons       = personService.FindPersons(personMatchQuery, updatePrimaryEmail);
            bool foundPersonWithPrimaryEmailButDifferentName = foundPersons.Any(a => a.Guid == PersonGuid.PersonWithPrimaryEmailButDifferentNameGuid);

            Assert.That.IsFalse(foundPersonWithPrimaryEmailButDifferentName);
        }
        public void PersonWithPreviousEmailShouldMatch()
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);
            var personWithPrimaryAndPreviousEmails = personService.Get(PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid);
            var emailSearch = Email.PreviousEmail1;

            /* Person should only match if the PrimaryEmail or Previous is exactly the same as Email search.
             */

            var personMatchQuery = new PersonService.PersonMatchQuery(personWithPrimaryAndPreviousEmails.FirstName, personWithPrimaryAndPreviousEmails.LastName, emailSearch, null)
            {
                MobilePhone   = null,
                Gender        = personWithPrimaryAndPreviousEmails.Gender,
                BirthDate     = personWithPrimaryAndPreviousEmails.BirthDate,
                SuffixValueId = personWithPrimaryAndPreviousEmails.SuffixValueId
            };

            bool updatePrimaryEmail = false;
            var  foundPerson        = personService.FindPerson(personMatchQuery, updatePrimaryEmail);

            Assert.That.IsNotNull(foundPerson);
        }
Exemple #11
0
        /// <summary>
        /// Gets the requestor person either from the attribute or using person matching if allowed
        /// </summary>
        /// <returns></returns>
        private Person GetRequestor()
        {
            Person person;
            var    personAliasGuid = GetGuidFromTextOrAttribute(AttributeKey.Requestor);

            if (personAliasGuid.HasValue)
            {
                var personAliasService = new PersonAliasService(_rockContext);
                person = personAliasService.GetPerson(personAliasGuid.Value);

                if (person != null)
                {
                    return(person);
                }
            }

            if (GetBoolean(AttributeKey.IsPersonMatchingEnabled) != true)
            {
                return(null);
            }

            var email     = GetTextFromSelectedAttribute(AttributeKey.Email);
            var firstName = GetTextFromSelectedAttribute(AttributeKey.FirstName);
            var lastName  = GetTextFromSelectedAttribute(AttributeKey.LastName);

            // Email, first, and last name are all required to do person matching
            if (email.IsNullOrWhiteSpace() || firstName.IsNullOrWhiteSpace() || lastName.IsNullOrWhiteSpace())
            {
                return(null);
            }

            var personService = new PersonService(_rockContext);
            var query         = new PersonService.PersonMatchQuery(firstName, lastName, email, null);

            return(personService.FindPerson(query, false, true, false));
        }
Exemple #12
0
        protected void bbSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                RockContext   rockContext   = new RockContext();
                PersonService personService = new PersonService(rockContext);
                Person        person        = null;

                PersonService.PersonMatchQuery personQuery = new PersonService.PersonMatchQuery(dtbFirstName.Text, dtbLastName.Text, ebEmailAddress.Text, null);
                person = personService.FindPerson(personQuery, true);

                if (person == null)
                {
                    person                   = new Person();
                    person.FirstName         = dtbFirstName.Text;
                    person.LastName          = dtbLastName.Text;
                    person.IsEmailActive     = true;
                    person.Email             = ebEmailAddress.Text;
                    person.EmailPreference   = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                    var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(ATTRIBUTE_KEY__DEFAULT_CONNECTION_STATUS).AsGuid());
                    if (defaultConnectionStatus != null)
                    {
                        person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                    }

                    var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(ATTRIBUTE_KEY__DEFAULT_RECORD_STATUS).AsGuid());
                    if (defaultRecordStatus != null)
                    {
                        person.RecordStatusValueId = defaultRecordStatus.Id;
                    }

                    PersonService.SaveNewPerson(person, rockContext);
                }


                var spiritualGiftsTally = new Dictionary <string, int>();

                var spiritualGiftsQuestions = DefinedTypeCache.Get(GetAttributeValue(ATTRIBUTE_KEY__SHAPE_SPIRITUAL_GIFTS_QUESTIONS).AsGuid());
                if (spiritualGiftsQuestions != null)
                {
                    foreach (var item in rSpiritualGiftsQuestions.Items)
                    {
                        var repeaterItem = item as RepeaterItem;
                        if (repeaterItem != null)
                        {
                            var questionIdField = repeaterItem.FindControl("hfSpiritualGiftsQuestionId") as HiddenField;
                            if (questionIdField != null)
                            {
                                var questionId = questionIdField.Value.AsInteger();

                                var optionList = repeaterItem.FindControl("rrblSpiritualGiftsQuestion") as RockRadioButtonList;
                                if (optionList != null)
                                {
                                    var answer = optionList.SelectedValue.AsInteger();

                                    var question = DefinedValueCache.Get(questionId);
                                    if (question.DefinedType.Guid == spiritualGiftsQuestions.Guid)
                                    {
                                        var spiritualGiftGuid = question.GetAttributeValue(ATTRIBUTE_KEY__SPIRITUAL_GIFT);
                                        if (!string.IsNullOrWhiteSpace(spiritualGiftGuid))
                                        {
                                            var currentScore = spiritualGiftsTally.GetValueOrNull(spiritualGiftGuid) ?? 0;
                                            currentScore = currentScore + answer;
                                            spiritualGiftsTally.AddOrReplace(spiritualGiftGuid, currentScore);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                var sortedGifts = spiritualGiftsTally.OrderBy(g => g.Value).Reverse().Select(g => g.Key).ToArray();


                var abilitiesTally = new Dictionary <string, int>();

                var abilitiesQuestions = DefinedTypeCache.Get(GetAttributeValue(ATTRIBUTE_KEY__SHAPE_ABILITIES_QUESTIONS).AsGuid());
                if (abilitiesQuestions != null)
                {
                    foreach (var item in rAbilitiesQuestions.Items)
                    {
                        var repeaterItem = item as RepeaterItem;
                        if (repeaterItem != null)
                        {
                            var questionIdField = repeaterItem.FindControl("hfAbilitiesQuestionId") as HiddenField;
                            if (questionIdField != null)
                            {
                                var questionId = questionIdField.Value.AsInteger();

                                var optionList = repeaterItem.FindControl("rrblAbilitiesQuestion") as RockRadioButtonList;
                                if (optionList != null)
                                {
                                    var answer = optionList.SelectedValue.AsInteger();

                                    var question = DefinedValueCache.Get(questionId);
                                    if (question.DefinedType.Guid == abilitiesQuestions.Guid)
                                    {
                                        var spiritualGiftGuid = question.GetAttributeValue(ATTRIBUTE_KEY__ABILITY);
                                        if (!string.IsNullOrWhiteSpace(spiritualGiftGuid))
                                        {
                                            var currentScore = abilitiesTally.GetValueOrNull(spiritualGiftGuid) ?? 0;
                                            currentScore = currentScore + answer;
                                            abilitiesTally.AddOrReplace(spiritualGiftGuid, currentScore);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                var sortedAbilities = abilitiesTally.OrderBy(g => g.Value).Reverse().Select(g => g.Key).ToArray();


                var heartCategories = DefinedTypeCache.Get(GetAttributeValue(ATTRIBUTE_KEY__SHAPE_HEART_CATEGORIES).AsGuid());

                var hearts = rcblHeartOptions
                             .SelectedValues
                             .Where(v =>
                {
                    var guid = v.AsGuidOrNull();
                    if (guid.HasValue)
                    {
                        var definedValue = DefinedValueCache.Get(guid.Value);
                        if (definedValue != null)
                        {
                            return(definedValue.DefinedType.Guid == heartCategories.Guid);
                        }
                    }
                    return(false);
                });


                person.LoadAttributes();

                if (sortedGifts.Length > 0)
                {
                    person.SetAttributeValue("SpiritualGift1", sortedGifts[0]);
                }
                if (sortedGifts.Length > 1)
                {
                    person.SetAttributeValue("SpiritualGift2", sortedGifts[1]);
                }
                if (sortedGifts.Length > 2)
                {
                    person.SetAttributeValue("SpiritualGift3", sortedGifts[2]);
                }
                if (sortedGifts.Length > 3)
                {
                    person.SetAttributeValue("SpiritualGift4", sortedGifts[3]);
                }

                if (sortedAbilities.Length > 0)
                {
                    person.SetAttributeValue("Ability1", sortedAbilities[0]);
                }
                if (sortedAbilities.Length > 1)
                {
                    person.SetAttributeValue("Ability2", sortedAbilities[1]);
                }

                person.SetAttributeValue("HeartCategories", string.Join(",", hearts));
                person.SetAttributeValue("HeartCauses", rtbHeartPast.Text);
                person.SetAttributeValue("HeartPassion", rtbHeartFuture.Text);

                person.SetAttributeValue("SHAPEPeople", rtbExperiences_People.Text);
                person.SetAttributeValue("SHAPEPlaces", rtbExperiences_Places.Text);
                person.SetAttributeValue("SHAPEEvents", rtbExperiences_Events.Text);

                person.SetAttributeValue("SHAPEContactMe", rrblContactMe.Text);

                person.SaveAttributeValues(rockContext);


                Guid?workflowGuid = GetAttributeValue(ATTRIBUTE_KEY__WORKFLOW).AsGuidOrNull();
                if (workflowGuid.HasValue)
                {
                    var workflowAttributes = new Dictionary <string, string>();

                    if (sortedGifts.Length > 0)
                    {
                        workflowAttributes.Add("SpiritualGift1", sortedGifts[0]);
                    }
                    if (sortedGifts.Length > 1)
                    {
                        workflowAttributes.Add("SpiritualGift2", sortedGifts[1]);
                    }
                    if (sortedGifts.Length > 2)
                    {
                        workflowAttributes.Add("SpiritualGift3", sortedGifts[2]);
                    }
                    if (sortedGifts.Length > 3)
                    {
                        workflowAttributes.Add("SpiritualGift4", sortedGifts[3]);
                    }

                    if (sortedAbilities.Length > 0)
                    {
                        workflowAttributes.Add("Ability1", sortedAbilities[0]);
                    }
                    if (sortedAbilities.Length > 1)
                    {
                        workflowAttributes.Add("Ability2", sortedAbilities[1]);
                    }

                    workflowAttributes.Add("HeartCategories", string.Join(",", hearts));
                    workflowAttributes.Add("HeartCauses", rtbHeartPast.Text);
                    workflowAttributes.Add("HeartPassion", rtbHeartFuture.Text);

                    workflowAttributes.Add("SHAPEPeople", rtbExperiences_People.Text);
                    workflowAttributes.Add("SHAPEPlaces", rtbExperiences_Places.Text);
                    workflowAttributes.Add("SHAPEEvents", rtbExperiences_Events.Text);

                    workflowAttributes.Add("SHAPEContactMe", rrblContactMe.Text);

                    person.LaunchWorkflow(workflowGuid, "", workflowAttributes);
                }

                var _DISCLastSaveDate = person.GetAttributeValue("LastSaveDate");

                if (string.IsNullOrWhiteSpace(_DISCLastSaveDate))
                {
                    NavigateToLinkedPage(ATTRIBUTE_KEY__DISC_ASSESSMENT_PAGE);
                }
                else
                {
                    NavigateToLinkedPage(ATTRIBUTE_KEY__SHAPE_RESULTS_PAGE);
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Saves the family and persons to the database
        /// </summary>
        /// <param name="kioskCampusId">The kiosk campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext)
        {
            SaveResult saveResult = new SaveResult();

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

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

            Group primaryFamily = null;

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

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

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

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

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

                person.SaveAttributeValues(rockContext);

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

                rockContext.SaveChanges();
            }

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

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

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

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

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

            primaryFamily.SaveAttributeValues(rockContext);

            var groupMemberService = new GroupMemberService(rockContext);

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

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

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

                    groupMemberService.Add(currentFamilyMember);

                    rockContext.SaveChanges();
                }
            }

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

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

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

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

                    rockContext.SaveChanges();

                    familyPersonState.GroupId = relatedFamily.Id;

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

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

                    groupMemberService.Add(familyMember);
                }

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

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

            return(saveResult);
        }
Exemple #14
0
        /// <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;
                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 &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.FirstName.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)
                {
                    // 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();
                    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, _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
                    if (!IsSimple)
                    {
                        foreach (var aFamily in families)
                        {
                            homeLocation = aFamily.GroupLocations
                                           .Where(l =>
                                                  l.GroupLocationTypeValueId == _homeAddressType.Id &&
                                                  l.IsMappedLocation)
                                           .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 using a 'Full' view, save the phone numbers and address
                if (!IsSimple)
                {
                    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;
                                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);
                            }
                        }
                    }
                }

                // Save the person 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);

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

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

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

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
        /// <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 (_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");
            }
        }
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnConnect_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var opportunityService       = new ConnectionOpportunityService(rockContext);
                var connectionRequestService = new ConnectionRequestService(rockContext);
                var personService            = new PersonService(rockContext);

                Person person = null;

                string firstName         = tbFirstName.Text.Trim();
                string lastName          = tbLastName.Text.Trim();
                string email             = tbEmail.Text.Trim();
                string mobilePhoneNumber = pnMobile.Text.Trim();
                int?   campusId          = cpCampus.SelectedCampusId;

                // if a person guid was passed in from the query string use that
                if (RockPage.PageParameter("PersonGuid") != null && !string.IsNullOrWhiteSpace(RockPage.PageParameter("PersonGuid")))
                {
                    Guid?personGuid = RockPage.PageParameter("PersonGuid").AsGuidOrNull();

                    if (personGuid.HasValue)
                    {
                        person = personService.Get(personGuid.Value);
                    }
                }
                else if (CurrentPerson != null &&
                         CurrentPerson.LastName.Equals(lastName, StringComparison.OrdinalIgnoreCase) &&
                         (CurrentPerson.NickName.Equals(firstName, StringComparison.OrdinalIgnoreCase) || CurrentPerson.FirstName.Equals(firstName, StringComparison.OrdinalIgnoreCase)) &&
                         CurrentPerson.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                {
                    // If the name and email entered are the same as current person (wasn't changed), use the current person
                    person = personService.Get(CurrentPerson.Id);
                }
                else
                {
                    // Try to find matching person
                    var personQuery = new PersonService.PersonMatchQuery(firstName, lastName, email, mobilePhoneNumber);
                    person = personService.FindPerson(personQuery, true);
                }

                // If person was not found, create a new one
                if (person == null)
                {
                    // If a match was not found, create a new person
                    var dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
                    var dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());

                    person                   = new Person();
                    person.FirstName         = firstName;
                    person.LastName          = lastName;
                    person.IsEmailActive     = true;
                    person.Email             = email;
                    person.EmailPreference   = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    if (dvcConnectionStatus != null)
                    {
                        person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }
                    if (dvcRecordStatus != null)
                    {
                        person.RecordStatusValueId = dvcRecordStatus.Id;
                    }

                    PersonService.SaveNewPerson(person, rockContext, campusId, false);
                    person = personService.Get(person.Id);
                }

                // If there is a valid person with a primary alias, continue
                if (person != null && person.PrimaryAliasId.HasValue)
                {
                    if (pnHome.Visible)
                    {
                        SavePhone(pnHome, person, _homePhone.Guid);
                    }

                    if (pnMobile.Visible)
                    {
                        SavePhone(pnMobile, person, _cellPhone.Guid);
                    }

                    //
                    // Now that we have a person, we can create the Connection Request
                    // Walk each of the controls found and determine if we need to
                    // take any action for the value of that control.
                    //
                    var checkboxes = new List <Control>();
                    var types      = new Type[] { typeof(CheckBox), typeof(RadioButton) };
                    KFSFindControlsRecursive(phConnections, types, ref checkboxes);

                    foreach (CheckBox box in checkboxes)
                    {
                        if (box.Checked)
                        {
                            int opportunityId = box.ID.AsInteger();
                            var opportunity   = opportunityService
                                                .Queryable()
                                                .Where(o => o.Id == opportunityId)
                                                .FirstOrDefault();

                            int defaultStatusId = opportunity.ConnectionType.ConnectionStatuses
                                                  .Where(s => s.IsDefault)
                                                  .Select(s => s.Id)
                                                  .FirstOrDefault();

                            // If opportunity is valid and has a default status
                            if (opportunity != null && defaultStatusId > 0)
                            {
                                var personCampus = person.GetCampus();
                                if (personCampus != null)
                                {
                                    campusId = personCampus.Id;
                                }

                                var connectionRequest = new ConnectionRequest();
                                connectionRequest.PersonAliasId           = person.PrimaryAliasId.Value;
                                connectionRequest.Comments                = tbComments.Text.Trim();
                                connectionRequest.ConnectionOpportunityId = opportunity.Id;
                                connectionRequest.ConnectionState         = ConnectionState.Active;
                                connectionRequest.ConnectionStatusId      = defaultStatusId;
                                connectionRequest.CampusId                = campusId;
                                connectionRequest.ConnectorPersonAliasId  = opportunity.GetDefaultConnectorPersonAliasId(campusId);
                                if (campusId.HasValue &&
                                    opportunity != null &&
                                    opportunity.ConnectionOpportunityCampuses != null)
                                {
                                    var campus = opportunity.ConnectionOpportunityCampuses
                                                 .Where(c => c.CampusId == campusId.Value)
                                                 .FirstOrDefault();
                                    if (campus != null)
                                    {
                                        connectionRequest.ConnectorPersonAliasId = campus.DefaultConnectorPersonAliasId;
                                    }
                                }

                                if (!connectionRequest.IsValid)
                                {
                                    // Controls will show warnings
                                    return;
                                }

                                connectionRequestService.Add(connectionRequest);

                                rockContext.SaveChanges();

                                var mergeFields = new Dictionary <string, object>();
                                mergeFields.Add("CurrentPerson", CurrentPerson);
                                mergeFields.Add("Person", person);

                                lResponseMessage.Text    = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
                                lResponseMessage.Visible = true;

                                pnlSignup.Visible = false;
                            }
                        }
                    }
                }
            }
        }
Exemple #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 attribute = AttributeCache.Get(GetAttributeValue(action, PERSON_ATTRIBUTE_KEY).AsGuid(), rockContext);

            if (attribute != null)
            {
                var    mergeFields  = GetMergeFields(action);
                string firstName    = GetAttributeValue(action, FIRST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string lastName     = GetAttributeValue(action, LAST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string email        = GetAttributeValue(action, EMAIL_KEY, true).ResolveMergeFields(mergeFields);
                string mobileNumber = GetAttributeValue(action, MOBILE_NUMBER_KEY, true).ResolveMergeFields(mergeFields) ?? string.Empty;

                int?birthDay   = GetAttributeValue(action, BIRTH_DAY_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthMonth = GetAttributeValue(action, BIRTH_MONTH_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthYear  = GetAttributeValue(action, BIRTH_YEAR_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) && string.IsNullOrWhiteSpace(mobileNumber)))
                {
                    errorMessages.Add("First Name, Last Name, and either Email or Mobile Number are required. One or more of these values was not provided!");
                }
                else
                {
                    Person      person        = null;
                    PersonAlias personAlias   = null;
                    var         personService = new PersonService(rockContext);

                    var personQuery = new PersonService.PersonMatchQuery(firstName, lastName, email, mobileNumber, null, birthMonth, birthDay, birthYear);
                    person = personService.FindPerson(personQuery, true);

                    if (person.IsNotNull())
                    {
                        personAlias = person.PrimaryAlias;
                    }
                    else
                    {
                        // Add New Person
                        person                   = new Person();
                        person.FirstName         = firstName.FixCase();
                        person.LastName          = lastName.FixCase();
                        person.IsEmailActive     = true;
                        person.Email             = email;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        person.BirthMonth        = birthMonth;
                        person.BirthDay          = birthDay;
                        person.BirthYear         = birthYear;

                        UpdatePhoneNumber(person, mobileNumber);

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

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

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, DEFAULT_CAMPUS_KEY, true).AsGuid());
                        var familyGroup   = PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus.Id : ( int? )null), false);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            person      = familyGroup.Members.Select(m => m.Person).First();
                            personAlias = person.PrimaryAlias;
                        }
                    }



                    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
                    {
                        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));
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnConnect_Click(object sender, EventArgs e)
        {
            Page.Validate();

            if (!Page.IsValid)
            {
                // Exit and allow the validation controls to render the appropriate error messages.
                return;
            }

            using (var rockContext = new RockContext())
            {
                var opportunityService       = new ConnectionOpportunityService(rockContext);
                var connectionRequestService = new ConnectionRequestService(rockContext);
                var personService            = new PersonService(rockContext);

                // Get the opportunity and default status
                var opportunity = opportunityService
                                  .Queryable()
                                  .Where(o => o.Id == _opportunityId)
                                  .FirstOrDefault();

                int defaultStatusId = opportunity.ConnectionType.ConnectionStatuses
                                      .Where(s => s.IsDefault)
                                      .Select(s => s.Id)
                                      .FirstOrDefault();

                // If opportunity is valid and has a default status
                if (opportunity != null && defaultStatusId > 0)
                {
                    Person person = null;

                    string firstName         = tbFirstName.Text.Trim();
                    string lastName          = tbLastName.Text.Trim();
                    string email             = tbEmail.Text.Trim();
                    string mobilePhoneNumber = pnMobile.Text.Trim();
                    int?   campusId          = cpCampus.SelectedCampusId;

                    // if a person guid was passed in from the query string use that
                    if (RockPage.PageParameter(PageParameterKey.PersonGuid) != null && !string.IsNullOrWhiteSpace(RockPage.PageParameter(PageParameterKey.PersonGuid)))
                    {
                        Guid?personGuid = RockPage.PageParameter(PageParameterKey.PersonGuid).AsGuidOrNull();

                        if (personGuid.HasValue)
                        {
                            person = personService.Get(personGuid.Value);
                        }
                    }
                    else if (CurrentPerson != null &&
                             CurrentPerson.LastName.Equals(lastName, StringComparison.OrdinalIgnoreCase) &&
                             (CurrentPerson.NickName.Equals(firstName, StringComparison.OrdinalIgnoreCase) || CurrentPerson.FirstName.Equals(firstName, StringComparison.OrdinalIgnoreCase)) &&
                             CurrentPerson.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                    {
                        // If the name and email entered are the same as current person (wasn't changed), use the current person
                        person = personService.Get(CurrentPerson.Id);
                    }

                    else
                    {
                        // Try to find matching person
                        var personQuery = new PersonService.PersonMatchQuery(firstName, lastName, email, mobilePhoneNumber);
                        person = personService.FindPerson(personQuery, true);
                    }

                    // If person was not found, create a new one
                    if (person == null)
                    {
                        // If a match was not found, create a new person
                        var dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue(AttributeKey.ConnectionStatus).AsGuid());
                        var dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue(AttributeKey.RecordStatus).AsGuid());

                        person                   = new Person();
                        person.FirstName         = firstName;
                        person.LastName          = lastName;
                        person.IsEmailActive     = true;
                        person.Email             = email;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        if (dvcConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                        }
                        if (dvcRecordStatus != null)
                        {
                            person.RecordStatusValueId = dvcRecordStatus.Id;
                        }

                        PersonService.SaveNewPerson(person, rockContext, campusId, false);
                        person = personService.Get(person.Id);
                    }

                    // If there is a valid person with a primary alias, continue
                    if (person != null && person.PrimaryAliasId.HasValue)
                    {
                        if (pnHome.Visible)
                        {
                            SavePhone(pnHome, person, _homePhone.Guid);
                        }

                        if (pnMobile.Visible)
                        {
                            SavePhone(pnMobile, person, _cellPhone.Guid);
                        }

                        // Now that we have a person, we can create the connection request
                        var connectionRequest = new ConnectionRequest();
                        connectionRequest.PersonAliasId           = person.PrimaryAliasId.Value;
                        connectionRequest.Comments                = tbComments.Text.Trim();
                        connectionRequest.ConnectionOpportunityId = opportunity.Id;
                        connectionRequest.ConnectionState         = ConnectionState.Active;
                        connectionRequest.ConnectionStatusId      = defaultStatusId;
                        connectionRequest.CampusId                = campusId;
                        connectionRequest.ConnectorPersonAliasId  = opportunity.GetDefaultConnectorPersonAliasId(campusId);
                        if (campusId.HasValue &&
                            opportunity != null &&
                            opportunity.ConnectionOpportunityCampuses != null)
                        {
                            var campus = opportunity.ConnectionOpportunityCampuses
                                         .Where(c => c.CampusId == campusId.Value)
                                         .FirstOrDefault();
                            if (campus != null)
                            {
                                connectionRequest.ConnectorPersonAliasId = campus.DefaultConnectorPersonAliasId;
                            }
                        }

                        if (!connectionRequest.IsValid)
                        {
                            // Controls will show warnings
                            return;
                        }

                        // Save changes
                        avcAttributes.GetEditValues(connectionRequest);

                        rockContext.WrapTransaction(() =>
                        {
                            connectionRequestService.Add(connectionRequest);
                            rockContext.SaveChanges();
                            connectionRequest.SaveAttributeValues(rockContext);
                        });

                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("Opportunity", new ConnectionOpportunityService(rockContext).Get(_opportunityId));
                        mergeFields.Add("CurrentPerson", CurrentPerson);
                        mergeFields.Add("Person", person);

                        lResponseMessage.Text    = GetAttributeValue(AttributeKey.LavaTemplate).ResolveMergeFields(mergeFields);
                        lResponseMessage.Visible = true;

                        pnlSignup.Visible = false;
                    }
                }
            }
        }