예제 #1
0
        /// <summary>
        /// Posts the specified phone number.
        /// </summary>
        /// <param name="phoneNumber">The phone number.</param>
        /// <returns></returns>
        public override System.Net.Http.HttpResponseMessage Post(PhoneNumber phoneNumber)
        {
            var    changes        = new List <string>();
            string newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;

            History.EvaluateChange(
                changes,
                string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                string.Empty,
                newPhoneNumber);

            var rockContext = (RockContext)Service.Context;

            System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());

            int?modifiedByPersonAliasId = phoneNumber.ModifiedAuditValuesAlreadyUpdated ? phoneNumber.ModifiedByPersonAliasId : (int?)null;

            HistoryService.SaveChanges(
                rockContext,
                typeof(Person),
                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                phoneNumber.PersonId,
                changes,
                true,
                modifiedByPersonAliasId);

            return(base.Post(phoneNumber));
        }
예제 #2
0
        /// <summary>
        /// Handles the Click event of the 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 lbToPersonSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);
            var changes = new List <string>();

            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON).Id;

            History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(dvpPersonConnectionStatus.SelectedValueAsInt()));
            person.ConnectionStatusValueId = dvpPersonConnectionStatus.SelectedValueAsInt();

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

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

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

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

            ppSource.SetValue(null);
            nbSuccess.Text = string.Format("{0} has been converted to a person.", person.FullName);

            pnlToPerson.Visible = false;
        }
        /// <summary>
        /// Sets from payment information.
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="changes">The changes.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext, List <string> changes = null)
        {
            if (changes != null)
            {
                History.EvaluateChange(changes, "Account Number", AccountNumberMasked, paymentInfo.MaskedNumber);
                History.EvaluateChange(changes, "Currency Type", DefinedValueCache.GetName(CurrencyTypeValueId),
                                       paymentInfo.CurrencyTypeValue != null ? paymentInfo.CurrencyTypeValue.Value : string.Empty);
                History.EvaluateChange(changes, "Credit Card Type", DefinedValueCache.GetName(CreditCardTypeValueId),
                                       paymentInfo.CreditCardTypeValue != null ? paymentInfo.CreditCardTypeValue.Value : string.Empty);
            }

            AccountNumberMasked   = paymentInfo.MaskedNumber;
            CurrencyTypeValueId   = paymentInfo.CurrencyTypeValue != null ? paymentInfo.CurrencyTypeValue.Id : (int?)null;
            CreditCardTypeValueId = paymentInfo.CreditCardTypeValue != null ? paymentInfo.CreditCardTypeValue.Id : (int?)null;

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = (CreditCardPaymentInfo)paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (changes != null)
                {
                    string oldNameOnCard = Encryption.DecryptString(NameOnCardEncrypted);
                    History.EvaluateChange(changes, "Name on Card", oldNameOnCard, nameOnCard);
                    History.EvaluateChange(changes, "Expiration Month", Encryption.DecryptString(ExpirationMonthEncrypted), ccPaymentInfo.ExpirationDate.Month.ToString());
                    History.EvaluateChange(changes, "Expiration Year", Encryption.DecryptString(ExpirationYearEncrypted), ccPaymentInfo.ExpirationDate.Year.ToString());
                    History.EvaluateChange(changes, "Billing Location", BillingLocation != null ? BillingLocation.ToString() : string.Empty, newLocation != null ? newLocation.ToString() : string.Empty);
                }

                NameOnCardEncrypted      = Encryption.EncryptString(nameOnCard);
                ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                ExpirationYearEncrypted  = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                BillingLocationId        = newLocation != null ? newLocation.Id : (int?)null;
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = (SwipePaymentInfo)paymentInfo;

                if (changes != null)
                {
                    string oldNameOnCard = Encryption.DecryptString(NameOnCardEncrypted);
                    History.EvaluateChange(changes, "Name on Card", oldNameOnCard, swipePaymentInfo.NameOnCard);
                    History.EvaluateChange(changes, "Expiration Month", Encryption.DecryptString(ExpirationMonthEncrypted), swipePaymentInfo.ExpirationDate.Month.ToString());
                    History.EvaluateChange(changes, "Expiration Year", Encryption.DecryptString(ExpirationYearEncrypted), swipePaymentInfo.ExpirationDate.Year.ToString());
                }

                NameOnCardEncrypted      = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                ExpirationYearEncrypted  = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
            }
        }
예제 #4
0
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="entry"></param>
        public override void PreSaveChanges(Data.DbContext dbContext, DbEntityEntry entry)
        {
            var rockContext = (RockContext)dbContext;

            GroupHistoryChanges = new History.HistoryChangeList();

            switch (entry.State)
            {
            case EntityState.Added:
            {
                string locationType = History.GetDefinedValueValue(null, GroupLocationTypeValueId);
                locationType = locationType.IsNotNullOrWhiteSpace() ? locationType : "Unknown";
                History.EvaluateChange(GroupHistoryChanges, $"{locationType} Location", (int?)null, Location, LocationId, rockContext);
                History.EvaluateChange(GroupHistoryChanges, $"{locationType} Is Mailing", false, IsMailingLocation);
                History.EvaluateChange(GroupHistoryChanges, $"{locationType} Is Map Location", false, IsMappedLocation);

                break;
            }

            case EntityState.Modified:
            {
                string locationTypeName  = DefinedValueCache.GetName(GroupLocationTypeValueId) ?? "Unknown";
                int?   oldLocationTypeId = entry.OriginalValues["GroupLocationTypeValueId"].ToStringSafe().AsIntegerOrNull();
                if ((oldLocationTypeId ?? 0) == (GroupLocationTypeValueId ?? 0))
                {
                    History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Location", entry.OriginalValues["LocationId"].ToStringSafe().AsIntegerOrNull(), Location, LocationId, rockContext);
                }
                else
                {
                    Location newLocation = null;
                    History.EvaluateChange(GroupHistoryChanges, $"{DefinedValueCache.GetName( oldLocationTypeId ) ?? "Unknown"} Location", entry.OriginalValues["LocationId"].ToStringSafe().AsIntegerOrNull(), newLocation, (int?)null, rockContext);
                    History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Location", (int?)null, Location, LocationId, rockContext);
                }

                History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Is Mailing", entry.OriginalValues["IsMailingLocation"].ToStringSafe().AsBoolean(), IsMailingLocation);
                History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Is Map Location", entry.OriginalValues["IsMappedLocation"].ToStringSafe().AsBoolean(), IsMappedLocation);

                break;
            }

            case EntityState.Deleted:
            {
                string locationType = History.GetDefinedValueValue(null, entry.OriginalValues["GroupLocationTypeValueId"].ToStringSafe().AsIntegerOrNull());
                locationType = locationType.IsNotNullOrWhiteSpace() ? locationType : "Unknown";
                Location loc = null;
                History.EvaluateChange(GroupHistoryChanges, $"{locationType} Location", entry.OriginalValues["LocationId"].ToStringSafe().AsIntegerOrNull(), loc, (int?)null, rockContext);
                break;
            }
            }

            base.PreSaveChanges(dbContext, entry);
        }
            /// <summary>
            /// Called before the save operation is executed.
            /// </summary>
            protected override void PreSave()
            {
                var rockContext = ( RockContext )this.RockContext;

                GroupHistoryChanges = new History.HistoryChangeList();

                switch (State)
                {
                case EntityContextState.Added:
                {
                    string locationType = History.GetDefinedValueValue(null, Entity.GroupLocationTypeValueId);
                    locationType = locationType.IsNotNullOrWhiteSpace() ? locationType : "Unknown";
                    History.EvaluateChange(GroupHistoryChanges, $"{locationType} Location", ( int? )null, Entity.Location, Entity.LocationId, rockContext);
                    History.EvaluateChange(GroupHistoryChanges, $"{locationType} Is Mailing", false, Entity.IsMailingLocation);
                    History.EvaluateChange(GroupHistoryChanges, $"{locationType} Is Map Location", false, Entity.IsMappedLocation);

                    break;
                }

                case EntityContextState.Modified:
                {
                    string locationTypeName  = DefinedValueCache.GetName(Entity.GroupLocationTypeValueId) ?? "Unknown";
                    int?   oldLocationTypeId = OriginalValues[nameof(GroupLocation.GroupLocationTypeValueId)].ToStringSafe().AsIntegerOrNull();
                    if ((oldLocationTypeId ?? 0) == (Entity.GroupLocationTypeValueId ?? 0))
                    {
                        History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Location", OriginalValues[nameof(GroupLocation.LocationId)].ToStringSafe().AsIntegerOrNull(), Entity.Location, Entity.LocationId, rockContext);
                    }
                    else
                    {
                        Location newLocation = null;
                        History.EvaluateChange(GroupHistoryChanges, $"{DefinedValueCache.GetName( oldLocationTypeId ) ?? "Unknown"} Location", OriginalValues[nameof(GroupLocation.LocationId)].ToStringSafe().AsIntegerOrNull(), newLocation, ( int? )null, rockContext);
                        History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Location", ( int? )null, Entity.Location, Entity.LocationId, rockContext);
                    }

                    History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Is Mailing", OriginalValues[nameof(GroupLocation.IsMailingLocation)].ToStringSafe().AsBoolean(), Entity.IsMailingLocation);
                    History.EvaluateChange(GroupHistoryChanges, $"{locationTypeName} Is Map Location", OriginalValues[nameof(GroupLocation.IsMappedLocation)].ToStringSafe().AsBoolean(), Entity.IsMappedLocation);

                    break;
                }

                case EntityContextState.Deleted:
                {
                    string locationType = History.GetDefinedValueValue(null, OriginalValues[nameof(GroupLocation.GroupLocationTypeValueId)].ToStringSafe().AsIntegerOrNull());
                    locationType = locationType.IsNotNullOrWhiteSpace() ? locationType : "Unknown";
                    Location loc = null;
                    History.EvaluateChange(GroupHistoryChanges, $"{locationType} Location", OriginalValues[nameof(GroupLocation.LocationId)].ToStringSafe().AsIntegerOrNull(), loc, ( int? )null, rockContext);
                    break;
                }
                }

                base.PreSave();
            }
예제 #6
0
        /// <summary>
        /// Handles the Click event of the 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 lbToPersonSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);
            var changes = new List <string>();

            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON).Id;

            History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(dvpPersonConnectionStatus.SelectedValueAsInt()));
            person.ConnectionStatusValueId = dvpPersonConnectionStatus.SelectedValueAsInt();

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

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

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

            History.EvaluateChange(changes, "Gender", person.Gender, rblGender.SelectedValueAsEnum <Gender>());
            person.Gender = rblGender.SelectedValueAsEnum <Gender>();

            History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(dvpMaritalStatus.SelectedValueAsId()));
            person.MaritalStatusValueId = dvpMaritalStatus.SelectedValueAsId();

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

            ppSource.SetValue(null);

            var parameters = new Dictionary <string, string>
            {
                { "PersonId", person.Id.ToString() }
            };
            var pageRef = new Rock.Web.PageReference(Rock.SystemGuid.Page.PERSON_PROFILE_PERSON_PAGES, parameters);

            nbSuccess.Text = string.Format("<a href='{1}'>{0}</a> has been converted to a person.", person.FullName, pageRef.BuildUrl());

            pnlToPerson.Visible = false;
        }
예제 #7
0
        /// <summary>
        /// Puts the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="phoneNumber">The phone number.</param>
        public override void Put(int id, PhoneNumber phoneNumber)
        {
            SetProxyCreation(true);

            var rockContext   = (RockContext)Service.Context;
            var existingPhone = Service.Get(id);

            if (existingPhone != null)
            {
                var changes = new List <string>();

                History.EvaluateChange(changes, "Phone Type", DefinedValueCache.GetName(existingPhone.NumberTypeValueId), DefinedValueCache.GetName(phoneNumber.NumberTypeValueId));

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

                if (changes.Any())
                {
                    System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());

                    int?modifiedByPersonAliasId = phoneNumber.ModifiedAuditValuesAlreadyUpdated ? phoneNumber.ModifiedByPersonAliasId : (int?)null;

                    HistoryService.SaveChanges(
                        rockContext,
                        typeof(Person),
                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                        phoneNumber.PersonId,
                        changes,
                        true,
                        modifiedByPersonAliasId);
                }
            }

            base.Put(id, phoneNumber);
        }
        /// <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();
                    }
                }
            });
        }
예제 #9
0
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="entry"></param>
        public override void PreSaveChanges(Data.DbContext dbContext, DbEntityEntry entry)
        {
            if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
            {
                if (string.IsNullOrEmpty(CountryCode))
                {
                    CountryCode = PhoneNumber.DefaultCountryCode();
                }

                // Clean up the number so that the Formatted number looks like (555) 123-4567 (without country code prefix)
                NumberFormatted = PhoneNumber.FormattedNumber(CountryCode, Number);

                // then use the NumberFormatted to set the cleaned up 'Number' value, so it would be 5551234567
                Number = PhoneNumber.CleanNumber(NumberFormatted);
            }

            // Check for duplicate
            if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
            {
                var rockContext        = ( RockContext )dbContext;
                var phoneNumberService = new PhoneNumberService(rockContext);
                var duplicates         = phoneNumberService.Queryable().Where(pn => pn.PersonId == PersonId && pn.Number == Number && pn.CountryCode == CountryCode);

                // Make sure this number isn't considered a duplicate
                if (entry.State == EntityState.Modified)
                {
                    duplicates = duplicates.Where(d => d.Id != Id);
                }

                if (duplicates.Any())
                {
                    var highestOrderedDuplicate = duplicates.Where(p => p.NumberTypeValue != null).OrderBy(p => p.NumberTypeValue.Order).FirstOrDefault();
                    if (NumberTypeValueId.HasValue && highestOrderedDuplicate != null && highestOrderedDuplicate.NumberTypeValue != null)
                    {
                        // Ensure that we preserve the PhoneNumber with the highest preference phone type
                        var numberType = DefinedValueCache.Get(NumberTypeValueId.Value, rockContext);
                        if (highestOrderedDuplicate.NumberTypeValue.Order < numberType.Order)
                        {
                            entry.State = entry.State == EntityState.Added ? EntityState.Detached : EntityState.Deleted;
                        }
                        else
                        {
                            phoneNumberService.DeleteRange(duplicates);
                        }
                    }
                }
            }

            int personId = PersonId;

            PersonHistoryChanges = new Dictionary <int, History.HistoryChangeList> {
                { personId, new History.HistoryChangeList() }
            };

            switch (entry.State)
            {
            case EntityState.Added:
            {
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(NumberTypeValueId)), string.Empty, NumberFormatted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Unlisted", DefinedValueCache.GetName(NumberTypeValueId)), (bool?)null, IsUnlisted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Messaging Enabled", DefinedValueCache.GetName(NumberTypeValueId)), (bool?)null, IsMessagingEnabled);
                break;
            }

            case EntityState.Modified:
            {
                string numberTypeName       = DefinedValueCache.GetName(NumberTypeValueId);
                int?   oldPhoneNumberTypeId = entry.OriginalValues["NumberTypeValueId"].ToStringSafe().AsIntegerOrNull();
                if ((oldPhoneNumberTypeId ?? 0) == (NumberTypeValueId ?? 0))
                {
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", numberTypeName), entry.OriginalValues["NumberFormatted"].ToStringSafe(), NumberFormatted);
                }
                else
                {
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(oldPhoneNumberTypeId)), entry.OriginalValues["NumberFormatted"].ToStringSafe(), string.Empty);
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", numberTypeName), string.Empty, NumberFormatted);
                }

                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Unlisted", numberTypeName), entry.OriginalValues["IsUnlisted"].ToStringSafe().AsBooleanOrNull(), IsUnlisted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Messaging Enabled", numberTypeName), entry.OriginalValues["IsMessagingEnabled"].ToStringSafe().AsBooleanOrNull(), IsMessagingEnabled);

                break;
            }

            case EntityState.Deleted:
            {
                personId = entry.OriginalValues["PersonId"].ToStringSafe().AsInteger();
                PersonHistoryChanges.AddOrIgnore(personId, new History.HistoryChangeList());
                int?oldPhoneNumberTypeId = entry.OriginalValues["NumberTypeValueId"].ToStringSafe().AsIntegerOrNull();
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(oldPhoneNumberTypeId)), entry.OriginalValues["NumberFormatted"].ToStringSafe(), string.Empty);

                return;
            }
            }

            base.PreSaveChanges(dbContext, entry);
        }
예제 #10
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 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();
                    }
                }
            });
        }
예제 #11
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                Rock.Data.RockTransactionScope.WrapTransaction(() =>
                {
                    var personService = new PersonService();

                    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)
                    {
                        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.BirthDate = 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);

                    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 = rblMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

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

                    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;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            tbPhone != null &&
                            cbSms != 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);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormatted;
                                    }

                                    phoneNumber.Number             = PhoneNumber.CleanNumber(tbPhone.Text);
                                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                    phoneNumber.IsUnlisted         = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

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

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService();
                    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.NumberFormatted, string.Empty);

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

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

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

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

                    int?newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                    person.RecordStatusReasonValueId = newRecordStatusReasonId;

                    if (!person.IsValid)
                    {
                        return;
                    }

                    if (personService.Save(person, CurrentPersonId))
                    {
                        if (changes.Any())
                        {
                            new HistoryService().SaveChanges(typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                             Person.Id, changes, CurrentPersonId);
                        }

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

            Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
        }
예제 #12
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);
                    }
                });
            }
        }
        void gPeople_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var person = e.Row.DataItem as PersonSearchResult;
                if (person != null)
                {
                    if (_inactiveStatus != null &&
                        person.RecordStatusValueId.HasValue &&
                        person.RecordStatusValueId.Value == _inactiveStatus.Id)
                    {
                        e.Row.AddCssClass("inactive");
                    }

                    if (person.IsDeceased)
                    {
                        e.Row.AddCssClass("deceased");
                    }

                    string delimitedCampuses = string.Empty;
                    if (person.CampusIds.Any())
                    {
                        var campuses = new List <string>();
                        foreach (var campusId in person.CampusIds)
                        {
                            var campus = CampusCache.Get(campusId);
                            if (campus != null)
                            {
                                campuses.Add(campus.Name);
                            }
                        }
                        if (campuses.Any())
                        {
                            delimitedCampuses = campuses.AsDelimited(", ");
                            var lCampus = e.Row.FindControl("lCampus") as Literal;
                            if (lCampus != null)
                            {
                                lCampus.Text = delimitedCampuses;
                            }
                        }
                    }

                    var lPerson = e.Row.FindControl("lPerson") as Literal;

                    if (!person.IsBusiness)
                    {
                        StringBuilder sbPersonDetails = new StringBuilder();
                        sbPersonDetails.Append(string.Format("<div class=\"photo-round photo-round-sm pull-left\" data-original=\"{0}&w=100\" style=\"background-image: url('{1}');\"></div>", person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-unknown.svg")));
                        sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">");
                        sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed));
                        sbPersonDetails.Append(string.Format("{0} ", Person.GetSignalMarkup(person.TopSignalColor, person.TopSignalIconCssClass)));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}</br></small>", delimitedCampuses));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName(person.ConnectionStatusValueId)));
                        sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted));

                        foreach (Guid phGuid in _phoneTypeGuids)
                        {
                            var dv = DefinedValueCache.Get(phGuid);
                            if (dv != null)
                            {
                                var pn = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == dv.Id);
                                if (pn != null)
                                {
                                    sbPersonDetails.Append(string.Format("<br/><small>{0}: {1}</small>", dv.Value.Left(1).ToUpper(), pn.Number));
                                }
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(person.Email))
                        {
                            sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email));
                        }

                        // add home addresses
                        foreach (var location in person.HomeAddresses)
                        {
                            if (string.IsNullOrWhiteSpace(location.Street1) &&
                                string.IsNullOrWhiteSpace(location.Street2) &&
                                string.IsNullOrWhiteSpace(location.City))
                            {
                                continue;
                            }

                            string format       = string.Empty;
                            var    countryValue = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid())
                                                  .DefinedValues
                                                  .Where(v => v.Value.Equals(location.Country, StringComparison.OrdinalIgnoreCase))
                                                  .FirstOrDefault();

                            if (countryValue != null)
                            {
                                format = countryValue.GetAttributeValue("AddressFormat");
                            }

                            if (!string.IsNullOrWhiteSpace(format))
                            {
                                var dict = location.ToDictionary();
                                dict["Country"] = countryValue.Description;
                                sbPersonDetails.Append(string.Format("<small><br>{0}</small>", format.ResolveMergeFields(dict).ConvertCrLfToHtmlBr().Replace("<br/><br/>", "<br/>")));
                            }
                            else
                            {
                                sbPersonDetails.Append(string.Format(string.Format("<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.State, location.PostalCode)));
                            }
                        }
                        sbPersonDetails.Append("</div>");

                        lPerson.Text = sbPersonDetails.ToString();

                        if (_showSpouse)
                        {
                            using (var rockContext = new RockContext())
                            {
                                var personRec = new PersonService(rockContext).Get(person.Id);
                                if (personRec != null)
                                {
                                    var lSpouse = e.Row.FindControl("lSpouse") as Literal;
                                    var spouse  = personRec.GetSpouse(rockContext);
                                    if (lSpouse != null && spouse != null)
                                    {
                                        lSpouse.Text = spouse.FullName;
                                    }
                                }
                            }
                        }

                        if (_envelopeNumbers != null && _envelopeNumbers.ContainsKey(person.Id))
                        {
                            var lEnvelopeNumber = e.Row.FindControl("lEnvelopeNumber") as Literal;
                            if (lEnvelopeNumber != null)
                            {
                                lEnvelopeNumber.Text = _envelopeNumbers[person.Id];
                            }
                        }
                    }
                    else
                    {
                        lPerson.Text = string.Format("{0}", person.LastName);
                    }
                }
            }
        }
예제 #14
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();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

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

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

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

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

                rockContext.SaveChanges();

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

            ShowSummary(hfBusinessId.Value.AsInteger());
        }
        public override void Put(int id, Person person)
        {
            SetProxyCreation(true);

            var rockContext    = (RockContext)Service.Context;
            var existingPerson = Service.Get(id);

            if (existingPerson != null)
            {
                var changes = new List <string>();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(existingPerson.RecordStatusValueId), DefinedValueCache.GetName(person.RecordStatusValueId));
                History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(existingPerson.RecordStatusReasonValueId), DefinedValueCache.GetName(person.RecordStatusReasonValueId));
                History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(existingPerson.TitleValueId), DefinedValueCache.GetName(person.TitleValueId));
                History.EvaluateChange(changes, "First Name", existingPerson.FirstName, person.FirstName);
                History.EvaluateChange(changes, "Nick Name", existingPerson.NickName, person.NickName);
                History.EvaluateChange(changes, "Middle Name", existingPerson.MiddleName, person.MiddleName);
                History.EvaluateChange(changes, "Last Name", existingPerson.LastName, person.LastName);
                History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(existingPerson.SuffixValueId), DefinedValueCache.GetName(person.SuffixValueId));
                History.EvaluateChange(changes, "Birth Month", existingPerson.BirthMonth, person.BirthMonth);
                History.EvaluateChange(changes, "Birth Day", existingPerson.BirthDay, person.BirthDay);
                History.EvaluateChange(changes, "Birth Year", existingPerson.BirthYear, person.BirthYear);
                History.EvaluateChange(changes, "Graduation Year", existingPerson.GraduationYear, person.GraduationYear);
                History.EvaluateChange(changes, "Anniversary Date", existingPerson.AnniversaryDate, person.AnniversaryDate);
                History.EvaluateChange(changes, "Gender", existingPerson.Gender, person.Gender);
                History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(existingPerson.MaritalStatusValueId), DefinedValueCache.GetName(person.MaritalStatusValueId));
                History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(existingPerson.ConnectionStatusValueId), DefinedValueCache.GetName(person.ConnectionStatusValueId));
                History.EvaluateChange(changes, "Email", existingPerson.Email, person.Email);
                History.EvaluateChange(changes, "Email Active", existingPerson.IsEmailActive, person.IsEmailActive);
                History.EvaluateChange(changes, "Email Preference", existingPerson.EmailPreference, person.EmailPreference);

                if (person.GivingGroupId != existingPerson.GivingGroupId)
                {
                    string oldGivingGroupName = existingPerson.GivingGroup != null ? existingPerson.GivingGroup.Name : string.Empty;
                    string newGivingGroupName = person.GivingGroup != null ? person.GivingGroup.Name : string.Empty;
                    if (person.GivingGroupId.HasValue && string.IsNullOrWhiteSpace(newGivingGroupName))
                    {
                        var givingGroup = new GroupService(rockContext).Get(person.GivingGroupId.Value);
                        newGivingGroupName = givingGroup != null ? givingGroup.Name : string.Empty;
                    }
                    History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName);
                }

                if (changes.Any())
                {
                    System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());

                    int?modifiedByPersonAliasId = person.ModifiedAuditValuesAlreadyUpdated ? person.ModifiedByPersonAliasId : (int?)null;

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

            base.Put(id, person);
        }
예제 #16
0
        /// <summary>
        /// Handles the Click event of the 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 lbToBusinessSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);
            var changes = new List <string>();

            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS).Id;

            History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(null));
            person.ConnectionStatusValueId = null;

            History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(null));
            person.TitleValueId = null;

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

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

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

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

            History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(null));
            person.SuffixValueId = null;

            History.EvaluateChange(changes, "Birth Month", person.BirthMonth, null);
            History.EvaluateChange(changes, "Birth Day", person.BirthDay, null);
            History.EvaluateChange(changes, "Birth Year", person.BirthYear, null);
            person.SetBirthDate(null);

            History.EvaluateChange(changes, "Gender", person.Gender, Gender.Unknown);
            person.Gender = Gender.Unknown;

            History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(null));
            person.MaritalStatusValueId = null;

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

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

            //
            // Check address(es) and make sure one is of type Work.
            //
            var family = person.GetFamily(context);

            if (family.GroupLocations.Count > 0)
            {
                var workLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;
                var homeLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;

                var workLocation = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == workLocationTypeId).FirstOrDefault();
                if (workLocation == null)
                {
                    var homeLocation = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationTypeId).FirstOrDefault();
                    if (homeLocation != null)
                    {
                        homeLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                }
            }

            //
            // Check phone(es) and make sure one is of type Work.
            //
            if (person.PhoneNumbers.Count > 0)
            {
                var workPhoneTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK).Id;
                var homePhoneTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME).Id;

                var workPhone = person.PhoneNumbers.Where(pn => pn.NumberTypeValueId == workPhoneTypeId).FirstOrDefault();
                if (workPhone == null)
                {
                    var homePhone = person.PhoneNumbers.Where(pn => pn.NumberTypeValueId == homePhoneTypeId).FirstOrDefault();
                    if (homePhone != null)
                    {
                        homePhone.NumberTypeValueId = workPhoneTypeId;
                    }
                }
            }

            //
            // Make sure member status in family is set to Adult.
            //
            var adultRoleId = GroupTypeCache.GetFamilyGroupType().Roles
                              .Where(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())
                              .Select(a => a.Id).First();

            family.Members.Where(m => m.PersonId == person.Id).First().GroupRoleId = adultRoleId;

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

            ppSource.SetValue(null);
            nbSuccess.Text = string.Format("{0} has been converted to a business.", person.LastName);

            pnlToBusiness.Visible = false;
        }
예제 #17
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();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

                business.GivingGroup = businessGroup;

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

            NavigateToParentPage();
        }
예제 #18
0
        protected void btnNext_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (CurrentCategoryIndex < attributeControls.Count)
                {
                    CurrentCategoryIndex++;
                    ShowAttributeCategory(CurrentCategoryIndex);
                }
                else
                {
                    var familyMembers = GetControlData();
                    if (familyMembers.Any())
                    {
                        RockTransactionScope.WrapTransaction(() =>
                        {
                            using (new UnitOfWorkScope())
                            {
                                var familyGroupType = GroupTypeCache.GetFamilyGroupType();

                                var familyChanges            = new List <string>();
                                var familyMemberChanges      = new Dictionary <Guid, List <string> >();
                                var familyDemographicChanges = new Dictionary <Guid, List <string> >();

                                if (familyGroupType != null)
                                {
                                    var groupService = new GroupService();

                                    var groupTypeRoleService = new GroupTypeRoleService();

                                    var familyGroup         = new Group();
                                    familyGroup.GroupTypeId = familyGroupType.Id;

                                    familyChanges.Add("Created");

                                    familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family";
                                    History.EvaluateChange(familyChanges, "Name", string.Empty, familyGroup.Name);

                                    int?campusId = cpCampus.SelectedValueAsInt();
                                    if (campusId.HasValue)
                                    {
                                        History.EvaluateChange(familyChanges, "Campus", string.Empty, CampusCache.Read(campusId.Value).Name);
                                    }
                                    familyGroup.CampusId = campusId;

                                    foreach (var familyMember in familyMembers)
                                    {
                                        var person = familyMember.Person;
                                        if (person != null)
                                        {
                                            familyGroup.Members.Add(familyMember);

                                            var demographicChanges = new List <string>();
                                            demographicChanges.Add("Created");
                                            History.EvaluateChange(demographicChanges, "Record Status", string.Empty,
                                                                   person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName(person.RecordStatusReasonValueId.Value) : string.Empty);
                                            History.EvaluateChange(demographicChanges, "Title", string.Empty,
                                                                   person.TitleValueId.HasValue ? DefinedValueCache.GetName(person.TitleValueId) : string.Empty);
                                            History.EvaluateChange(demographicChanges, "First Name", string.Empty, person.FirstName);
                                            History.EvaluateChange(demographicChanges, "Nick Name", string.Empty, person.NickName);
                                            History.EvaluateChange(demographicChanges, "Middle Name", string.Empty, person.MiddleName);
                                            History.EvaluateChange(demographicChanges, "Last Name", string.Empty, person.LastName);
                                            History.EvaluateChange(demographicChanges, "Gender", null, person.Gender);
                                            History.EvaluateChange(demographicChanges, "Birth Date", null, person.BirthDate);
                                            History.EvaluateChange(demographicChanges, "Connection Status", string.Empty,
                                                                   person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName(person.ConnectionStatusValueId) : string.Empty);
                                            History.EvaluateChange(demographicChanges, "Graduation Date", null, person.GraduationDate);
                                            familyDemographicChanges.Add(person.Guid, demographicChanges);

                                            var memberChanges = new List <string>();
                                            string roleName   = familyGroupType.Roles[familyMember.GroupRoleId] ?? string.Empty;
                                            History.EvaluateChange(memberChanges, "Role", string.Empty, roleName);
                                            familyMemberChanges.Add(person.Guid, memberChanges);
                                        }
                                    }

                                    if (!String.IsNullOrWhiteSpace(tbStreet1.Text) ||
                                        !String.IsNullOrWhiteSpace(tbStreet2.Text) ||
                                        !String.IsNullOrWhiteSpace(tbCity.Text) ||
                                        !String.IsNullOrWhiteSpace(tbZip.Text))
                                    {
                                        string addressChangeField = "Address";

                                        var groupLocation = new GroupLocation();
                                        var location      = new LocationService().Get(
                                            tbStreet1.Text, tbStreet2.Text, tbCity.Text, ddlState.SelectedValue, tbZip.Text);
                                        groupLocation.Location = location;

                                        Guid locationTypeGuid = Guid.Empty;
                                        if (Guid.TryParse(GetAttributeValue("LocationType"), out locationTypeGuid))
                                        {
                                            var locationType = Rock.Web.Cache.DefinedValueCache.Read(locationTypeGuid);
                                            if (locationType != null)
                                            {
                                                addressChangeField = string.Format("{0} Address", locationType.Name);
                                                groupLocation.GroupLocationTypeValueId = locationType.Id;
                                            }
                                        }

                                        familyGroup.GroupLocations.Add(groupLocation);

                                        History.EvaluateChange(familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString());
                                    }


                                    groupService.Add(familyGroup, CurrentPersonId);
                                    groupService.Save(familyGroup, CurrentPersonId);

                                    var historyService = new HistoryService();
                                    historyService.SaveChanges(typeof(Group), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                               familyGroup.Id, familyChanges, CurrentPersonId);

                                    var personService = new PersonService();

                                    foreach (var groupMember in familyMembers)
                                    {
                                        var person = personService.Get(groupMember.PersonId);
                                        if (person != null)
                                        {
                                            var changes = familyDemographicChanges[person.Guid];
                                            if (groupMember.GroupRoleId != _childRoleId)
                                            {
                                                person.GivingGroupId = familyGroup.Id;
                                                personService.Save(person, CurrentPersonId);
                                                History.EvaluateChange(changes, "Giving Group", string.Empty, familyGroup.Name);
                                            }

                                            foreach (var attributeControl in attributeControls)
                                            {
                                                foreach (var attribute in attributeControl.AttributeList)
                                                {
                                                    string attributeValue = person.GetAttributeValue(attribute.Key);
                                                    if (!string.IsNullOrWhiteSpace(attributeValue))
                                                    {
                                                        Rock.Attribute.Helper.SaveAttributeValue(person, attribute, attributeValue, CurrentPersonId);
                                                        attributeValue = attribute.FieldType.Field.FormatValue(null, attributeValue, attribute.QualifierValues, false);
                                                        History.EvaluateChange(changes, attribute.Name, string.Empty, attributeValue);
                                                    }
                                                }
                                            }

                                            historyService.SaveChanges(typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                                                       person.Id, changes, CurrentPersonId);

                                            historyService.SaveChanges(typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                                                       person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof(Group), familyGroup.Id, CurrentPersonId);
                                        }
                                    }
                                }
                            }
                        });

                        Response.Redirect(string.Format("~/Person/{0}", familyMembers[0].Person.Id), false);
                    }
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Handles the Click event of the btnSave control. Perform a save operation on
        /// the person being edited and then navigate to the return page.
        /// </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)
        {
            RockContext rockContext           = new RockContext();
            Person      person                = new PersonService(rockContext).Get(TargetPersonId);
            Guid        emailWorkflowTypeGuid = Guid.Empty;

            rockContext.WrapTransaction(() =>
            {
                var changes = new List <string>();

                //
                // Process the nick name.
                //
                if (GetAttributeValue("EditNickName").AsBoolean(true))
                {
                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text.Trim());
                    person.NickName = tbNickName.Text.Trim();
                }

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

                //
                // Process the birthday.
                //
                if (GetAttributeValue("EditBirthday").AsBoolean(true))
                {
                    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);
                }

                //
                // Process the grade / graduation year.
                //
                if (GetAttributeValue("EditGrade").AsBoolean(true))
                {
                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

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

                //
                // Process the marital status and anniversary date.
                //
                if (GetAttributeValue("EditMaritalStatus").AsBoolean(true))
                {
                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

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

                //
                // Process the e-mail address.
                //
                if (GetAttributeValue("EditEmail").AsBoolean(true))
                {
                    emailWorkflowTypeGuid = GetAttributeValue("EmailChangeWorkflow").AsGuid();

                    if (emailWorkflowTypeGuid == Guid.Empty)
                    {
                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text.Trim());
                        person.Email = tbEmail.Text.Trim();
                    }
                }

                //
                // Process all the phone numbers for this person.
                //
                bool smsSelected       = false;
                var phoneNumberTypeIds = new List <int>();
                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != 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;
                                }

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

                //
                // If the person is valid then save the person and begin
                // working on the family (address).
                //
                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);

                            changes.Clear();
                        }
                    }

                    //
                    // Save the family address information.
                    //
                    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("AddressType").AsGuidOrNull();
                                if (addressTypeGuid.HasValue)
                                {
                                    var groupLocationService = new GroupLocationService(rockContext);

                                    var addressTypeDv = DefinedValueCache.Read(addressTypeGuid.Value);
                                    var familyAddress = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == addressTypeDv.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))
                                        {
                                            var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());

                                            if (familyAddress == null)
                                            {
                                                familyAddress = new GroupLocation();
                                                groupLocationService.Add(familyAddress);
                                                familyAddress.GroupLocationTypeValueId = addressTypeDv.Id;
                                                familyAddress.GroupId           = familyGroup.Id;
                                                familyAddress.IsMailingLocation = true;
                                                familyAddress.IsMappedLocation  = true;
                                            }
                                            else if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() && previousAddressValue != null)
                                            {
                                                var isChanged = familyAddress.Location.Street1 != acAddress.Street1 ||
                                                                familyAddress.Location.Street2 != acAddress.Street2 ||
                                                                familyAddress.Location.City != acAddress.City ||
                                                                familyAddress.Location.State != acAddress.State ||
                                                                familyAddress.Location.PostalCode != acAddress.PostalCode;

                                                var hasPrevious = groupLocationService
                                                                  .Queryable("Location")
                                                                  .Where(l => l.GroupLocationTypeValueId == previousAddressValue.Id && l.GroupId == familyGroup.Id)
                                                                  .Where(l => l.Location.Street1 == familyAddress.Location.Street1)
                                                                  .Where(l => l.Location.Street2 == familyAddress.Location.Street2)
                                                                  .Where(l => l.Location.City == familyAddress.Location.City)
                                                                  .Where(l => l.Location.State == familyAddress.Location.State)
                                                                  .Where(l => l.Location.PostalCode == familyAddress.Location.PostalCode)
                                                                  .Where(l => l.Location.Country == familyAddress.Location.Country)
                                                                  .Any();

                                                //
                                                // Only save the previous address if it has actually changed and there is not
                                                // already a matching previous address.
                                                //
                                                if (isChanged && !hasPrevious)
                                                {
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                    previousAddress.GroupId = familyGroup.Id;

                                                    Location previousAddressLocation   = new Location();
                                                    previousAddressLocation.Street1    = familyAddress.Location.Street1;
                                                    previousAddressLocation.Street2    = familyAddress.Location.Street2;
                                                    previousAddressLocation.City       = familyAddress.Location.City;
                                                    previousAddressLocation.State      = familyAddress.Location.State;
                                                    previousAddressLocation.PostalCode = familyAddress.Location.PostalCode;
                                                    previousAddressLocation.Country    = familyAddress.Location.Country;

                                                    previousAddress.Location = previousAddressLocation;
                                                }
                                            }

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

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

                                            History.EvaluateChange(changes, addressTypeDv.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);
                                }
                            }
                        }
                    }
                }
            });

            if (emailWorkflowTypeGuid != Guid.Empty)
            {
                LaunchEmailWorkflow(emailWorkflowTypeGuid, person, tbEmail.Text.Trim());
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SuccessTemplate")))
            {
                pnlEdit.Visible    = false;
                pnlSuccess.Visible = true;

                nbSuccess.Text = GetAttributeValue("SuccessTemplate").ResolveMergeFields(new Dictionary <string, object>());
            }
            else
            {
                NavigateToParentPage();
            }
        }
예제 #20
0
        /// <summary>
        /// Handles the Click event of the btnSubmit 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 btnSubmit_Click(object sender, EventArgs e)
        {
            if (_person != null)
            {
                var changes = new List <string>();

                var rockContext = new RockContext();
                var service     = new PersonService(rockContext);
                var person      = service.Get(_person.Id);
                if (person != null)
                {
                    EmailPreference emailPreference = EmailPreference.EmailAllowed;

                    switch (rblEmailPreference.SelectedValue)
                    {
                    case "1":
                    {
                        emailPreference = EmailPreference.NoMassEmails;
                        break;
                    }

                    case "2":
                    case "3":
                    {
                        emailPreference = EmailPreference.DoNotEmail;
                        break;
                    }
                    }

                    History.EvaluateChange(changes, "Email Preference", person.EmailPreference, emailPreference);
                    person.EmailPreference = emailPreference;

                    if (rblEmailPreference.SelectedValue == "3")
                    {
                        var newRecordStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                        if (newRecordStatus != null)
                        {
                            History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), newRecordStatus.Value);
                            person.RecordStatusValueId = newRecordStatus.Id;
                        }

                        var newInactiveReason = DefinedValueCache.Read(ddlInactiveReason.SelectedValue.AsInteger());
                        if (newInactiveReason != null)
                        {
                            History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), newInactiveReason.Value);
                            person.RecordStatusReasonValueId = newInactiveReason.Id;
                        }

                        var newReviewReason = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_REVIEW_REASON_SELF_INACTIVATED);
                        if (newReviewReason != null)
                        {
                            History.EvaluateChange(changes, "Review Reason", DefinedValueCache.GetName(person.ReviewReasonValueId), newReviewReason.Value);
                            person.ReviewReasonValueId = newReviewReason.Id;
                        }

                        // If the inactive reason note is the same as the current review reason note, update it also.
                        if ((person.InactiveReasonNote ?? string.Empty) == (person.ReviewReasonNote ?? string.Empty))
                        {
                            History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveNote.Text);
                            person.InactiveReasonNote = tbInactiveNote.Text;
                        }

                        History.EvaluateChange(changes, "Review Reason Note", person.ReviewReasonNote, tbInactiveNote.Text);
                        person.ReviewReasonNote = tbInactiveNote.Text;
                    }
                    else
                    {
                        var newRecordStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE);
                        if (newRecordStatus != null)
                        {
                            History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), newRecordStatus.Value);
                            person.RecordStatusValueId = newRecordStatus.Id;
                        }

                        History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), string.Empty);
                        person.RecordStatusReasonValueId = null;
                    }

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

                    rockContext.SaveChanges();

                    nbMessage.Visible = true;
                    return;
                }
            }
        }
        /// <summary>
        /// Saves the new family.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="familyMembers">The family members.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param>
        /// <returns></returns>
        public static Group SaveNewFamily( RockContext rockContext, List<GroupMember> familyMembers, int? campusId, bool savePersonAttributes )
        {
            var familyGroupType = GroupTypeCache.GetFamilyGroupType();

            var familyChanges = new List<string>();
            var familyMemberChanges = new Dictionary<Guid, List<string>>();
            var familyDemographicChanges = new Dictionary<Guid, List<string>>();

            if ( familyGroupType != null )
            {
                var groupService = new GroupService( rockContext );

                var familyGroup = new Group();

                familyGroup.GroupTypeId = familyGroupType.Id;

                familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family";
                History.EvaluateChange( familyChanges, "Family", string.Empty, familyGroup.Name );

                if ( campusId.HasValue )
                {
                    History.EvaluateChange( familyChanges, "Campus", string.Empty, CampusCache.Read( campusId.Value ).Name );
                }
                familyGroup.CampusId = campusId;

                int? childRoleId = null;
                var childRole = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) );
                if ( childRole != null )
                {
                    childRoleId = childRole.Id;
                }

                foreach ( var familyMember in familyMembers )
                {
                    var person = familyMember.Person;
                    if ( person != null )
                    {
                        familyGroup.Members.Add( familyMember );

                        var demographicChanges = new List<string>();
                        demographicChanges.Add( "Created" );

                        History.EvaluateChange( demographicChanges, "Record Type", string.Empty, person.RecordTypeValueId.HasValue ? DefinedValueCache.GetName( person.RecordTypeValueId.Value ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Record Status", string.Empty, person.RecordStatusValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusValueId.Value ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Record Status Reason", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusReasonValueId.Value ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName( person.ConnectionStatusValueId ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Deceased", false.ToString(), ( person.IsDeceased ?? false ).ToString() );
                        History.EvaluateChange( demographicChanges, "Title", string.Empty, person.TitleValueId.HasValue ? DefinedValueCache.GetName( person.TitleValueId ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName );
                        History.EvaluateChange( demographicChanges, "Nick Name", string.Empty, person.NickName );
                        History.EvaluateChange( demographicChanges, "Middle Name", string.Empty, person.MiddleName );
                        History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName );
                        History.EvaluateChange( demographicChanges, "Suffix", string.Empty, person.SuffixValueId.HasValue ? DefinedValueCache.GetName( person.SuffixValueId ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate );
                        History.EvaluateChange( demographicChanges, "Gender", null, person.Gender );
                        History.EvaluateChange( demographicChanges, "Marital Status", string.Empty, person.MaritalStatusValueId.HasValue ? DefinedValueCache.GetName( person.MaritalStatusValueId ) : string.Empty );
                        History.EvaluateChange( demographicChanges, "Anniversary Date", null, person.AnniversaryDate );
                        History.EvaluateChange( demographicChanges, "Graduation Year", null, person.GraduationYear );
                        History.EvaluateChange( demographicChanges, "Email", string.Empty, person.Email );
                        History.EvaluateChange( demographicChanges, "Email Active", false.ToString(), ( person.IsEmailActive ?? false ).ToString() );
                        History.EvaluateChange( demographicChanges, "Email Note", string.Empty, person.EmailNote );
                        History.EvaluateChange( demographicChanges, "Email Preference", null, person.EmailPreference );
                        History.EvaluateChange( demographicChanges, "Inactive Reason Note", string.Empty, person.InactiveReasonNote );
                        History.EvaluateChange( demographicChanges, "System Note", string.Empty, person.SystemNote );

                        familyDemographicChanges.Add( person.Guid, demographicChanges );

                        var memberChanges = new List<string>();

                        string roleName = familyGroupType.Roles
                            .Where( r => r.Id == familyMember.GroupRoleId )
                            .Select( r => r.Name )
                            .FirstOrDefault();

                        History.EvaluateChange( memberChanges, "Role", string.Empty, roleName );
                        familyMemberChanges.Add( person.Guid, memberChanges );
                    }
                }

                groupService.Add( familyGroup );
                rockContext.SaveChanges();

                var personService = new PersonService( rockContext );

                foreach ( var groupMember in familyMembers )
                {
                    var person = groupMember.Person;

                    if ( savePersonAttributes )
                    {
                        var newValues = person.AttributeValues;

                        person.LoadAttributes();
                        foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) )
                        {
                            string oldValue = person.GetAttributeValue( attributeCache.Key ) ?? string.Empty;
                            string newValue = string.Empty;
                            if ( newValues != null &&
                                newValues.ContainsKey( attributeCache.Key ) &&
                                newValues[attributeCache.Key] != null )
                            {
                                newValue = newValues[attributeCache.Key].Value ?? string.Empty;
                            }

                            if ( !oldValue.Equals( newValue ) )
                            {
                                History.EvaluateChange( familyDemographicChanges[person.Guid], attributeCache.Name,
                                    attributeCache.FieldType.Field.FormatValue( null, oldValue, attributeCache.QualifierValues, false ),
                                    attributeCache.FieldType.Field.FormatValue( null, newValue, attributeCache.QualifierValues, false ) );
                                Rock.Attribute.Helper.SaveAttributeValue( person, attributeCache, newValue );
                            }
                        }
                    }

                    person = personService.Get( groupMember.PersonId );
                    if ( person != null )
                    {
                        bool updateRequired = false;
                        if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) )
                        {
                            person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
                            updateRequired = true;
                        }
                        var changes = familyDemographicChanges[person.Guid];
                        if ( groupMember.GroupRoleId != childRoleId )
                        {
                            person.GivingGroupId = familyGroup.Id;
                            updateRequired = true;
                            History.EvaluateChange( changes, "Giving Group", string.Empty, familyGroup.Name );
                        }

                        if ( updateRequired )
                        {
                            rockContext.SaveChanges();
                        }

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

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof( Group ), familyGroup.Id );

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            person.Id, familyChanges, familyGroup.Name, typeof( Group ), familyGroup.Id );
                    }
                }

                return familyGroup;
            }

            return null;
        }
예제 #22
0
파일: PhoneNumber.cs 프로젝트: sjison/Rock
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="entry"></param>
        public override void PreSaveChanges(DbContext dbContext, DbEntityEntry entry)
        {
            if (entry.State == System.Data.Entity.EntityState.Added || entry.State == System.Data.Entity.EntityState.Modified)
            {
                if (string.IsNullOrEmpty(CountryCode))
                {
                    CountryCode = PhoneNumber.DefaultCountryCode();
                }

                NumberFormatted = PhoneNumber.FormattedNumber(CountryCode, Number);
                Number          = PhoneNumber.CleanNumber(NumberFormatted);
            }

            var rockContext = (RockContext)dbContext;
            int personId    = PersonId;

            PersonHistoryChanges = new Dictionary <int, List <string> > {
                { personId, new List <string>() }
            };

            switch (entry.State)
            {
            case System.Data.Entity.EntityState.Added:
            {
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(NumberTypeValueId)), string.Empty, NumberFormatted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Unlisted", DefinedValueCache.GetName(NumberTypeValueId)), (bool?)null, IsUnlisted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Messaging Enabled", DefinedValueCache.GetName(NumberTypeValueId)), (bool?)null, IsMessagingEnabled);
                break;
            }

            case System.Data.Entity.EntityState.Modified:
            {
                string numberTypeName       = DefinedValueCache.GetName(NumberTypeValueId);
                int?   oldPhoneNumberTypeId = entry.OriginalValues["NumberTypeValueId"].ToStringSafe().AsIntegerOrNull();
                if ((oldPhoneNumberTypeId ?? 0) == (NumberTypeValueId ?? 0))
                {
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", numberTypeName), entry.OriginalValues["NumberFormatted"].ToStringSafe(), NumberFormatted);
                }
                else
                {
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(oldPhoneNumberTypeId)), entry.OriginalValues["NumberFormatted"].ToStringSafe(), string.Empty);
                    History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", numberTypeName), string.Empty, NumberFormatted);
                }

                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Unlisted", numberTypeName), entry.OriginalValues["IsUnlisted"].ToStringSafe().AsBooleanOrNull(), IsUnlisted);
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone Messaging Enabled", numberTypeName), entry.OriginalValues["IsMessagingEnabled"].ToStringSafe().AsBooleanOrNull(), IsMessagingEnabled);

                break;
            }

            case System.Data.Entity.EntityState.Deleted:
            {
                personId = entry.OriginalValues["PersonId"].ToStringSafe().AsInteger();
                PersonHistoryChanges.AddOrIgnore(personId, new List <string>());
                int?oldPhoneNumberTypeId = entry.OriginalValues["NumberTypeValueId"].ToStringSafe().AsIntegerOrNull();
                History.EvaluateChange(PersonHistoryChanges[personId], string.Format("{0} Phone", DefinedValueCache.GetName(oldPhoneNumberTypeId)), entry.OriginalValues["NumberFormatted"].ToStringSafe(), string.Empty);

                return;
            }
            }

            base.PreSaveChanges(dbContext, entry);
        }
예제 #23
0
        /// <summary>
        /// Shows the financial batch summary.
        /// </summary>
        /// <param name="batch">The financial batch.</param>
        private void ShowReadonlyDetails(FinancialBatch batch)
        {
            SetEditMode(false);

            if (batch != null)
            {
                hfBatchId.SetValue(batch.Id);

                SetHeadingInfo(batch, batch.Name);

                string campusName = string.Empty;
                if (batch.CampusId.HasValue)
                {
                    var campus = CampusCache.Read(batch.CampusId.Value);
                    if (campus != null)
                    {
                        campusName = campus.ToString();
                    }
                }

                var rockContext = new RockContext();
                var financialTransactionService = new FinancialTransactionService(rockContext);
                var batchTransactions           = financialTransactionService.Queryable().Where(a => a.BatchId.HasValue && a.BatchId.Value == batch.Id);

                var     financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);
                var     qryTransactionDetails             = financialTransactionDetailService.Queryable().Where(a => a.Transaction.BatchId == batch.Id);
                decimal txnTotal = qryTransactionDetails.Select(a => (decimal?)a.Amount).Sum() ?? 0;

                decimal variance     = txnTotal - batch.ControlAmount;
                string  amountFormat = string.Format(
                    "{0} / {1} / " + (variance == 0.0M ? "{2}" : "<span class='label label-danger'>{2}</span>"),
                    txnTotal.FormatAsCurrency(),
                    batch.ControlAmount.FormatAsCurrency(),
                    variance.FormatAsCurrency());

                lDetails.Text = new DescriptionList()
                                .Add("Date Range", new DateRange(batch.BatchStartDateTime, batch.BatchEndDateTime).ToString("g"))
                                .Add("Transaction / Control / Variance", amountFormat)
                                .Add("Accounting Code", batch.AccountingSystemCode)
                                .Add("Notes", batch.Note)
                                .Html;

                batch.LoadAttributes();
                var attributes = batch.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name).ToList();

                var attributeCategories = Helper.GetAttributeCategories(attributes);

                Rock.Attribute.Helper.AddDisplayControls(batch, attributeCategories, phReadonlyAttributes, null, false);

                // Account Summary
                gAccounts.DataSource = qryTransactionDetails
                                       .GroupBy(d => new
                {
                    AccountId   = d.AccountId,
                    AccountName = d.Account.Name
                })
                                       .Select(s => new
                {
                    Id     = s.Key.AccountId,
                    Name   = s.Key.AccountName,
                    Amount = s.Sum(a => (decimal?)a.Amount) ?? 0.0M
                })
                                       .OrderBy(s => s.Name)
                                       .ToList();

                gAccounts.DataBind();

                // Currency Summary
                gCurrencyTypes.DataSource = batchTransactions
                                            .GroupBy(c => new
                {
                    CurrencyTypeValueId = c.FinancialPaymentDetailId.HasValue ? c.FinancialPaymentDetail.CurrencyTypeValueId : 0,
                })
                                            .Select(s => new
                {
                    CurrencyTypeValueId = s.Key.CurrencyTypeValueId,
                    Amount = s.Sum(a => (decimal?)a.TransactionDetails.Sum(t => t.Amount)) ?? 0.0M
                })
                                            .ToList()
                                            .Select(s => new
                {
                    Id     = s.CurrencyTypeValueId,
                    Name   = DefinedValueCache.GetName(s.CurrencyTypeValueId),
                    Amount = s.Amount
                }).OrderBy(a => a.Name).ToList();

                gCurrencyTypes.DataBind();
            }
        }
예제 #24
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)
                    {
                        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;

                    var newCommunicationPreference = rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>();
                    History.EvaluateChange(changes, "Communication Preference", person.CommunicationPreference, newCommunicationPreference);
                    person.CommunicationPreference = newCommunicationPreference;

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

                    // Save the Envelope Number attribute if it exists and has changed
                    var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());
                    if (GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null)
                    {
                        if (person.Attributes == null)
                        {
                            person.LoadAttributes(rockContext);
                        }

                        var newEnvelopeNumber = tbGivingEnvelopeNumber.Text;
                        var oldEnvelopeNumber = person.GetAttributeValue(personGivingEnvelopeAttribute.Key);
                        if (newEnvelopeNumber != oldEnvelopeNumber)
                        {
                            // If they haven't already comfirmed about duplicate, see if the envelope number if assigned to somebody else
                            if (!string.IsNullOrWhiteSpace(newEnvelopeNumber) && hfGivingEnvelopeNumberConfirmed.Value != newEnvelopeNumber)
                            {
                                var otherPersonIdsWithEnvelopeNumber = new AttributeValueService(rockContext).Queryable()
                                                                       .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.Value == newEnvelopeNumber && a.EntityId != person.Id)
                                                                       .Select(a => a.EntityId);
                                if (otherPersonIdsWithEnvelopeNumber.Any())
                                {
                                    var personList           = new PersonService(rockContext).Queryable().Where(a => otherPersonIdsWithEnvelopeNumber.Contains(a.Id)).AsNoTracking().ToList();
                                    string personListMessage = personList.Select(a => a.FullName).ToList().AsDelimited(", ", " and ");
                                    int maxCount             = 5;
                                    if (personList.Count > maxCount)
                                    {
                                        var otherCount    = personList.Count() - maxCount;
                                        personListMessage = personList.Select(a => a.FullName).Take(10).ToList().AsDelimited(", ") + " and " + otherCount.ToString() + " other " + "person".PluralizeIf(otherCount > 1);
                                    }

                                    string givingEnvelopeWarningText = string.Format(
                                        "The envelope #{0} is already assigned to {1}. Do you want to also assign this number to {2}?",
                                        newEnvelopeNumber,
                                        personListMessage,
                                        person.FullName);

                                    string givingEnvelopeWarningScriptFormat = @"
                                        Rock.dialogs.confirm('{0}', function (result) {{
                                            if ( result )
                                                {{
                                                   $('#{1}').val('{2}');
                                                }}
                                        }})";

                                    string givingEnvelopeWarningScript = string.Format(
                                        givingEnvelopeWarningScriptFormat,
                                        givingEnvelopeWarningText,
                                        hfGivingEnvelopeNumberConfirmed.ClientID,
                                        newEnvelopeNumber);

                                    ScriptManager.RegisterStartupScript(hfGivingEnvelopeNumberConfirmed, hfGivingEnvelopeNumberConfirmed.GetType(), "confirm-envelope-number", givingEnvelopeWarningScript, true);
                                    return;
                                }
                            }

                            History.EvaluateChange(changes, "Giving Envelope Number", oldEnvelopeNumber, newEnvelopeNumber);
                            person.SetAttributeValue(personGivingEnvelopeAttribute.Key, newEnvelopeNumber);
                        }
                    }

                    person.GivingGroupId = newGivingGroupId;

                    bool recordStatusChangedToOrFromInactive = false;
                    var recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id;

                    int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                    // Is the person's record status changing?
                    if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId != newRecordStatusId)
                    {
                        //  If it was inactive OR if the new status is inactive, flag this for use later below.
                        if (person.RecordStatusValueId == recordStatusInactiveId || newRecordStatusId == recordStatusInactiveId)
                        {
                            recordStatusChangedToOrFromInactive = true;
                        }
                    }

                    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 == recordStatusInactiveId)
                    {
                        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)
                    {
                        var saveChangeResult = rockContext.SaveChanges();

                        // if AttributeValues where loaded and set (for example Giving Envelope Number), Save Attribute Values
                        if (person.AttributeValues != null)
                        {
                            person.SaveAttributeValues(rockContext);
                        }

                        if (saveChangeResult > 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();
                                        }
                                    }
                                }
                            }

                            // If the person's record status was changed to or from inactive,
                            // we need to check if any of their families need to be activated or inactivated.
                            if (recordStatusChangedToOrFromInactive)
                            {
                                foreach (var family in personService.GetFamilies(person.Id))
                                {
                                    // Are there any more members of the family who are NOT inactive?
                                    // If not, mark the whole family inactive.
                                    if (!family.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveId).Any())
                                    {
                                        family.IsActive = false;
                                    }
                                    else
                                    {
                                        family.IsActive = true;
                                    }
                                }

                                rockContext.SaveChanges();
                            }
                        }

                        Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
                    }
                });
            }
        }
예제 #25
0
        void gPeople_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var person = e.Row.DataItem as PersonSearchResult;
                if (person != null)
                {
                    if (_inactiveStatus != null &&
                        person.RecordStatusValueId.HasValue &&
                        person.RecordStatusValueId.Value == _inactiveStatus.Id)
                    {
                        e.Row.AddCssClass("inactive");
                    }

                    if (person.IsDeceased ?? false)
                    {
                        e.Row.AddCssClass("deceased");
                    }

                    string delimitedCampuses = string.Empty;
                    if (person.CampusIds.Any())
                    {
                        var campuses = new List <string>();
                        foreach (var campusId in person.CampusIds)
                        {
                            var campus = CampusCache.Read(campusId);
                            if (campus != null)
                            {
                                campuses.Add(campus.Name);
                            }
                        }
                        if (campuses.Any())
                        {
                            delimitedCampuses = campuses.AsDelimited(", ");
                            var lCampus = e.Row.FindControl("lCampus") as Literal;
                            if (lCampus != null)
                            {
                                lCampus.Text = delimitedCampuses;
                            }
                        }
                    }

                    var lPerson = e.Row.FindControl("lPerson") as Literal;

                    if (!person.IsBusiness)
                    {
                        StringBuilder sbPersonDetails = new StringBuilder();
                        sbPersonDetails.Append(string.Format("<div class=\"photo-round photo-round-sm pull-left\" style=\"background-image: url('{0}');\"></div>", person.PhotoUrl));
                        sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">");
                        sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}</br></small>", delimitedCampuses));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName(person.ConnectionStatusValueId)));
                        sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted));
                        if (!string.IsNullOrWhiteSpace(person.Email))
                        {
                            sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email));
                        }

                        // add home addresses
                        foreach (var location in person.HomeAddresses)
                        {
                            if (string.IsNullOrWhiteSpace(location.Street1) &&
                                string.IsNullOrWhiteSpace(location.Street2) &&
                                string.IsNullOrWhiteSpace(location.City))
                            {
                                continue;
                            }

                            string format       = string.Empty;
                            var    countryValue = Rock.Web.Cache.DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid())
                                                  .DefinedValues
                                                  .Where(v => v.Value.Equals(location.Country, StringComparison.OrdinalIgnoreCase))
                                                  .FirstOrDefault();

                            if (countryValue != null)
                            {
                                format = countryValue.GetAttributeValue("AddressFormat");
                            }

                            if (!string.IsNullOrWhiteSpace(format))
                            {
                                var dict = location.ToDictionary();
                                dict["Country"] = countryValue.Description;
                                sbPersonDetails.Append(string.Format("<small><br>{0}</small>", format.ResolveMergeFields(dict).ConvertCrLfToHtmlBr().Replace("<br/><br/>", "<br/>")));
                            }
                            else
                            {
                                sbPersonDetails.Append(string.Format(string.Format("<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.City, location.PostalCode)));
                            }
                        }
                        sbPersonDetails.Append("</div>");

                        lPerson.Text = sbPersonDetails.ToString();
                    }
                    else
                    {
                        lPerson.Text = string.Format("{0}", person.LastName);
                    }
                }
            }
        }
예제 #26
0
        protected void lbSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var rockContext = new RockContext();

                rockContext.WrapTransaction(() =>
                {
                    if (person != null)
                    {
                        var personService = new PersonService(rockContext);

                        var changes = new List <string>();

                        var personSave = personService.Get(person.Id);
                        personSave.LoadAttributes();


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

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

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

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

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

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

                        var birthMonth = personSave.BirthMonth;
                        var birthDay   = personSave.BirthDay;
                        var birthYear  = personSave.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);
                            }

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

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


                        DateTime gradeTransitionDate = GlobalAttributesCache.Read().GetValue("GradeTransitionDate").AsDateTime() ?? new DateTime(RockDateTime.Now.Year, 6, 1);

                        // add a year if the next graduation mm/dd won't happen until next year
                        int gradeOffsetRefactor = (RockDateTime.Now < gradeTransitionDate) ? 0 : 1;


                        int?graduationYear = null;
                        if (gpGrade.SelectedValue.AsIntegerOrNull() != null)
                        {
                            graduationYear = gradeTransitionDate.Year + gradeOffsetRefactor + gpGrade.SelectedValue.AsIntegerOrNull();
                        }

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

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

                        personSave.SetAttributeValue("Allergy", rtbAllergy.Text);

                        var phoneNumberTypeIds = new List <int>();

                        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)
                            {
                                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                                {
                                    int phoneNumberTypeId;
                                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                    {
                                        var phoneNumber       = personSave.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                        string oldPhoneNumber = string.Empty;
                                        if (phoneNumber == null)
                                        {
                                            phoneNumber = new PhoneNumber {
                                                NumberTypeValueId = phoneNumberTypeId
                                            };
                                            personSave.PhoneNumbers.Add(phoneNumber);
                                        }
                                        else
                                        {
                                            oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                        }

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

                                        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 personSave.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);

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

                        History.EvaluateChange(changes, "Email", personSave.Email, ebEmail.Text);
                        personSave.Email = ebEmail.Text.Trim();

                        if (personSave.IsValid)
                        {
                            personSave.SaveAttributeValues();

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

                            if (!String.IsNullOrWhiteSpace(GetAttributeValue("PersonDetailsPage")))
                            {
                                NavigateToLinkedPage("PersonDetailsPage", new Dictionary <string, string>()
                                {
                                    { "PersonId", person.Id.ToString() }
                                });
                            }
                            else
                            {
                                NavigateToCurrentPage(new Dictionary <string, string>()
                                {
                                    { "PersonId", person.Id.ToString() }
                                });
                            }
                        }
                    }
                });
            }
        }