/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var personService = new PersonService(rockContext); Person business = null; if (int.Parse(hfBusinessId.Value) != 0) { business = personService.Get(int.Parse(hfBusinessId.Value)); } if (business == null) { business = new Person(); personService.Add(business); tbBusinessName.Text = tbBusinessName.Text.FixCase(); } // Business Name business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id; var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId); if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId }; business.PhoneNumbers.Add(phoneNumber); } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; } else { if (phoneNumber != null) { business.PhoneNumbers.Remove(phoneNumber); new PhoneNumberService(rockContext).Delete(phoneNumber); } } // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // Record Status business.RecordStatusValueId = ddlRecordStatus.SelectedValueAsInt();; // Record Status Reason int?newRecordStatusReasonId = null; if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; business.Email = tbEmail.Text.Trim(); business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); if (!business.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // Add/Update Family Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext); business.GivingGroup = adultFamilyMember.Group; // Add/Update Known Relationship Group Type var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()); int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext); // Add/Update Implied Relationship Group Type var impliedRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid()); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext); rockContext.SaveChanges(); // Location int workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id; var groupLocationService = new GroupLocationService(rockContext); var workLocation = groupLocationService.Queryable("Location") .Where(gl => gl.GroupId == adultFamilyMember.Group.Id && gl.GroupLocationTypeValueId == workLocationTypeId) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(acAddress.Street1)) { if (workLocation != null) { groupLocationService.Delete(workLocation); } } else { var newLocation = new LocationService(rockContext).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); if (workLocation == null) { workLocation = new GroupLocation(); groupLocationService.Add(workLocation); workLocation.GroupId = adultFamilyMember.Group.Id; workLocation.GroupLocationTypeValueId = workLocationTypeId; } workLocation.Location = newLocation; workLocation.IsMailingLocation = true; } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); }); var queryParams = new Dictionary <string, string>(); queryParams.Add("businessId", hfBusinessId.Value); NavigateToCurrentPage(queryParams); }
/// <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(); } } }); }
/// <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) { // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if (Page.IsValid) { confirmExit.Enabled = true; using (new UnitOfWorkScope()) { var familyService = new GroupService(); var familyMemberService = new GroupMemberService(); var personService = new PersonService(); // SAVE FAMILY _family = familyService.Get(_family.Id); _family.Name = tbFamilyName.Text; _family.CampusId = cpCampus.SelectedValueAsInt(); var familyGroupTypeId = _family.GroupTypeId; familyService.Save(_family, CurrentPersonId); // SAVE FAMILY MEMBERS int?recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int?reasonValueId = ddlReason.SelectedValueAsInt(); var newFamilies = new List <Group>(); foreach (var familyMember in FamilyMembers) { var role = familyRoles.Where(r => r.Guid.Equals(familyMember.RoleGuid)).FirstOrDefault(); if (role == null) { role = familyRoles.FirstOrDefault(); } // People added to family (new or from other family) if (!familyMember.ExistingFamilyMember) { var groupMember = new GroupMember(); if (familyMember.Id == -1) { // added new person groupMember.Person = new Person(); groupMember.Person.GivenName = familyMember.FirstName; groupMember.Person.LastName = familyMember.LastName; groupMember.Person.Gender = familyMember.Gender; groupMember.Person.BirthDate = familyMember.BirthDate; } else { // added from other family groupMember.Person = personService.Get(familyMember.Id); } groupMember.Person.RecordStatusValueId = recordStatusValueID; groupMember.Person.RecordStatusReasonValueId = reasonValueId; groupMember.GroupId = _family.Id; if (role != null) { groupMember.GroupRoleId = role.Id; } if (groupMember.Person != null) { familyMemberService.Add(groupMember, CurrentPersonId); familyMemberService.Save(groupMember, CurrentPersonId); } } else { // existing family members var groupMember = familyMemberService.Queryable().Where(m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId == _family.Id).FirstOrDefault(); if (groupMember != null) { if (familyMember.Removed) { // Family member was removed and should be created in their own new family var newFamily = new Group(); newFamily.Name = familyMember.LastName + " Family"; newFamily.GroupTypeId = familyGroupTypeId; newFamily.CampusId = _family.CampusId; familyService.Add(newFamily, CurrentPersonId); familyService.Save(newFamily, CurrentPersonId); groupMember.Group = newFamily; familyMemberService.Save(groupMember, CurrentPersonId); newFamilies.Add(newFamily); } else { // Existing member was not remvoved if (role != null) { groupMember.GroupRoleId = role.Id; groupMember.Person.RecordStatusValueId = recordStatusValueID; groupMember.Person.RecordStatusReasonValueId = reasonValueId; familyMemberService.Save(groupMember, CurrentPersonId); } } } } // Remove anyone that was moved from another family if (familyMember.RemoveFromOtherFamilies) { var otherFamilies = familyMemberService.Queryable() .Where(m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId != _family.Id) .ToList(); foreach (var otherFamilyMember in otherFamilies) { var fm = familyMemberService.Get(otherFamilyMember.Id); familyMemberService.Delete(fm, CurrentPersonId); familyMemberService.Save(fm, CurrentPersonId); var f = familyService.Queryable() .Where(g => g.Id == otherFamilyMember.GroupId && !g.Members.Any()) .FirstOrDefault(); if (f != null) { familyService.Delete(f, CurrentPersonId); familyService.Save(f, CurrentPersonId); } } } } // SAVE LOCATIONS var groupLocationService = new GroupLocationService(); // delete any group locations that were removed var remainingLocationIds = FamilyAddresses.Where(a => a.Id > 0).Select(a => a.Id).ToList(); foreach (var removedLocation in groupLocationService.Queryable() .Where(l => l.GroupId == _family.Id && !remainingLocationIds.Contains(l.Id))) { groupLocationService.Delete(removedLocation, CurrentPersonId); groupLocationService.Save(removedLocation, CurrentPersonId); } foreach (var familyAddress in FamilyAddresses) { Location updatedAddress = null; if (familyAddress.LocationIsDirty) { updatedAddress = new LocationService().Get( familyAddress.Street1, familyAddress.Street2, familyAddress.City, familyAddress.State, familyAddress.Zip); } GroupLocation groupLocation = null; if (familyAddress.Id > 0) { groupLocation = groupLocationService.Get(familyAddress.Id); } if (groupLocation == null) { groupLocation = new GroupLocation(); groupLocation.GroupId = _family.Id; groupLocationService.Add(groupLocation, CurrentPersonId); } groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId; groupLocation.IsMailing = familyAddress.IsMailing; groupLocation.IsLocation = familyAddress.IsLocation; if (updatedAddress != null) { groupLocation.Location = updatedAddress; } groupLocationService.Save(groupLocation, CurrentPersonId); // Add the same locations to any new families created by removing an existing family member if (newFamilies.Any()) { //reload grouplocation for access to child properties groupLocation = groupLocationService.Get(groupLocation.Id); foreach (var newFamily in newFamilies) { var newFamilyLocation = new GroupLocation(); newFamilyLocation.GroupId = newFamily.Id; newFamilyLocation.LocationId = groupLocation.LocationId; newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newFamilyLocation.IsMailing = groupLocation.IsMailing; newFamilyLocation.IsLocation = groupLocation.IsLocation; groupLocationService.Add(newFamilyLocation, CurrentPersonId); groupLocationService.Save(newFamilyLocation, CurrentPersonId); } } } _family = familyService.Get(_family.Id); if (_family.Members.Any(m => m.PersonId == Person.Id)) { Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } else { var fm = _family.Members .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) && m.Person.Gender == Gender.Male) .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); if (fm == null) { fm = _family.Members .Where(m => m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT))) .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); } if (fm == null) { fm = _family.Members .OrderByDescending(m => m.Person.Age) .FirstOrDefault(); } if (fm != null) { Response.Redirect(string.Format("~/Person/{0}", fm.PersonId), false); } else { Response.Redirect("~", false); } } } } }
/// <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()); }
protected void btnSave_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var attributeService = new AttributeService(rockContext); if (checkinArea.Visible) { var groupTypeService = new GroupTypeService(rockContext); var groupType = groupTypeService.Get(checkinArea.GroupTypeGuid); if (groupType != null) { groupType.LoadAttributes(rockContext); checkinArea.GetGroupTypeValues(groupType); if (groupType.IsValid) { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); bool AttributesUpdated = false; // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes)) { var attribute = attributeService.Get(labelAttribute.Value.Guid); Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); AttributesUpdated = true; } // Make sure default role is set if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any()) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; int binaryFileFieldTypeID = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id; foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupType.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if (!attribute.IsValid) { return; } attributeService.Add(attribute); AttributesUpdated = true; } rockContext.SaveChanges(); GroupTypeCache.Flush(groupType.Id); Rock.CheckIn.KioskDevice.FlushAll(); if (AttributesUpdated) { AttributeCache.FlushEntityAttributes(); } nbSaveSuccess.Visible = true; BuildRows(); } } } if (checkinGroup.Visible) { var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var group = groupService.Get(checkinGroup.GroupGuid); if (group != null) { group.LoadAttributes(rockContext); checkinGroup.GetGroupValues(group); // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList(); foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList()) { groupLocationService.Delete(groupLocation); group.GroupLocations.Remove(groupLocation); } var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList(); foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList()) { var groupLocation = new GroupLocation(); groupLocation.LocationId = item.LocationId; group.GroupLocations.Add(groupLocation); } if (group.IsValid) { rockContext.SaveChanges(); group.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.FlushAll(); nbSaveSuccess.Visible = true; BuildRows(); } } } } hfIsDirty.Value = "false"; }
/// <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(); } }
public object UpdateProfile(MobilePerson profile) { var user = UserLoginService.GetCurrentUser(false); if (user == null) { return(ActionStatusCode(System.Net.HttpStatusCode.Unauthorized)); } var personId = user.PersonId.Value; var rockContext = new Data.RockContext(); var personService = new PersonService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); var person = personService.Get(personId); person.NickName = person.NickName == person.FirstName ? profile.FirstName : person.NickName; person.FirstName = profile.FirstName; person.LastName = profile.LastName; person.Gender = ( Gender )profile.Gender; if (GetAttributeValue(AttributeKeys.BirthDateShow).AsBoolean()) { person.SetBirthDate(profile.BirthDate?.Date); } if (GetAttributeValue(AttributeKeys.CampusShow).AsBoolean()) { person.PrimaryFamily.CampusId = profile.CampusGuid.HasValue ? CampusCache.Get(profile.CampusGuid.Value)?.Id : null; } if (GetAttributeValue(AttributeKeys.EmailShow).AsBoolean()) { person.Email = profile.Email; } if (GetAttributeValue(AttributeKeys.MobilePhoneShow).AsBoolean()) { int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id; var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); } // TODO: What to do with country code? phoneNumber.CountryCode = PhoneNumber.CleanNumber("+1"); phoneNumber.Number = PhoneNumber.CleanNumber(profile.MobilePhone); if (string.IsNullOrWhiteSpace(phoneNumber.Number)) { person.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } } if (GetAttributeValue(AttributeKeys.AddressShow).AsBoolean()) { var addressTypeGuid = SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid(); var groupLocationService = new GroupLocationService(rockContext); var dvHomeAddressType = DefinedValueCache.Get(addressTypeGuid); var familyAddress = groupLocationService.Queryable().Where(l => l.GroupId == person.PrimaryFamily.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault(); if (familyAddress != null && string.IsNullOrWhiteSpace(profile.HomeAddress.Street1)) { // delete the current address groupLocationService.Delete(familyAddress); } else { if (!string.IsNullOrWhiteSpace(profile.HomeAddress.Street1)) { if (familyAddress == null) { familyAddress = new GroupLocation(); groupLocationService.Add(familyAddress); familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id; familyAddress.GroupId = person.PrimaryFamily.Id; familyAddress.IsMailingLocation = true; familyAddress.IsMappedLocation = true; } else if (familyAddress.Location.Street1 != profile.HomeAddress.Street1) { // user clicked move so create a previous address var previousAddress = new GroupLocation(); groupLocationService.Add(previousAddress); var previousAddressValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid()); if (previousAddressValue != null) { previousAddress.GroupLocationTypeValueId = previousAddressValue.Id; previousAddress.GroupId = person.PrimaryFamily.Id; Location previousAddressLocation = new Location { Street1 = familyAddress.Location.Street1, Street2 = familyAddress.Location.Street2, City = familyAddress.Location.City, State = familyAddress.Location.State, PostalCode = familyAddress.Location.PostalCode, Country = familyAddress.Location.Country }; previousAddress.Location = previousAddressLocation; } } // TODO: ??? //familyAddress.IsMailingLocation = cbIsMailingAddress.Checked; //familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked; familyAddress.Location = new LocationService(rockContext).Get( profile.HomeAddress.Street1, "", profile.HomeAddress.City, profile.HomeAddress.State, profile.HomeAddress.PostalCode, profile.HomeAddress.Country, person.PrimaryFamily, true); // since there can only be one mapped location, set the other locations to not mapped if (familyAddress.IsMappedLocation) { var groupLocations = groupLocationService.Queryable() .Where(l => l.GroupId == person.PrimaryFamily.Id && l.Id != familyAddress.Id).ToList(); foreach (var groupLocation in groupLocations) { groupLocation.IsMappedLocation = false; } } rockContext.SaveChanges(); } } } rockContext.SaveChanges(); var mobilePerson = MobileHelper.GetMobilePerson(person, MobileHelper.GetCurrentApplicationSite()); mobilePerson.AuthToken = MobileHelper.GetAuthenticationToken(user.UserName); return(ActionOk(mobilePerson)); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var personService = new PersonService(rockContext); Person business = null; if (int.Parse(hfBusinessId.Value) != 0) { business = personService.Get(int.Parse(hfBusinessId.Value)); } if (business == null) { business = new Person(); personService.Add(business); tbBusinessName.Text = tbBusinessName.Text.FixCase(); } // Business Name business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id; var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId); if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId }; business.PhoneNumbers.Add(phoneNumber); } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; } else { if (phoneNumber != null) { business.PhoneNumbers.Remove(phoneNumber); new PhoneNumberService(rockContext).Delete(phoneNumber); } } // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // Record Status business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();; // Record Status Reason int?newRecordStatusReasonId = null; if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = dvpReason.SelectedValueAsInt(); } business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; business.Email = tbEmail.Text.Trim(); business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); avcEditAttributes.GetEditValues(business); if (!business.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // Add/Update Family Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext); business.GivingGroup = adultFamilyMember.Group; // Add/Update Known Relationship Group Type var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()); int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext); // Add/Update Implied Relationship Group Type var impliedRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid()); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext); rockContext.SaveChanges(); // Location int workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id; var groupLocationService = new GroupLocationService(rockContext); var workLocation = groupLocationService.Queryable("Location") .Where(gl => gl.GroupId == adultFamilyMember.Group.Id && gl.GroupLocationTypeValueId == workLocationTypeId) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(acAddress.Street1)) { if (workLocation != null) { if (cbSaveFormerAddressAsPreviousAddress.Checked) { GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now); } groupLocationService.Delete(workLocation); } } else { var newLocation = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); if (workLocation == null) { workLocation = new GroupLocation(); groupLocationService.Add(workLocation); workLocation.GroupId = adultFamilyMember.Group.Id; workLocation.GroupLocationTypeValueId = workLocationTypeId; } else { // Save this to history if the box is checked and the new info is different than the current one. if (cbSaveFormerAddressAsPreviousAddress.Checked && newLocation.Id != workLocation.Location.Id) { new GroupLocationHistoricalService(rockContext).Add(GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now)); } } workLocation.Location = newLocation; workLocation.IsMailingLocation = true; } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); }); /* Ethan Drotning 2022-01-11 * Need save the PersonSearchKeys outside of the transaction since the DB might not have READ_COMMITTED_SNAPSHOT enabled. */ // PersonSearchKey var personSearchKeyService = new PersonSearchKeyService(rockContext); var validSearchTypes = GetValidSearchKeyTypes(); var databaseSearchKeys = personSearchKeyService.Queryable().Where(a => a.PersonAlias.PersonId == business.Id && validSearchTypes.Contains(a.SearchTypeValue.Guid)).ToList(); foreach (var deletedSearchKey in databaseSearchKeys.Where(a => !PersonSearchKeysState.Any(p => p.Guid == a.Guid))) { personSearchKeyService.Delete(deletedSearchKey); } foreach (var personSearchKey in PersonSearchKeysState.Where(a => !databaseSearchKeys.Any(d => d.Guid == a.Guid))) { personSearchKey.PersonAliasId = business.PrimaryAliasId.Value; personSearchKeyService.Add(personSearchKey); } rockContext.SaveChanges(); business.SaveAttributeValues(); var queryParams = new Dictionary <string, string> { { "BusinessId", hfBusinessId.Value } }; NavigateToCurrentPage(queryParams); }