Example #1
0
        /// <summary>
        /// Creates a new person.
        /// </summary>
        /// <returns>The <see cref="Person"/> object that was created.</returns>
        private Person CreateNewPerson(string firstName, string lastName, string email, string mobilePhone, bool enableMessaging)
        {
            Person person = new Person
            {
                FirstName               = firstName,
                LastName                = lastName,
                Email                   = email,
                IsEmailActive           = true,
                EmailPreference         = EmailPreference.EmailAllowed,
                RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id,
                ConnectionStatusValueId = ConnectionStatus?.Id,
                RecordStatusValueId     = RecordStatus?.Id
            };

            if (mobilePhone.IsNotNullOrWhiteSpace())
            {
                int phoneNumberTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
                var phoneNumber       = new PhoneNumber
                {
                    NumberTypeValueId  = phoneNumberTypeId,
                    Number             = PhoneNumber.CleanNumber(mobilePhone),
                    IsMessagingEnabled = enableMessaging
                };

                person.PhoneNumbers.Add(phoneNumber);
            }

            return(person);
        }
Example #2
0
        private void SavePhone(PhoneNumberBox phoneNumberBox, Person person, Guid phoneTypeGuid, List <string> changes)
        {
            var numberType = DefinedValueCache.Read(phoneTypeGuid);

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

                if (newPhoneNumber != string.Empty)
                {
                    if (phone == null)
                    {
                        phone = new PhoneNumber();
                        person.PhoneNumbers.Add(phone);
                        phone.NumberTypeValueId = numberType.Id;
                    }
                    else
                    {
                        oldPhoneNumber = phone.NumberFormattedWithCountryCode;
                    }
                    phone.CountryCode = PhoneNumber.CleanNumber(phoneNumberBox.CountryCode);
                    phone.Number      = newPhoneNumber;

                    History.EvaluateChange(
                        changes,
                        string.Format("{0} Phone", numberType.Value),
                        oldPhoneNumber,
                        phone.NumberFormattedWithCountryCode);
                }
            }
        }
        private void SavePhone(PhoneNumberBox phoneNumberBox, Person person, Guid phoneTypeGuid)
        {
            var numberType = DefinedValueCache.Get(phoneTypeGuid);

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

                if (newPhoneNumber != string.Empty)
                {
                    if (phone == null)
                    {
                        phone = new PhoneNumber();
                        person.PhoneNumbers.Add(phone);
                        phone.NumberTypeValueId = numberType.Id;
                    }
                    else
                    {
                        oldPhoneNumber = phone.NumberFormattedWithCountryCode;
                    }
                    phone.CountryCode = PhoneNumber.CleanNumber(phoneNumberBox.CountryCode);
                    phone.Number      = newPhoneNumber;
                }
            }
        }
Example #4
0
        void UpdatePhoneNumber(Person person, string mobileNumber)
        {
            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(mobileNumber)))
            {
                var phoneNumberType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                if (phoneNumberType == null)
                {
                    return;
                }

                var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id);
                string oldPhoneNumber = string.Empty;
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = phoneNumberType.Id
                    };
                    person.PhoneNumbers.Add(phoneNumber);
                }
                else
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                // TODO handle country code here
                phoneNumber.Number = PhoneNumber.CleanNumber(mobileNumber);
            }
        }
Example #5
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));
        }
Example #6
0
        private static Person GetOrCreateNamelessPerson(string email, string phone, PersonService personService)
        {
            var namelessPersonRecordValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_NAMELESS).Id;
            int numberTypeMobileValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
            var number = PhoneNumber.CleanNumber(phone);

            var personQryOptions = new Rock.Model.PersonService.PersonQueryOptions
            {
                IncludeNameless = true
            };

            var qry = personService.Queryable(personQryOptions).Where(p => p.RecordTypeValueId == namelessPersonRecordValueId);

            if (email.IsNotNullOrWhiteSpace())
            {
                qry = qry.Where(p => p.Email == email);
            }

            if (phone.IsNotNullOrWhiteSpace())
            {
                qry = qry.Where(p => p.PhoneNumbers.Select(pn => pn.Number == number).Any());
            }

            var people = qry.ToList();

            if (people.Count() == 1)
            {
                return(people.First());
            }

            //Didn't get just one person... Time to make a new one!
            var person = new Person();

            person.RecordTypeValueId = namelessPersonRecordValueId;

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

            if (phone.IsNotNullOrWhiteSpace())
            {
                var smsPhoneNumber = new PhoneNumber();
                smsPhoneNumber.NumberTypeValueId  = numberTypeMobileValueId;
                smsPhoneNumber.Number             = number;
                smsPhoneNumber.IsMessagingEnabled = true;
                person.PhoneNumbers.Add(smsPhoneNumber);
            }

            personService.Add(person);
            (( RockContext )personService.Context).SaveChanges();

            person = personService.Get(person.Id);
            return(person);
        }
Example #7
0
        /// <summary>
        /// Sets the phone number.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="pnbNumber">The PNB number.</param>
        /// <param name="cbSms">The cb SMS.</param>
        /// <param name="phoneTypeGuid">The phone type unique identifier.</param>
        /// <param name="changes">The changes.</param>
        private void SetPhoneNumber(RockContext rockContext, Person person, PhoneNumberBox pnbNumber, RockCheckBox cbSms, Guid phoneTypeGuid, List <string> changes)
        {
            var phoneType = DefinedValueCache.Read(phoneTypeGuid);

            if (phoneType != null)
            {
                var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneType.Id);
                string oldPhoneNumber = string.Empty;
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = phoneType.Id
                    };
                }
                else
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbNumber.CountryCode);
                phoneNumber.Number      = PhoneNumber.CleanNumber(pnbNumber.Number);

                if (string.IsNullOrWhiteSpace(phoneNumber.Number))
                {
                    if (phoneNumber.Id > 0)
                    {
                        new PhoneNumberService(rockContext).Delete(phoneNumber);
                        person.PhoneNumbers.Remove(phoneNumber);
                    }
                }
                else
                {
                    if (phoneNumber.Id <= 0)
                    {
                        person.PhoneNumbers.Add(phoneNumber);
                    }
                    if (cbSms != null && cbSms.Checked)
                    {
                        phoneNumber.IsMessagingEnabled = true;
                        person.PhoneNumbers
                        .Where(n => n.NumberTypeValueId != phoneType.Id)
                        .ToList()
                        .ForEach(n => n.IsMessagingEnabled = false);
                    }
                }

                History.EvaluateChange(changes,
                                       string.Format("{0} Phone", phoneType.Value),
                                       oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode);
            }
        }
Example #8
0
        protected void pnbPhone_TextChanged(object sender, EventArgs e)
        {
            var tbPhone     = ( PhoneNumberBox )sender;
            var hfPhoneType = ( HiddenField )tbPhone.Parent.FindControl("hfPhoneType");
            var mobileDV    = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());

            if (hfPhoneType.Value.AsInteger() == mobileDV.Id)
            {
                var    number = PhoneNumber.CleanNumber(tbPhone.Text);
                string validationInformation = ValidateMobilePhoneNumber(number);

                if (validationInformation.IsNotNullOrWhiteSpace())
                {
                    maNotice.Show(validationInformation, ModalAlertType.Warning);
                }
            }
        }
Example #9
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));
        }
Example #10
0
        /// <summary>
        /// Updates the person record with the provided account information.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="account">The account.</param>
        /// <param name="rockContext">The rock context.</param>
        private void UpdatePerson(Person person, AccountData account, RockContext rockContext)
        {
            person.FirstName = account.FirstName;
            person.LastName  = account.LastName;

            if (account.Gender != ( int )Gender.Unknown)
            {
                person.Gender = ( Gender )account.Gender;
            }

            if (account.BirthDate.HasValue)
            {
                person.BirthMonth = account.BirthDate.Value.Month;
                person.BirthDay   = account.BirthDate.Value.Day;
                if (account.BirthDate.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = account.BirthDate.Value.Year;
                }
            }

            if (account.Campus.HasValue)
            {
                var campusId = CampusCache.Get(account.Campus.Value)?.Id;

                if (campusId.HasValue)
                {
                    person.GetFamily(rockContext).CampusId = campusId;
                }
            }

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

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(account.MobilePhone)))
            {
                int phoneNumberTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id;

                person.UpdatePhoneNumber(phoneNumberTypeId, string.Empty, account.MobilePhone, null, null, rockContext);
            }
        }
Example #11
0
        private List <Person> GetByMatch(string firstName, string lastName, DateTime?birthday, string cellPhone, string email)
        {
            cellPhone = PhoneNumber.CleanNumber(cellPhone) ?? string.Empty;
            email     = email ?? string.Empty;

            //Stop if first name or last name is blank or if all three of email, phone and birthday are blank
            if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName) ||
                !(!string.IsNullOrWhiteSpace(cellPhone) || !string.IsNullOrWhiteSpace(email) || birthday != null)
                )
            {
                return(null);
            }

            //Search for person who matches first and last name and one of email, phone number, or birthday
            return(new PersonService(_rockContext).Queryable()
                   .Where(p => p.LastName == lastName &&
                          (p.FirstName == firstName || p.NickName == firstName) &&
                          ((p.Email == email && p.Email != string.Empty) ||
                           (p.PhoneNumbers.Where(pn => pn.Number == cellPhone).Any() && cellPhone != string.Empty) ||
                           (birthday != null && p.BirthDate == birthday)))
                   .ToList());
        }
Example #12
0
        /// <summary>
        /// Set the phone number of the person.
        /// </summary>
        /// <param name="person">The Person whose phone number is to be changed.</param>
        /// <param name="phoneType">The phone number type of the phone number.</param>
        /// <param name="pnBox">The value of the phone number.</param>
        /// <param name="changes">The list of changes to later be recorded to history.</param>
        protected void SetPhone(Person person, DefinedValueCache phoneType, Rock.Web.UI.Controls.PhoneNumberBox pnBox, List <string> changes)
        {
            var    phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneType.Id);
            string oldPhone    = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id
                };
                person.PhoneNumbers.Add(phoneNumber);
            }
            else
            {
                oldPhone = phoneNumber.NumberFormattedWithCountryCode;
            }

            phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnBox.CountryCode);
            phoneNumber.Number      = PhoneNumber.CleanNumber(pnBox.Number);

            History.EvaluateChange(changes, string.Format("{0} Phone", phoneType.Value), oldPhone, phoneNumber.NumberFormattedWithCountryCode);
        }
Example #13
0
        private void UpdatePersonPhoneNumber(Person person, string phone)
        {
            if (phone.IsNullOrWhiteSpace())
            {
                return;
            }

            var countryCode            = string.Empty;
            var extension              = string.Empty;
            var extStartIndex          = phone.IndexOf(";ext=");
            var defaultPhoneNumberType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);

            if (extStartIndex > 0)
            {
                extension = phone.Substring(extStartIndex);
                phone     = phone.Replace(extension, string.Empty);
                extension = PhoneNumber.CleanNumber(extension.Replace(";ext=", ""));
            }

            phone = phone.Trim();

            if (phone.StartsWith("+"))
            {
                var phoneParts = phone.Split(new char[] { ' ', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
                countryCode = PhoneNumber.CleanNumber(phoneParts[0]);
                phone       = string.Join("", phoneParts, 1, phoneParts.Length - 1);
            }

            person.PhoneNumbers.Add(new PhoneNumber
            {
                Number            = PhoneNumber.CleanNumber(phone),
                Extension         = extension,
                CountryCode       = countryCode,
                NumberTypeValueId = defaultPhoneNumberType.Id
            });
        }
Example #14
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            // Get the From value. Can be in the form of Text, Phone Number, Person or Defined type
            string fromValue = string.Empty;
            int?   fromId    = null;

            fromValue = GetAttributeValue(action, "From", true);


            if (!string.IsNullOrWhiteSpace(fromValue))
            {
                Guid?fromGuid = fromValue.AsGuidOrNull();

                DefinedTypeCache smsPhoneNumbers = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.COMMUNICATION_SMS_FROM);

                // If fromGuid is null but fromValue is not, then this is a phone number (match it up with the value from the DefinedType)
                if (fromGuid == null)
                {
                    try
                    {
                        fromValue = PhoneNumber.CleanNumber(fromValue);
                        fromGuid  = smsPhoneNumbers.DefinedValues.Where(dv => dv.Value.Right(10) == fromValue.Right(10)).Select(dv => dv.Guid).FirstOrDefault();
                        if (fromGuid == Guid.Empty)
                        {
                            action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
                        }
                    }
                    catch (Exception e)
                    {
                        action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
                    }
                }

                // At this point, fromGuid should either be a Person or a DefinedValue

                if (fromGuid.HasValue)
                {
                    fromId = smsPhoneNumbers.DefinedValues.Where(dv => dv.Guid == fromGuid || dv.GetAttributeValue("ResponseRecipient") == fromGuid.ToString()).Select(dv => dv.Id).FirstOrDefault();
                }
            }

            else
            {
                // The From number is required and was not entered
                action.AddLogEntry("Invalid sending number: Person or valid SMS phone number not found", true);
            }

            // Get the recipients, Can be in the form of Text, Phone Number, Person, Group or Security role
            var    recipients = new List <RockSMSMessageRecipient>();
            string toValue    = GetAttributeValue(action, "To");
            Guid   guid       = toValue.AsGuid();

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

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

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);

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

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

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

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

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                        var recipient            = new RockSMSMessageRecipient(person, phoneNumber.ToSmsNumber(), recipientMergeFields);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add(recipient.PersonMergeFieldKey, person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(RockSMSMessageRecipient.CreateAnonymous(toValue.ResolveMergeFields(mergeFields), mergeFields));
                }
            }

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

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

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

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

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

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

            return(true);
        }
Example #15
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole        = null;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else if (ddlFamilyRole.SelectedValue == "C")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            var  phoneNumberTypeIds = new List <int>();
            bool smsSelected        = false;

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (hfPhoneType != null &&
                    pnbPhone != null &&
                    cbSms != null &&
                    cbUnlisted != null)
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                        string oldPhoneNumber = string.Empty;
                        if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text);
            changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked);
            changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
            changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());


            var birthday = bpBirthday.SelectedDate;

            if (birthday.HasValue)
            {
                changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                }
                else
                {
                    int?year = null;
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", year);
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

            if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                (currentLocation != null && currentLocation.Street1 != location.Street1))
            {
                LocationService locationService = new LocationService(rockContext);
                locationService.Add(location);
                rockContext.SaveChanges();

                var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                GroupLocation groupLocation = new GroupLocation
                {
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId,
                    GroupId    = family.Id,
                    LocationId = location.Id,
                    GroupLocationTypeValueId = homeLocationType.Id,
                    IsMailingLocation        = true,
                    IsMappedLocation         = true
                };

                var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                foreach (var homelocation in homelocations)
                {
                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "GroupLocationTypeValue",
                        previousLocationType,
                        true,
                        homelocation.Location.ToString());

                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "IsMailingLocation",
                        false,
                        true,
                        homelocation.Location.ToString());
                }
            }

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool          autoApply = CanAutoApply(person);
            List <string> errors;

            if (changeRequest.ChangeRecords.Any() ||
                (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
            {
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
Example #16
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>();

            // get person
            int?personId = null;

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

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

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

            // determine the phone type to edit
            DefinedValueCache phoneType = null;
            var phoneTypeAttributeValue = action.GetWorkflowAttributeValue(GetAttributeValue(action, "PhoneTypeAttribute").AsGuid());

            if (phoneTypeAttributeValue != null)
            {
                phoneType = DefinedValueCache.Get(phoneTypeAttributeValue.AsGuid());
            }
            if (phoneType == null)
            {
                phoneType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneType").AsGuid());
            }
            if (phoneType == null)
            {
                errorMessages.Add("The phone type to be updated was not selected.");
                return(false);
            }

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean(true);

            // get the new phone number value
            string phoneNumberValue     = GetAttributeValue(action, "PhoneNumber");
            Guid?  phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull();

            if (phoneNumberValueGuid.HasValue)
            {
                phoneNumberValue = action.GetWorkflowAttributeValue(phoneNumberValueGuid.Value);
            }
            else
            {
                phoneNumberValue = phoneNumberValue.ResolveMergeFields(GetMergeFields(action));
            }
            phoneNumberValue = PhoneNumber.CleanNumber(phoneNumberValue);

            // gets value indicating if phone number is unlisted
            string unlistedValue     = GetAttributeValue(action, "Unlisted");
            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();

            if (unlistedValueGuid.HasValue)
            {
                unlistedValue = action.GetWorkflowAttributeValue(unlistedValueGuid.Value);
            }
            else
            {
                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?unlisted = unlistedValue.AsBooleanOrNull();

            // gets value indicating if messaging should be enabled for phone number
            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();

            if (smsEnabledValueGuid.HasValue)
            {
                smsEnabledValue = action.GetWorkflowAttributeValue(smsEnabledValueGuid.Value);
            }
            else
            {
                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?smsEnabled = smsEnabledValue.AsBooleanOrNull();

            bool updated            = false;
            bool newPhoneNumber     = false;
            var  phoneNumberService = new PhoneNumberService(rockContext);
            var  phoneNumber        = phoneNumberService.Queryable()
                                      .Where(n =>
                                             n.PersonId == personId.Value &&
                                             n.NumberTypeValueId == phoneType.Id)
                                      .FirstOrDefault();
            string oldValue = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id, PersonId = personId.Value
                };
                newPhoneNumber = true;
                updated        = true;
            }
            else
            {
                oldValue = phoneNumber.NumberFormattedWithCountryCode;
            }

            if (!string.IsNullOrWhiteSpace(phoneNumberValue) || !ignoreBlanks)
            {
                updated            = updated || phoneNumber.Number != phoneNumberValue;
                phoneNumber.Number = phoneNumberValue;
            }
            if (unlisted.HasValue)
            {
                updated = updated || phoneNumber.IsUnlisted != unlisted.Value;
                phoneNumber.IsUnlisted = unlisted.Value;
            }
            if (smsEnabled.HasValue)
            {
                updated = updated || phoneNumber.IsMessagingEnabled != smsEnabled.Value;
                phoneNumber.IsMessagingEnabled = smsEnabled.Value;
            }

            if (updated)
            {
                if (oldValue != phoneNumber.NumberFormattedWithCountryCode)
                {
                    var changes = new History.HistoryChangeList();
                    changes.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Phone").SetSourceOfChange($"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow");
                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId.Value, changes, false);
                }

                if (phoneNumber.Number.IsNullOrWhiteSpace())
                {
                    if (!newPhoneNumber)
                    {
                        phoneNumberService.Delete(phoneNumber);
                    }
                }
                else
                {
                    if (newPhoneNumber)
                    {
                        phoneNumberService.Add(phoneNumber);
                    }
                }

                rockContext.SaveChanges();

                if (action.Activity != null && action.Activity.Workflow != null)
                {
                    var workflowType = action.Activity.Workflow.WorkflowTypeCache;
                    if (workflowType != null && workflowType.LoggingLevel == WorkflowLoggingLevel.Action)
                    {
                        var person = new PersonService(rockContext).Get(personId.Value);
                        action.AddLogEntry(string.Format("Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode));
                    }
                }
            }

            return(true);
        }
Example #17
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsUserAuthorized(Rock.Security.Authorization.EDIT))
            {
                var rockContext = new RockContext();

                rockContext.WrapTransaction(() =>
                {
                    var personService = new PersonService(rockContext);

                    var changes = new List <string>();

                    var person = personService.Get(Person.Id);

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

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

                    int?newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId));
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text);
                    person.FirstName = tbFirstName.Text;

                    string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text;
                    History.EvaluateChange(changes, "Nick Name", person.NickName, nickName);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text);
                    person.MiddleName = tbMiddleName.Text;

                    History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text);
                    person.LastName = tbLastName.Text;

                    int?newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while (birthday.Value.CompareTo(today) > 0)
                        {
                            birthday = birthday.Value.AddYears(-100);
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);

                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

                    History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                    person.GraduationYear = graduationYear;

                    History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate);
                    person.AnniversaryDate = dpAnniversaryDate.SelectedDate;

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

                    int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId));
                    person.ConnectionStatusValueId = newConnectionStatusId;

                    var phoneNumberTypeIds = new List <int>();

                    bool smsSelected = false;

                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox cbUnlisted     = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                            {
                                int phoneNumberTypeId;
                                if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                {
                                    var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                    phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                    // Only allow one number to have SMS selected
                                    if (smsSelected)
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

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

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

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

                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text.Trim();

                    History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked);
                    person.IsEmailActive = cbIsEmailActive.Checked;

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

                    int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId();
                    if (person.GivingGroupId != newGivingGroupId)
                    {
                        string oldGivingGroupName = string.Empty;
                        if (Person.GivingGroup != null)
                        {
                            oldGivingGroupName = GetFamilyNameWithFirstNames(Person.GivingGroup.Name, Person.GivingGroup.Members);
                        }

                        string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty;
                        History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName);
                    }

                    person.GivingGroupId = newGivingGroupId;

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

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

                    History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                    person.RecordStatusReasonValueId = newRecordStatusReasonId;
                    History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text);
                    person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim();

                    // Save any Removed/Added Previous Names
                    var personPreviousNameService = new PersonPreviousNameService(rockContext);
                    var databasePreviousNames     = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList();
                    foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid)))
                    {
                        personPreviousNameService.Delete(deletedPreviousName);

                        History.EvaluateChange(
                            changes,
                            "Previous Name",
                            deletedPreviousName.ToString(),
                            string.Empty);
                    }

                    foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid)))
                    {
                        addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value;
                        personPreviousNameService.Add(addedPreviousName);

                        History.EvaluateChange(
                            changes,
                            "Previous Name",
                            string.Empty,
                            addedPreviousName.ToString());
                    }

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

                            if (orphanedPhotoId.HasValue)
                            {
                                BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                                if (binaryFile != null)
                                {
                                    string errorMessage;
                                    if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                    {
                                        binaryFileService.Delete(binaryFile);
                                        rockContext.SaveChanges();
                                    }
                                }
                            }

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if (imgPhoto.CropBinaryFileId.HasValue)
                            {
                                if (imgPhoto.CropBinaryFileId != person.PhotoId)
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                    var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                                    if (binaryFile != null && binaryFile.IsTemporary)
                                    {
                                        string errorMessage;
                                        if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                        {
                                            binaryFileService.Delete(binaryFile);
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
                    }
                });
            }
        }
Example #18
0
        public object UpdateProfile(MobilePerson profile)
        {
            var user = UserLoginService.GetCurrentUser(false);

            if (user == null)
            {
                return(ActionStatusCode(System.Net.HttpStatusCode.Unauthorized));
            }

            var personId    = user.PersonId.Value;
            var rockContext = new Data.RockContext();

            var personService      = new PersonService(rockContext);
            var phoneNumberService = new PhoneNumberService(rockContext);
            var person             = personService.Get(personId);

            person.NickName  = person.NickName == person.FirstName ? profile.FirstName : person.NickName;
            person.FirstName = profile.FirstName;
            person.LastName  = profile.LastName;

            var gender = (Model.Gender)profile.Gender;

            if (GenderVisibility != VisibilityTriState.Hidden)
            {
                person.Gender = gender;
            }

            if (GetAttributeValue(AttributeKeys.BirthDateShow).AsBoolean())
            {
                person.SetBirthDate(profile.BirthDate?.Date);
            }

            if (GetAttributeValue(AttributeKeys.CampusShow).AsBoolean())
            {
                person.PrimaryFamily.CampusId = profile.CampusGuid.HasValue ? CampusCache.Get(profile.CampusGuid.Value)?.Id : null;
            }

            if (GetAttributeValue(AttributeKeys.EmailShow).AsBoolean())
            {
                person.Email = profile.Email;
            }

            if (GetAttributeValue(AttributeKeys.MobilePhoneShow).AsBoolean())
            {
                int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = phoneNumberTypeId
                    };
                    person.PhoneNumbers.Add(phoneNumber);
                }

                // TODO: What to do with country code?
                phoneNumber.CountryCode = PhoneNumber.CleanNumber("+1");
                phoneNumber.Number      = PhoneNumber.CleanNumber(profile.MobilePhone);

                if (string.IsNullOrWhiteSpace(phoneNumber.Number))
                {
                    person.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }
            }

            if (GetAttributeValue(AttributeKeys.AddressShow).AsBoolean())
            {
                var addressTypeGuid = SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();

                var groupLocationService = new GroupLocationService(rockContext);

                var dvHomeAddressType = DefinedValueCache.Get(addressTypeGuid);
                var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == person.PrimaryFamily.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();

                if (familyAddress != null && string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                {
                    // delete the current address
                    groupLocationService.Delete(familyAddress);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                    {
                        if (familyAddress == null)
                        {
                            familyAddress = new GroupLocation();
                            groupLocationService.Add(familyAddress);
                            familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                            familyAddress.GroupId           = person.PrimaryFamily.Id;
                            familyAddress.IsMailingLocation = true;
                            familyAddress.IsMappedLocation  = true;
                        }
                        else if (familyAddress.Location.Street1 != profile.HomeAddress.Street1)
                        {
                            // user clicked move so create a previous address
                            var previousAddress = new GroupLocation();
                            groupLocationService.Add(previousAddress);

                            var previousAddressValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                            if (previousAddressValue != null)
                            {
                                previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                previousAddress.GroupId = person.PrimaryFamily.Id;

                                Location previousAddressLocation = new Location
                                {
                                    Street1    = familyAddress.Location.Street1,
                                    Street2    = familyAddress.Location.Street2,
                                    City       = familyAddress.Location.City,
                                    State      = familyAddress.Location.State,
                                    PostalCode = familyAddress.Location.PostalCode,
                                    Country    = familyAddress.Location.Country
                                };

                                previousAddress.Location = previousAddressLocation;
                            }
                        }

                        // TODO: ???
                        // familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                        // familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;
                        familyAddress.Location = new LocationService(rockContext).Get(
                            profile.HomeAddress.Street1,
                            string.Empty,
                            profile.HomeAddress.City,
                            profile.HomeAddress.State,
                            profile.HomeAddress.PostalCode,
                            profile.HomeAddress.Country,
                            person.PrimaryFamily,
                            true);

                        // since there can only be one mapped location, set the other locations to not mapped
                        if (familyAddress.IsMappedLocation)
                        {
                            var groupLocations = groupLocationService.Queryable()
                                                 .Where(l => l.GroupId == person.PrimaryFamily.Id && l.Id != familyAddress.Id).ToList();

                            foreach (var groupLocation in groupLocations)
                            {
                                groupLocation.IsMappedLocation = false;
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }

            rockContext.SaveChanges();

            var mobilePerson = MobileHelper.GetMobilePerson(person, MobileHelper.GetCurrentApplicationSite());

            mobilePerson.AuthToken = MobileHelper.GetAuthenticationToken(user.UserName);

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

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    int?orphanedPhotoId = null;
                    if (person.PhotoId != imgPhoto.BinaryFileId)
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId  = imgPhoto.BinaryFileId;

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

                    int?newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId));
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text);
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text);
                    person.LastName = tbLastName.Text;

                    int?newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while (birthday.Value.CompareTo(today) > 0)
                        {
                            birthday = birthday.Value.AddYears(-100);
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List <int>();

                    bool smsSelected = false;

                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox cbUnlisted     = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                            {
                                int phoneNumberTypeId;
                                if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                {
                                    var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                    phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                    // Only allow one number to have SMS selected
                                    if (smsSelected)
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

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

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

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

                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text.Trim();

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

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

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

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if (imgPhoto.CropBinaryFileId.HasValue)
                            {
                                if (imgPhoto.CropBinaryFileId != person.PhotoId)
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                    var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                                    if (binaryFile != null && binaryFile.IsTemporary)
                                    {
                                        string errorMessage;
                                        if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                        {
                                            binaryFileService.Delete(binaryFile);
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        if (pnlAddress.Visible)
                        {
                            Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if (familyGroupTypeGuid.HasValue)
                            {
                                var familyGroup = new GroupService(rockContext).Queryable()
                                                  .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                         f.Members.Any(m => m.PersonId == person.Id))
                                                  .FirstOrDefault();
                                if (familyGroup != null)
                                {
                                    Guid?addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if (addressTypeGuid.HasValue)
                                    {
                                        var groupLocationService = new GroupLocationService(rockContext);

                                        var dvHomeAddressType = DefinedValueCache.Read(addressTypeGuid.Value);
                                        var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();
                                        if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            // delete the current address
                                            History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                            groupLocationService.Delete(familyAddress);
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                            {
                                                if (familyAddress == null)
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add(familyAddress);
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId           = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation  = true;
                                                }
                                                else if (hfStreet1.Value != string.Empty)
                                                {
                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                                                    if (previousAddressValue != null)
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation   = new Location();
                                                        previousAddressLocation.Street1    = hfStreet1.Value;
                                                        previousAddressLocation.Street2    = hfStreet2.Value;
                                                        previousAddressLocation.City       = hfCity.Value;
                                                        previousAddressLocation.State      = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country    = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues(updatedHomeAddress);

                                                History.EvaluateChange(changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof(Person),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes);
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            });
        }
Example #20
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid());

            Person person = new Person();

            person.FirstName         = tbFirstName.Text;
            person.LastName          = tbLastName.Text;
            person.Email             = tbEmail.Text;
            person.IsEmailActive     = true;
            person.EmailPreference   = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if (dvcRecordStatus != null)
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch (ddlGender.SelectedValue)
            {
            case "M":
                person.Gender = Gender.Male;
                break;

            case "F":
                person.Gender = Gender.Female;
                break;

            default:
                person.Gender = Gender.Unknown;
                break;
            }

            var birthday = bdaypBirthDay.SelectedDate;

            if (birthday.HasValue)
            {
                person.BirthMonth = birthday.Value.Month;
                person.BirthDay   = birthday.Value.Day;
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = birthday.Value.Year;
                }
            }

            bool smsSelected = false;

            foreach (RepeaterItem item in rPhoneNumbers.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var phoneNumber = new PhoneNumber {
                            NumberTypeValueId = phoneNumberTypeId
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                        phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                        // Only allow one number to have SMS selected
                        if (smsSelected)
                        {
                            phoneNumber.IsMessagingEnabled = false;
                        }
                        else
                        {
                            phoneNumber.IsMessagingEnabled = cbSms.Checked;
                            smsSelected = cbSms.Checked;
                        }

                        phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    }
                }
            }

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

            // save address
            if (pnlAddress.Visible)
            {
                if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode))
                {
                    Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid();
                    if (locationTypeGuid != Guid.Empty)
                    {
                        Guid                 familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService         groupService         = new GroupService(rockContext);
                        GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                        var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add(groupLocation);

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

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(locationTypeGuid).Id;
                        groupLocation.IsMailingLocation        = true;
                        groupLocation.IsMappedLocation         = true;

                        rockContext.SaveChanges();
                    }
                }
            }

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

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    int?orphanedPhotoId = null;
                    if (person.PhotoId != imgPhoto.BinaryFileId)
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId  = imgPhoto.BinaryFileId;

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

                    int?newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId));
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text);
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text);
                    person.LastName = tbLastName.Text;

                    int?newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while (birthday.Value.CompareTo(today) > 0)
                        {
                            birthday = birthday.Value.AddYears(-100);
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List <int>();

                    bool smsSelected = false;

                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox cbUnlisted     = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                            {
                                int phoneNumberTypeId;
                                if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                {
                                    var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                    phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                    // Only allow one number to have SMS selected
                                    if (smsSelected)
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

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

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

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

                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text.Trim();

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

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

                        NavigateToParentPage();
                    }
                }
            });
        }
Example #22
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.Read(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

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


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

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

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

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

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

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

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

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


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

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

                                History.EvaluateChange(
                                    changes,
                                    string.Format("{0} Phone", numberType.Value),
                                    oldPhoneNumber,
                                    phoneModel.NumberFormattedWithCountryCode);
                            }
                        }
                    }

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

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }

            return(true);
        }
Example #23
0
        protected void SavePersonDetails(Person person, RockContext rockContext)
        {
            person.NickName = tbNickName.Text;

            person.TitleValueId  = dvpTitle.SelectedValue.AsIntegerOrNull();
            person.FirstName     = tbFirstName.Text;
            person.MiddleName    = tbMiddleName.Text;
            person.LastName      = tbLastName.Text;
            person.SuffixValueId = dvpSuffix.SelectedValue.AsIntegerOrNull();

            person.Gender = rblGender.SelectedValueAsEnum <Gender>();
            person.SetBirthDate(bpBirthday.SelectedDate);
            person.GradeOffset = gpGrade.SelectedValue.AsIntegerOrNull();

            person.LoadAttributes();
            person.SetAttributeValue("Allergy", rtbAllergy.Text);

            var newPhoneNumbers = new List <PhoneNumber>();

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;

                if (hfPhoneType != null && pnbPhone != null && cbUnlisted != null)
                {
                    var countryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    var phoneNumber = PhoneNumber.CleanNumber(pnbPhone.Number);
                    if (!string.IsNullOrWhiteSpace(countryCode) && !string.IsNullOrWhiteSpace(phoneNumber))
                    {
                        newPhoneNumbers.Add(new PhoneNumber
                        {
                            NumberTypeValueId  = hfPhoneType.ValueAsInt(),
                            Number             = phoneNumber,
                            CountryCode        = countryCode,
                            IsMessagingEnabled = false,
                            IsUnlisted         = cbUnlisted.Checked
                        });
                    }
                }
            }

            foreach (PhoneNumber oldPhoneNumber in person.PhoneNumbers.ToList())
            {
                var matchingPhoneNumber = newPhoneNumbers.FirstOrDefault(pn => pn.NumberTypeValueId == oldPhoneNumber.NumberTypeValueId);
                if (matchingPhoneNumber != null)
                {
                    oldPhoneNumber.CountryCode = matchingPhoneNumber.CountryCode;
                    oldPhoneNumber.Number      = matchingPhoneNumber.Number;
                    oldPhoneNumber.IsUnlisted  = matchingPhoneNumber.IsUnlisted;
                    newPhoneNumbers.Remove(matchingPhoneNumber);
                }
                else
                {
                    person.PhoneNumbers.Remove(oldPhoneNumber);
                    new PhoneNumberService(rockContext).Delete(oldPhoneNumber);
                }
            }

            foreach (PhoneNumber newPhoneNumber in newPhoneNumbers)
            {
                person.PhoneNumbers.Add(newPhoneNumber);
            }
        }
Example #24
0
        /// <summary>
        /// Gets the name of the OAuth user.
        /// </summary>
        /// <param name="oauthUser">The OAuth user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetOAuthUser(Guid connectionStatusGuid, OAuthUser oauthUser, string accessToken = "")
        {
            // accessToken is required
            if (accessToken.IsNullOrWhiteSpace())
            {
                return(null);
            }

            string username = string.Empty;
            string oauthId  = oauthUser.id;

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

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

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

                    Person person = null;

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

                    var personRecordTypeId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPendingId    = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;
                    var personConnectionStatusId = DefinedValueCache.Get(connectionStatusGuid).Id;
                    var phoneNumberTypeId        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Id;

                    rockContext.WrapTransaction(() =>
                    {
                        if (person == null)
                        {
                            person                         = new Person();
                            person.IsSystem                = false;
                            person.RecordTypeValueId       = personRecordTypeId;
                            person.RecordStatusValueId     = personStatusPendingId;
                            person.ConnectionStatusValueId = personConnectionStatusId;
                            person.FirstName               = firstName;
                            person.LastName                = lastName;
                            person.Email                   = email;
                            person.IsEmailActive           = true;
                            person.EmailPreference         = EmailPreference.EmailAllowed;
                            person.Gender                  = Gender.Unknown;

                            var phoneNumber = new PhoneNumber {
                                NumberTypeValueId = phoneNumberTypeId
                            };
                            person.PhoneNumbers.Add(phoneNumber);
                            phoneNumber.Number = PhoneNumber.CleanNumber(oauthUser.contact.phone.AsNumeric());

                            var birthday = oauthUser.contact.birthday.Split((new char[] { '-' }));
                            if (birthday.Length == 3)
                            {
                                person.BirthYear  = birthday[0].AsIntegerOrNull();
                                person.BirthMonth = birthday[1].AsIntegerOrNull();
                                person.BirthDay   = birthday[2].AsIntegerOrNull();
                            }

                            var gender = oauthUser.contact.gender_id.AsIntegerOrNull();
                            if (gender != null)
                            {
                                person.Gender = ( Gender )gender;
                            }

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

                            // save address
                            var personLocation = new LocationService(rockContext)
                                                 .Get(oauthUser.address.street1, oauthUser.address.street2,
                                                      oauthUser.address.city, oauthUser.address.state, oauthUser.address.zip, oauthUser.address.country);
                            if (personLocation != null)
                            {
                                Guid locationTypeGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();
                                if (locationTypeGuid != Guid.Empty)
                                {
                                    Guid familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                                    GroupService groupService = new GroupService(rockContext);
                                    GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                                    var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                                    var groupLocation     = new GroupLocation();
                                    groupLocation.GroupId = family.Id;
                                    groupLocationService.Add(groupLocation);

                                    groupLocation.Location = personLocation;

                                    groupLocation.GroupLocationTypeValueId = DefinedValueCache.Get(locationTypeGuid).Id;
                                    groupLocation.IsMailingLocation        = true;
                                    groupLocation.IsMappedLocation         = true;

                                    rockContext.SaveChanges();
                                }
                            }
                        }

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

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

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

                return(username);
            }
        }
Example #25
0
        public static IEnumerable <Person> GetByMatch(this PersonService personService, String firstName, String lastName, DateTime?birthDate, String email = null, String phone = null, String street1 = null, String postalCode = null)
        {
            using (Rock.Data.RockContext context = new Rock.Data.RockContext())
            {
                //FirstName LastName and (DOB or email or phone or street address) are required. If not return an empty list.
                if (firstName.IsNullOrWhiteSpace() || lastName.IsNullOrWhiteSpace() ||
                    (!birthDate.HasValue &&
                     string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     string.IsNullOrWhiteSpace(street1)))
                {
                    return(new List <Person>());
                }

                LocationService       locationService       = new LocationService(context);
                AttributeValueService attributeValueService = new AttributeValueService(context);
                List <AttributeValue> attributeValues       = attributeValueService.GetByAttributeId(AttributeCache.Get(GOES_BY_ATTRIBUTE.AsGuid()).Id).ToList();
                var diminutiveName = DefinedTypeCache.Get(DIMINUTIVE_NAMES.AsGuid());

                firstName = firstName ?? string.Empty;
                lastName  = lastName ?? string.Empty;
                email     = email.ToLower() ?? string.Empty;
                phone     = PhoneNumber.CleanNumber(phone ?? string.Empty);
                List <Person> matchingPersons = new List <Person>();

                // Do a quick check to see if we get a match right up front
                List <Person> persons = new List <Person>();
                if (birthDate.HasValue || !string.IsNullOrEmpty(email))
                {
                    var fastQuery = personService.Queryable(false, false).Where(p => (p.FirstName.ToLower() == firstName.ToLower() || p.NickName.ToLower() == firstName.ToLower()) && p.LastName == lastName);
                    if (birthDate.HasValue)
                    {
                        fastQuery = fastQuery.Where(p => p.BirthDate == birthDate);
                    }
                    if (!String.IsNullOrEmpty(email))
                    {
                        fastQuery = fastQuery.Where(p => p.Email.ToLower() == email);
                    }
                    persons = fastQuery.ToList();

                    // We have an exact match.  Just be done.
                    if (persons.Count == 1)
                    {
                        return(persons);
                    }
                }

                // Go ahead and do this more leniant search if we get this far
                persons = personService.Queryable(false, false)
                          .Where(p =>
                                 p.LastName == lastName &&
                                 (!birthDate.HasValue || p.BirthDate == null || (birthDate.HasValue && p.BirthDate.Value == birthDate.Value)))
                          .ToList();

                // Set a placeholder for the location so we only geocode it 1 time
                Location location = null;

                foreach (Person person in persons)
                {
                    // Check to see if the phone exists anywhere in the family
                    Boolean phoneExists = !string.IsNullOrWhiteSpace(phone) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.PhoneNumbers.Where(pn => pn.Number == phone).Any()).Any()).Any();

                    // Check to see if the email exists anywhere in the family
                    Boolean emailExists = !string.IsNullOrWhiteSpace(email) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.Email == email).Any()).Any();

                    Boolean addressMatches = false;
                    // Check the address if it was passed
                    if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                    {
                        if (person.GetHomeLocation() != null)
                        {
                            if (person.GetHomeLocation().Street1 == street1)
                            {
                                addressMatches = true;
                            }
                            // If it doesn't match, we need to geocode it and check it again
                            if (location == null && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                            {
                                location            = new Location();
                                location.Street1    = street1;
                                location.PostalCode = postalCode;
                                locationService.Verify(location, true);
                            }
                            if (location != null && !addressMatches && person.GetHomeLocation().Street1 == location.Street1)
                            {
                                addressMatches = true;
                            }
                        }
                    }

                    // At least phone, email, or address have to match
                    if (phoneExists || emailExists || addressMatches)
                    {
                        matchingPersons.Add(person);
                    }
                }

                List <Person> firstNameMatchingPersons = new List <Person>();

                // Now narrow down the list by looking for the first name (or diminutive name)
                foreach (Person matchingPerson in matchingPersons)
                {
                    if (firstName != null && ((matchingPerson.FirstName != null && matchingPerson.FirstName.ToLower() != firstName.ToLower()) || (matchingPerson.NickName != null && matchingPerson.NickName.ToLower() != firstName.ToLower())))
                    {
                        foreach (DefinedValueCache dv in diminutiveName.DefinedValues)
                        {
                            AttributeValue av       = attributeValues.Where(av2 => av2.EntityId == dv.Id).FirstOrDefault();
                            List <string>  nameList = new List <string>();
                            nameList = av.Value.Split('|').ToList();
                            nameList.Add(dv.Value);
                            if (nameList.Contains(firstName.ToLower()) &&
                                (nameList.Contains(matchingPerson.FirstName.ToLower()) || nameList.Contains(matchingPerson.NickName.ToLower())))
                            {
                                firstNameMatchingPersons.Add(matchingPerson);
                                break;
                            }
                        }
                    }
                    else
                    {
                        firstNameMatchingPersons.Add(matchingPerson);
                    }
                }

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

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

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

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

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

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

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

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

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

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

            // Record Status Reason
            int?newRecordStatusReasonId = null;

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

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

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

            queryParams.Add("BusinessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
Example #27
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <param name="account">The account details.</param>
        /// <param name="rockContext">The database context to operate in.</param>
        /// <returns></returns>
        private Person CreatePerson(AccountData account, RockContext rockContext)
        {
            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue(AttributeKeys.ConnectionStatus).AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue(AttributeKeys.RecordStatus).AsGuid());

            Person person = new Person
            {
                FirstName         = account.FirstName,
                LastName          = account.LastName,
                Email             = account.Email,
                Gender            = ( Gender )account.Gender,
                IsEmailActive     = true,
                EmailPreference   = EmailPreference.EmailAllowed,
                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;
            }

            if (account.BirthDate.HasValue)
            {
                person.BirthMonth = account.BirthDate.Value.Month;
                person.BirthDay   = account.BirthDate.Value.Day;
                if (account.BirthDate.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = account.BirthDate.Value.Year;
                }
            }

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(account.MobilePhone)))
            {
                int phoneNumberTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id;

                var phoneNumber = new PhoneNumber
                {
                    NumberTypeValueId = phoneNumberTypeId,
                    Number            = PhoneNumber.CleanNumber(account.MobilePhone)
                };
                person.PhoneNumbers.Add(phoneNumber);

                // TODO: Do we need to deal with this? -dsh
                //phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );

                // TODO: How to deal with SMS enabled option? -dsh
                phoneNumber.IsMessagingEnabled = false;
            }

            int?campusId = null;

            if (account.Campus.HasValue)
            {
                campusId = CampusCache.Get(account.Campus.Value)?.Id;
            }

            PersonService.SaveNewPerson(person, rockContext, campusId, false);

            return(person);
        }
Example #28
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var service = new PersonService();
            var person  = service.Get(Person.Id);

            person.PhotoId              = imgPhoto.BinaryFileId;
            person.TitleValueId         = ddlTitle.SelectedValueAsInt();
            person.GivenName            = tbGivenName.Text;
            person.NickName             = tbNickName.Text;
            person.MiddleName           = tbMiddleName.Text;
            person.LastName             = tbLastName.Text;
            person.SuffixValueId        = ddlSuffix.SelectedValueAsInt();
            person.BirthDate            = dpBirthDate.SelectedDate;
            person.AnniversaryDate      = dpAnniversaryDate.SelectedDate;
            person.Gender               = rblGender.SelectedValue.ConvertToEnum <Gender>();
            person.MaritalStatusValueId = rblMaritalStatus.SelectedValueAsInt();
            person.PersonStatusValueId  = rblStatus.SelectedValueAsInt();

            var phoneNumberTypeIds = new List <int>();

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                TextBox     tbPhone     = item.FindControl("tbPhone") as TextBox;
                CheckBox    cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;

                if (hfPhoneType != null &&
                    tbPhone != null &&
                    cbUnlisted != null)
                {
                    if (!string.IsNullOrWhiteSpace(tbPhone.Text))
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                            if (phoneNumber == null)
                            {
                                phoneNumber = new PhoneNumber {
                                    NumberTypeValueId = phoneNumberTypeId
                                };
                                person.PhoneNumbers.Add(phoneNumber);
                            }

                            phoneNumber.Number     = PhoneNumber.CleanNumber(tbPhone.Text);
                            phoneNumber.IsUnlisted = cbUnlisted.Checked;

                            phoneNumberTypeIds.Add(phoneNumberTypeId);
                        }
                    }
                }
            }

            // Remove any blank numbers
            person.PhoneNumbers
            .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
            .ToList()
            .ForEach(n => person.PhoneNumbers.Remove(n));

            person.Email = tbEmail.Text;

            person.RecordStatusValueId       = ddlRecordStatus.SelectedValueAsInt();
            person.RecordStatusReasonValueId = ddlReason.SelectedValueAsInt();

            service.Save(person, CurrentPersonId);

            Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
        }
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved          = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments    = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();
            bool isPersonMatchingEnabled = GetAttributeValue("EnablePersonMatching").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();

            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int?     categoryId          = bddlCategory.SelectedValueAsInt();
            Guid     defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                category   = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService(rockContext).Get(categoryId.Value);
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category   = category;

            var personContext = this.ContextEntity <Person>();

            if (personContext == null)
            {
                Person person = null;
                if (isPersonMatchingEnabled)
                {
                    var personService = new PersonService(new RockContext());
                    person = personService.FindPerson(new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, pnbPhone.Number), false, true, false);

                    if (person == null && (!string.IsNullOrWhiteSpace(tbEmail.Text) || !string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))))
                    {
                        var personRecordTypeId  = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        var personStatusPending = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                        person                     = new Person();
                        person.IsSystem            = false;
                        person.RecordTypeValueId   = personRecordTypeId;
                        person.RecordStatusValueId = personStatusPending;
                        person.FirstName           = tbFirstName.Text;
                        person.LastName            = tbLastName.Text;
                        person.Gender              = Gender.Unknown;

                        if (!string.IsNullOrWhiteSpace(tbEmail.Text))
                        {
                            person.Email           = tbEmail.Text;
                            person.IsEmailActive   = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                        }

                        PersonService.SaveNewPerson(person, rockContext, cpCampus.SelectedCampusId);

                        if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                        {
                            var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE));

                            var phoneNumber = new PhoneNumber {
                                NumberTypeValueId = mobilePhoneType.Id
                            };
                            phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                            phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);
                            person.PhoneNumbers.Add(phoneNumber);
                        }
                    }
                }

                prayerRequest.FirstName = tbFirstName.Text;
                prayerRequest.LastName  = tbLastName.Text;
                prayerRequest.Email     = tbEmail.Text;
                if (person != null)
                {
                    prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                }
                else
                {
                    prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
                }
            }
            else
            {
                prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId;
                prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName;
                prayerRequest.LastName  = personContext.LastName;
                prayerRequest.Email     = personContext.Email;
            }

            prayerRequest.CampusId = cpCampus.SelectedCampusId;

            prayerRequest.Text = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = this.DefaultToPublic;
            }

            if (!Page.IsValid)
            {
                return;
            }

            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, prayerRequest);

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                prayerRequest.SaveAttributeValues(rockContext);
            });


            StartWorkflow(prayerRequest, rockContext);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else if (GetAttributeValue("RefreshPageOnSave").AsBoolean())
            {
                NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString()));
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("PrayerRequest", prayerRequest);
                nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var  phoneNumberTypeIds = new List <int>();
                    var  phoneNumbersScreen = new List <PhoneNumber>();
                    bool smsSelected        = false;
                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped file is still in BinaryFile. So clean it up
                if (imgPhoto.CropBinaryFileId.HasValue)
                {
                    if (imgPhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    person.BirthMonth = birthday.Value.Month;
                    person.BirthDay   = birthday.Value.Day;

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        person.BirthYear = birthday.Value.Year;
                    }
                    else
                    {
                        person.BirthYear = null;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                    CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null &&
                        cbUnlisted != null &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }