/// <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); person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS).Id; person.ConnectionStatusValueId = null; person.TitleValueId = null; person.FirstName = null; person.NickName = null; person.MiddleName = null; person.LastName = tbBusinessName.Text.Trim(); person.SuffixValueId = null; person.SetBirthDate(null); person.Gender = Gender.Unknown; person.MaritalStatusValueId = null; person.AnniversaryDate = 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.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id; var homeLocationTypeId = DefinedValueCache.Get(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.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK).Id; var homePhoneTypeId = DefinedValueCache.Get(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(); ppSource.SetValue(null); var parameters = new Dictionary <string, string> { { "BusinessId", person.Id.ToString() } }; var pageRef = new Rock.Web.PageReference(Rock.SystemGuid.Page.BUSINESS_DETAIL, parameters); nbSuccess.Text = string.Format("The person formerly known as <a href='{1}'>{0}</a> has been converted to a business.", person.LastName, pageRef.BuildUrl()); pnlToBusiness.Visible = false; }
/// <summary> /// Maps the company. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapCompany(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var businessList = new List <Group>(); // Record status: Active, Inactive, Pending int?statusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?statusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?statusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Record type: Business int?businessRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS), lookupContext).Id; // Group role: TBD int groupRoleId = new GroupTypeRoleService(lookupContext).Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; // Group type: Family int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Cached F1 attribute: HouseholdId var householdIdAttribute = AttributeCache.Read(HouseholdAttributeId, lookupContext); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying company import ({0:N0} found).", totalRows)); foreach (var row in tableData) { int?householdId = row["Household_ID"] as int?; if (GetPersonAliasId(null, householdId) == null) { var businessGroup = new Group(); var business = new Person(); business.CreatedByPersonAliasId = ImportPersonAlias.Id; business.CreatedDateTime = row["Created_Date"] as DateTime?; business.RecordTypeValueId = businessRecordTypeId; var businessName = row["Household_Name"] as string; if (businessName != null) { businessName.Replace("'", "'"); businessName.Replace("&", "&"); business.LastName = businessName.Left(50); businessGroup.Name = businessName.Left(50); } business.Attributes = new Dictionary <string, AttributeCache>(); business.AttributeValues = new Dictionary <string, AttributeValue>(); AddPersonAttribute(householdIdAttribute, business, householdId.ToString()); var groupMember = new GroupMember(); groupMember.Person = business; groupMember.GroupRoleId = groupRoleId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; businessGroup.Members.Add(groupMember); businessGroup.GroupTypeId = familyGroupTypeId; businessList.Add(businessGroup); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} companies imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveCompanies(businessList); businessList.Clear(); ReportPartialProgress(); } } } if (businessList.Any()) { SaveCompanies(businessList); } ReportProgress(100, string.Format("Finished company import: {0:N0} companies imported.", completed)); }
/// <summary> /// Called after the save operation has been executed /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { var rockContext = ( RockContext )this.RockContext; if (HistoryChanges != null) { foreach (var historyItem in HistoryChanges) { int personId = historyItem.PersonId > 0 ? historyItem.PersonId : Entity.PersonId; // if GroupId is 0, it is probably a Group that wasn't saved yet, so get the GroupId from historyItem.Group.Id instead if (historyItem.GroupId == 0) { historyItem.GroupId = historyItem.Group?.Id; } var changes = HistoryService.GetChanges( typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), personId, historyItem.PersonHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, Entity.ModifiedByPersonAliasId, rockContext.SourceOfChange); if (changes.Any()) { Task.Run(async() => { // Wait 1 second to allow all post save actions to complete await Task.Delay(1000); try { using (var insertRockContext = new RockContext()) { insertRockContext.BulkInsert(changes); } } catch (SystemException ex) { ExceptionLogService.LogException(ex, null); } }); } var groupMemberChanges = HistoryService.GetChanges( typeof(GroupMember), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), Entity.Id, historyItem.GroupMemberHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, Entity.ModifiedByPersonAliasId, rockContext.SourceOfChange); if (groupMemberChanges.Any()) { Task.Run(async() => { // Wait 1 second to allow all post save actions to complete await Task.Delay(1000); try { using (var insertRockContext = new RockContext()) { insertRockContext.BulkInsert(groupMemberChanges); } } catch (SystemException ex) { ExceptionLogService.LogException(ex, null); } }); } } } base.PostSave(); // if this is a GroupMember record on a Family, ensure that AgeClassification, PrimaryFamily, // GivingLeadId, and GroupSalution is updated // NOTE: This is also done on Person.PostSaveChanges in case Birthdate changes var groupTypeFamilyRoleIds = GroupTypeCache.GetFamilyGroupType()?.Roles?.Select(a => a.Id).ToList(); if (groupTypeFamilyRoleIds?.Any() == true) { if (groupTypeFamilyRoleIds.Contains(Entity.GroupRoleId)) { PersonService.UpdatePersonAgeClassification(Entity.PersonId, rockContext); PersonService.UpdatePrimaryFamily(Entity.PersonId, rockContext); PersonService.UpdateGivingLeaderId(Entity.PersonId, rockContext); GroupService.UpdateGroupSalutations(Entity.GroupId, rockContext); if (_preSaveChangesOldGroupId.HasValue && _preSaveChangesOldGroupId.Value != Entity.GroupId) { // if person was moved to a different family, the old family will need its GroupSalutations updated GroupService.UpdateGroupSalutations(_preSaveChangesOldGroupId.Value, rockContext); } } } if (State == EntityContextState.Added || State == EntityContextState.Modified) { if (Entity.Group != null && Entity.Person != null) { if (Entity.Group?.IsSecurityRoleOrSecurityGroupType() == true) { /* 09/27/2021 MDP * * If this GroupMember record results in making this Person having a higher AccountProtectionProfile level, * update the Person's AccountProtectionProfile. * Note: If this GroupMember record could result in making this Person having a *lower* AccountProtectionProfile level, * don't lower the AccountProtectionProfile here, because other rules have to be considered before * lowering the AccountProtectionProfile level. So we'll let the RockCleanup job take care of making sure the * AccountProtectionProfile is updated after factoring in all the rules. * */ if (Entity.Group.ElevatedSecurityLevel >= Utility.Enums.ElevatedSecurityLevel.Extreme && Entity.Person.AccountProtectionProfile < Utility.Enums.AccountProtectionProfile.Extreme) { Entity.Person.AccountProtectionProfile = Utility.Enums.AccountProtectionProfile.Extreme; rockContext.SaveChanges(); } else if (Entity.Group.ElevatedSecurityLevel >= Utility.Enums.ElevatedSecurityLevel.High && Entity.Person.AccountProtectionProfile < Utility.Enums.AccountProtectionProfile.High) { Entity.Person.AccountProtectionProfile = Utility.Enums.AccountProtectionProfile.High; rockContext.SaveChanges(); } } } } SendUpdateGroupMemberMessage(); }
/// <summary> /// Loads the family data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadFamily(CsvDataModel csvData) { // Required variables var lookupContext = new RockContext(); var locationService = new LocationService(lookupContext); int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; int numImportedFamilies = ImportedPeople.Select(p => p.ForeignId).Distinct().Count(); int homeLocationTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME)).Id; int workLocationTypeId = DefinedValueCache.Read(new Guid("E071472A-F805-4FC4-917A-D5E3C095C35C")).Id; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newGroupLocations = new Dictionary <GroupLocation, string>(); string currentFamilyId = string.Empty; int completed = 0; ReportProgress(0, string.Format("Starting family import ({0:N0} already exist).", numImportedFamilies)); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { string rowFamilyId = row[FamilyId]; string rowFamilyName = row[FamilyName]; if (!string.IsNullOrWhiteSpace(rowFamilyId) && rowFamilyId != currentFamilyGroup.ForeignId) { currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignId == rowFamilyId); if (currentFamilyGroup == null) { currentFamilyGroup = new Group(); currentFamilyGroup.ForeignId = rowFamilyId; currentFamilyGroup.Name = row[FamilyName]; currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id; currentFamilyGroup.GroupTypeId = familyGroupTypeId; newFamilyList.Add(currentFamilyGroup); } // Set the family campus string campusName = row[Campus]; if (!string.IsNullOrWhiteSpace(campusName)) { var familyCampus = CampusList.Where(c => c.Name.StartsWith(campusName) || c.ShortCode.StartsWith(campusName)).FirstOrDefault(); if (familyCampus == null) { familyCampus = new Campus(); familyCampus.IsSystem = false; familyCampus.Name = campusName; lookupContext.Campuses.Add(familyCampus); lookupContext.SaveChanges(true); } // This won't assign a campus if the family already exists because the context doesn't get saved currentFamilyGroup.CampusId = familyCampus.Id; } // Add the family addresses since they exist in this file string famAddress = row[Address]; string famAddress2 = row[Address2]; string famCity = row[City]; string famState = row[State]; string famZip = row[Zip]; string famCountry = row[Country]; // Use the core Rock location service to add or lookup an address Location primaryAddress = locationService.Get(famAddress, famAddress2, famCity, famState, famZip, famCountry); if (primaryAddress != null) { primaryAddress.Name = currentFamilyGroup.Name + " Home"; var primaryLocation = new GroupLocation(); primaryLocation.LocationId = primaryAddress.Id; primaryLocation.IsMailingLocation = true; primaryLocation.IsMappedLocation = true; primaryLocation.GroupLocationTypeValueId = homeLocationTypeId; newGroupLocations.Add(primaryLocation, rowFamilyId); } string famSecondAddress = row[SecondaryAddress]; string famSecondAddress2 = row[SecondaryAddress2]; string famSecondCity = row[SecondaryCity]; string famSecondState = row[SecondaryState]; string famSecondZip = row[SecondaryZip]; string famSecondCountry = row[SecondaryCountry]; Location secondaryAddress = locationService.Get(famSecondAddress, famSecondAddress2, famSecondCity, famSecondState, famSecondZip, famSecondCountry); if (secondaryAddress != null) { secondaryAddress.Name = currentFamilyGroup.Name + " Work"; var secondaryLocation = new GroupLocation(); secondaryLocation.LocationId = primaryAddress.Id; secondaryLocation.IsMailingLocation = true; secondaryLocation.IsMappedLocation = true; secondaryLocation.GroupLocationTypeValueId = workLocationTypeId; newGroupLocations.Add(secondaryLocation, rowFamilyId); } completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} families imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveFamilies(newFamilyList, newGroupLocations); ReportPartialProgress(); // Reset lookup context lookupContext = new RockContext(); locationService = new LocationService(lookupContext); newFamilyList.Clear(); newGroupLocations.Clear(); } } } // Check to see if any rows didn't get saved to the database if (newGroupLocations.Any()) { SaveFamilies(newFamilyList, newGroupLocations); } ReportProgress(0, string.Format("Finished family import: {0:N0} families imported.", completed)); return(completed); }
private void LoadDropdowns() { ddlSearchType.Items.Clear(); var searchTypes = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CHECKIN_SEARCH_TYPE.AsGuid()); if (searchTypes != null) { foreach (var searchType in searchTypes.DefinedValues) { if (searchType.GetAttributeValue("UserSelectable").AsBooleanOrNull() ?? true) { ddlSearchType.Items.Add(new System.Web.UI.WebControls.ListItem(searchType.Value, searchType.Id.ToString())); } } } lbKnownRelationshipTypes.Items.Clear(); lbKnownRelationshipTypes.Items.Add(new ListItem("Child", "0")); lbSameFamilyKnownRelationshipTypes.Items.Clear(); lbSameFamilyKnownRelationshipTypes.Items.Add(new ListItem("Child", "0")); lbCanCheckInKnownRelationshipTypes.Items.Clear(); var knownRelationShipRoles = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS).Roles; foreach (var knownRelationShipRole in knownRelationShipRoles.Where(a => a.Name != "Child")) { lbKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); lbSameFamilyKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); lbCanCheckInKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); } lbRegistrationRequiredAttributesForAdults.Items.Clear(); lbRegistrationOptionalAttributesForAdults.Items.Clear(); lbRegistrationRequiredAttributesForChildren.Items.Clear(); lbRegistrationOptionalAttributesForChildren.Items.Clear(); var fakePerson = new Person(); fakePerson.LoadAttributes(); foreach (var personAttribute in fakePerson.Attributes.Select(a => new { Name = a.Value.Name, Value = a.Value.Guid.ToString() })) { lbRegistrationRequiredAttributesForAdults.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationOptionalAttributesForAdults.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationRequiredAttributesForChildren.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationOptionalAttributesForChildren.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); } lbRegistrationOptionalAttributesForFamilies.Items.Clear(); lbRegistrationRequiredAttributesForFamilies.Items.Clear(); var fakeFamily = new Group { GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id }; fakeFamily.LoadAttributes(); foreach (var groupTypeFamilyAttribute in fakeFamily.Attributes.Select(a => new { Name = a.Value.Name, Value = a.Value.Guid.ToString() })) { lbRegistrationRequiredAttributesForFamilies.Items.Add(new ListItem(groupTypeFamilyAttribute.Name, groupTypeFamilyAttribute.Value)); lbRegistrationOptionalAttributesForFamilies.Items.Add(new ListItem(groupTypeFamilyAttribute.Name, groupTypeFamilyAttribute.Value)); } }
public List <StatementGeneratorRecipient> GetStatementGeneratorRecipients([FromBody] StatementGeneratorOptions options) { if (options == null) { throw new Exception("StatementGenerationOption options must be specified"); } using (var rockContext = new RockContext()) { var financialTransactionQry = GetFinancialTransactionQuery(options, rockContext, true); var financialPledgeQry = GetFinancialPledgeQuery(options, rockContext, true); // Get distinct Giving Groups for Persons that have a specific GivingGroupId and have transactions that match the filter // These are Persons that give as part of a Group.For example, Husband and Wife var qryGivingGroupIdsThatHaveTransactions = financialTransactionQry.Select(a => a.AuthorizedPersonAlias.Person.GivingGroupId).Where(a => a.HasValue) .Select(a => new { PersonId = ( int? )null, GroupId = a.Value }).Distinct(); var qryGivingGroupIdsThatHavePledges = financialPledgeQry.Select(a => a.PersonAlias.Person.GivingGroupId).Where(a => a.HasValue) .Select(a => new { PersonId = ( int? )null, GroupId = a.Value }).Distinct(); // Get Persons and their GroupId(s) that do not have GivingGroupId and have transactions that match the filter. // These are the persons that give as individuals vs as part of a group. We need the Groups (families they belong to) in order // to determine which address(es) the statements need to be mailed to var groupTypeIdFamily = GroupTypeCache.GetFamilyGroupType().Id; var groupMembersQry = new GroupMemberService(rockContext).Queryable().Where(m => m.Group.GroupTypeId == groupTypeIdFamily); var qryIndividualGiversThatHaveTransactions = financialTransactionQry .Where(a => !a.AuthorizedPersonAlias.Person.GivingGroupId.HasValue) .Select(a => a.AuthorizedPersonAlias.PersonId).Distinct() .Join(groupMembersQry, p => p, m => m.PersonId, (p, m) => new { PersonId = ( int? )p, GroupId = m.GroupId }); var qryIndividualGiversThatHavePledges = financialPledgeQry .Where(a => !a.PersonAlias.Person.GivingGroupId.HasValue) .Select(a => a.PersonAlias.PersonId).Distinct() .Join(groupMembersQry, p => p, m => m.PersonId, (p, m) => new { PersonId = ( int? )p, GroupId = m.GroupId }); var unionQry = qryGivingGroupIdsThatHaveTransactions.Union(qryIndividualGiversThatHaveTransactions); if (options.PledgesAccountIds.Any()) { unionQry = unionQry.Union(qryGivingGroupIdsThatHavePledges).Union(qryIndividualGiversThatHavePledges); } /* Limit to Mailing Address and sort by ZipCode */ IQueryable <GroupLocation> groupLocationsQry = GetGroupLocationQuery(rockContext); // Do an outer join on location so we can include people that don't have an address (if options.IncludeIndividualsWithNoAddress) // var unionJoinLocationQry = from pg in unionQry join l in groupLocationsQry on pg.GroupId equals l.GroupId into u from l in u.DefaultIfEmpty() select new { pg.PersonId, pg.GroupId, LocationGuid = ( Guid? )l.Location.Guid, l.Location.PostalCode }; // Require that LocationId has a value unless this is for a specific person, a dataview, or the IncludeIndividualsWithNoAddress option is enabled if (options.PersonId == null && options.DataViewId == null && !options.IncludeIndividualsWithNoAddress) { unionJoinLocationQry = unionJoinLocationQry.Where(a => a.LocationGuid.HasValue); } if (options.OrderBy == OrderBy.PostalCode) { unionJoinLocationQry = unionJoinLocationQry.OrderBy(a => a.PostalCode); } else if (options.OrderBy == OrderBy.LastName) { // get a query to look up LastName for recipients that give as a group var qryLastNameAsGroup = new PersonService(rockContext).Queryable(false, true) .Where(a => a.GivingLeaderId == a.Id && a.GivingGroupId.HasValue) .Select(a => new { a.GivingGroupId, a.LastName, a.FirstName }); // get a query to look up LastName for recipients that give as individuals var qryLastNameAsIndividual = new PersonService(rockContext).Queryable(false, true); unionJoinLocationQry = unionJoinLocationQry.Select(a => new { a.PersonId, a.GroupId, a.LocationGuid, a.PostalCode, GivingLeader = a.PersonId.HasValue ? qryLastNameAsIndividual.Where(p => p.Id == a.PersonId).Select(x => new { x.LastName, x.FirstName }).FirstOrDefault() : qryLastNameAsGroup.Where(gl => gl.GivingGroupId == a.GroupId).Select(x => new { x.LastName, x.FirstName }).FirstOrDefault() }).OrderBy(a => a.GivingLeader.LastName).ThenBy(a => a.GivingLeader.FirstName) .Select(a => new { a.PersonId, a.GroupId, a.LocationGuid, a.PostalCode }); } var givingIdsQry = unionJoinLocationQry.Select(a => new { a.PersonId, a.GroupId, a.LocationGuid }); var recipientList = givingIdsQry.ToList().Select(a => new StatementGeneratorRecipient { GroupId = a.GroupId, PersonId = a.PersonId, LocationGuid = a.LocationGuid }).ToList(); if (options.DataViewId.HasValue) { var dataView = new DataViewService(new RockContext()).Get(options.DataViewId.Value); if (dataView != null) { List <string> errorMessages = new List <string>(); var personList = dataView.GetQuery(null, null, out errorMessages).OfType <Rock.Model.Person>().Select(a => new { a.Id, a.GivingGroupId }).ToList(); HashSet <int> personIds = new HashSet <int>(personList.Select(a => a.Id)); HashSet <int> groupsIds = new HashSet <int>(personList.Where(a => a.GivingGroupId.HasValue).Select(a => a.GivingGroupId.Value).Distinct()); foreach (var recipient in recipientList.ToList()) { if (recipient.PersonId.HasValue) { if (!personIds.Contains(recipient.PersonId.Value)) { recipientList.Remove(recipient); } } else { if (!groupsIds.Contains(recipient.GroupId)) { recipientList.Remove(recipient); } } } } } return(recipientList); } }
/// <summary> /// Shows the edit person details. /// </summary> /// <param name="personGuid">The person's global unique identifier.</param> private void ShowEditPersonDetails(Person person) { var childGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid(); RockContext rockContext = new RockContext(); RoleType = null; rblRole.DataSource = GroupTypeCache.GetFamilyGroupType().Roles.OrderBy(r => r.Order).ToList(); rblRole.DataBind(); rblRole.Visible = true; rblRole.Required = true; if (GetAttributeValue("DisableNameEdit").AsBoolean()) { tbFirstName.Enabled = false; tbLastName.Enabled = false; } imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonNoPictureUrl(person, 200, 200); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); var familyRole = person.GetFamilyRole(); rblRole.SelectedValue = familyRole != null?familyRole.Id.ToString() : "0"; if (person.Id != 0 && person.GetFamilyRole().Guid == childGuid) { _IsEditRecordAdult = false; tbEmail.Required = false; // don't display campus selector to children. cpCampus.Visible = false; if (person.GraduationYear.HasValue) { ypGraduation.SelectedYear = person.GraduationYear.Value; } else { ypGraduation.SelectedYear = null; } ddlGradePicker.Visible = true; if (!person.HasGraduated ?? false) { int gradeOffset = person.GradeOffset.Value; var maxGradeOffset = ddlGradePicker.MaxGradeOffset; // keep trying until we find a Grade that has a gradeOffset that includes the Person's gradeOffset (for example, there might be combined grades) while (!ddlGradePicker.Items.OfType <ListItem>().Any(a => a.Value.AsInteger() == gradeOffset) && gradeOffset <= maxGradeOffset) { gradeOffset++; } ddlGradePicker.SetValue(gradeOffset); } else { ddlGradePicker.SelectedIndex = 0; } } else { _IsEditRecordAdult = true; bool requireEmail = GetAttributeValue("RequireAdultEmailAddress").AsBoolean(); tbEmail.Required = requireEmail; ddlGradePicker.Visible = false; // show/hide campus selector bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean(); cpCampus.Visible = showCampus; if (showCampus) { cpCampus.Campuses = CampusCache.All(false); cpCampus.SetValue(person.GetCampus()); } } tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString(false); rblCommunicationPreference.Visible = this.GetAttributeValue("ShowCommunicationPreference").AsBoolean(); rblCommunicationPreference.SetValue(person.CommunicationPreference == CommunicationType.SMS ? "2" : "1"); // Family Attributes if (person.Id == CurrentPerson.Id) { Guid?locationTypeGuid = GetAttributeValue("AddressType").AsGuidOrNull(); if (locationTypeGuid.HasValue) { pnlAddress.Visible = true; var addressTypeDv = DefinedValueCache.Get(locationTypeGuid.Value); lAddressTitle.Text = addressTypeDv.Value + " Address"; var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if (familyGroupTypeGuid.HasValue) { var familyGroupType = GroupTypeCache.Get(familyGroupTypeGuid.Value); var familyAddress = new GroupLocationService(rockContext).Queryable() .Where(l => l.Group.GroupTypeId == familyGroupType.Id && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any(m => m.PersonId == person.Id)) .FirstOrDefault(); if (familyAddress != null) { acAddress.SetValues(familyAddress.Location); } } } } else { pnlAddress.Visible = false; } BindPhoneNumbers(person); pnlEdit.Visible = true; if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean()) { cbTOS.Visible = true; cbTOS.Required = true; cbTOS.Text = GetAttributeValue(AttributeKeys.TermsOfServiceText); } }
/// <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); }
private void CreateControls(bool setSelection) { // Load all the attribute controls attributeControls.Clear(); pnlAttributes.Controls.Clear(); phDuplicates.Controls.Clear(); var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); var locationService = new LocationService(rockContext); foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false)) { Guid guid = Guid.Empty; if (Guid.TryParse(categoryGuid, out guid)) { var category = CategoryCache.Read(guid); if (category != null) { var attributeControl = new NewFamilyAttributes(); attributeControl.ClearRows(); pnlAttributes.Controls.Add(attributeControl); attributeControls.Add(attributeControl); attributeControl.ID = "familyAttributes_" + category.Id.ToString(); attributeControl.CategoryId = category.Id; foreach (var attribute in attributeService.GetByCategoryId(category.Id)) { if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson)) { attributeControl.AttributeList.Add(AttributeCache.Read(attribute)); } } } } } nfmMembers.ClearRows(); nfciContactInfo.ClearRows(); var groupMemberService = new GroupMemberService(rockContext); var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; var homeLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid(); var location = new Location(); acAddress.GetValues(location); foreach (var familyMember in FamilyMembers) { string familyMemberGuidString = familyMember.Person.Guid.ToString().Replace("-", "_"); var familyMemberRow = new NewFamilyMembersRow(); nfmMembers.Controls.Add(familyMemberRow); familyMemberRow.ID = string.Format("row_{0}", familyMemberGuidString); familyMemberRow.RoleUpdated += familyMemberRow_RoleUpdated; familyMemberRow.DeleteClick += familyMemberRow_DeleteClick; familyMemberRow.PersonGuid = familyMember.Person.Guid; familyMemberRow.RequireGender = nfmMembers.RequireGender; familyMemberRow.RequireGrade = nfmMembers.RequireGrade; familyMemberRow.RoleId = familyMember.GroupRoleId; familyMemberRow.ShowGrade = familyMember.GroupRoleId == _childRoleId; familyMemberRow.ValidationGroup = BlockValidationGroup; var contactInfoRow = new NewFamilyContactInfoRow(); nfciContactInfo.Controls.Add(contactInfoRow); contactInfoRow.ID = string.Format("ci_row_{0}", familyMemberGuidString); contactInfoRow.PersonGuid = familyMember.Person.Guid; contactInfoRow.IsMessagingEnabled = _SMSEnabled; contactInfoRow.PersonName = familyMember.Person.FullName; if (_homePhone != null) { var homePhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault(); if (homePhoneNumber != null) { contactInfoRow.HomePhoneNumber = PhoneNumber.FormattedNumber(homePhoneNumber.CountryCode, homePhoneNumber.Number); contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode; } } if (_cellPhone != null) { var cellPhoneNumber = familyMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault(); if (cellPhoneNumber != null) { contactInfoRow.CellPhoneNumber = PhoneNumber.FormattedNumber(cellPhoneNumber.CountryCode, cellPhoneNumber.Number); contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode; } } contactInfoRow.Email = familyMember.Person.Email; if (setSelection) { if (familyMember.Person != null) { familyMemberRow.TitleValueId = familyMember.Person.TitleValueId; familyMemberRow.FirstName = familyMember.Person.FirstName; familyMemberRow.LastName = familyMember.Person.LastName; familyMemberRow.SuffixValueId = familyMember.Person.SuffixValueId; familyMemberRow.Gender = familyMember.Person.Gender; familyMemberRow.BirthDate = familyMember.Person.BirthDate; familyMemberRow.ConnectionStatusValueId = familyMember.Person.ConnectionStatusValueId; familyMemberRow.GradeOffset = familyMember.Person.GradeOffset; } } foreach (var attributeControl in attributeControls) { var attributeRow = new NewFamilyAttributesRow(); attributeControl.Controls.Add(attributeRow); attributeRow.ID = string.Format("{0}_{1}", attributeControl.ID, familyMemberGuidString); attributeRow.AttributeList = attributeControl.AttributeList; attributeRow.PersonGuid = familyMember.Person.Guid; attributeRow.PersonName = familyMember.Person.FullName; if (setSelection) { attributeRow.SetEditValues(familyMember.Person); } } if (Duplicates.ContainsKey(familyMember.Person.Guid)) { var dupRow = new HtmlGenericControl("div"); dupRow.AddCssClass("row"); dupRow.ID = string.Format("dupRow_{0}", familyMemberGuidString); phDuplicates.Controls.Add(dupRow); var newPersonCol = new HtmlGenericControl("div"); newPersonCol.AddCssClass("col-md-6"); newPersonCol.ID = string.Format("newPersonCol_{0}", familyMemberGuidString); dupRow.Controls.Add(newPersonCol); newPersonCol.Controls.Add(PersonHtmlPanel( familyMemberGuidString, familyMember.Person, familyMember.GroupRole, location, rockContext)); LinkButton lbRemoveMember = new LinkButton(); lbRemoveMember.ID = string.Format("lbRemoveMember_{0}", familyMemberGuidString); lbRemoveMember.AddCssClass("btn btn-danger btn-xs"); lbRemoveMember.Text = "Remove"; lbRemoveMember.Click += lbRemoveMember_Click; newPersonCol.Controls.Add(lbRemoveMember); var dupPersonCol = new HtmlGenericControl("div"); dupPersonCol.AddCssClass("col-md-6"); dupPersonCol.ID = string.Format("dupPersonCol_{0}", familyMemberGuidString); dupRow.Controls.Add(dupPersonCol); var duplicateHeader = new HtmlGenericControl("h4"); duplicateHeader.InnerText = "Possible Duplicate Records"; dupPersonCol.Controls.Add(duplicateHeader); foreach (var duplicate in Duplicates[familyMember.Person.Guid]) { GroupTypeRole groupTypeRole = null; Location duplocation = null; var familyGroupMember = groupMemberService.Queryable() .Where(a => a.PersonId == duplicate.Id) .Where(a => a.Group.GroupTypeId == familyGroupType.Id) .Select(s => new { s.GroupRole, GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid == homeLocationGuid).Select(a => a.Location).FirstOrDefault() }) .FirstOrDefault(); if (familyGroupMember != null) { groupTypeRole = familyGroupMember.GroupRole; duplocation = familyGroupMember.GroupLocation; } dupPersonCol.Controls.Add(PersonHtmlPanel( familyMemberGuidString, duplicate, groupTypeRole, duplocation, rockContext)); } } } ShowPage(); }
/// <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(); }
/// <summary> /// Shows the report. /// </summary> private void ShowMap() { string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: var(--border-radius-base); }} </style>"; lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight")); // add styling to map string styleCode = "null"; DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid()); if (dvcMapStyle != null) { styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); } var polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string polygonColors = polygonColorList.AsDelimited(","); string latitude = "39.8282"; string longitude = "-98.5795"; string zoom = "4"; var orgLocation = GlobalAttributesCache.Get().OrganizationLocation; if (orgLocation != null && orgLocation.GeoPoint != null) { latitude = orgLocation.GeoPoint.Latitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")); longitude = orgLocation.GeoPoint.Longitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")); zoom = "12"; } var rockContext = new RockContext(); var campuses = CampusCache.All(); var locationService = new LocationService(rockContext); CampusMarkersData = string.Empty; if (cbShowCampusLocations.Checked) { foreach (var campus in campuses) { if (campus.LocationId.HasValue) { var location = locationService.Get(campus.LocationId.Value); if (location != null && location.GeoPoint != null) { CampusMarkersData += string.Format("{{ location: new google.maps.LatLng({0},{1}), campusName:'{2}' }},", location.GeoPoint.Latitude, location.GeoPoint.Longitude, campus.Name); } } } CampusMarkersData.TrimEnd(new char[] { ',' }); } // show geofences if a group was specified this.GroupId = this.PageParameter("GroupId").AsIntegerOrNull(); if (!this.GroupId.HasValue && gpGroupToMap.Visible) { // if a page parameter wasn't specified, use the selected group from the filter this.GroupId = gpGroupToMap.SelectedValue.AsIntegerOrNull(); } var groupMemberService = new GroupMemberService(rockContext); var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); int groupLocationTypeHomeId = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0; var groupTypeFamily = GroupTypeCache.GetFamilyGroupType(); int groupTypeFamilyId = groupTypeFamily != null ? groupTypeFamily.Id : 0; // if there is a DataViewId page parameter, use that instead of the Block or Filter dataview setting (the filter control won't be visible if there is a DataViewId page parameter) int? dataViewId = this.PageParameter("DataViewId").AsIntegerOrNull(); Guid?dataViewGuid = null; if (!dataViewId.HasValue) { dataViewGuid = this.GetAttributeValue("DataView").AsGuidOrNull(); } if (ddlUserDataView.Visible) { dataViewGuid = ddlUserDataView.SelectedValue.AsGuidOrNull(); } IQueryable <int> qryPersonIds = null; if (dataViewId.HasValue || dataViewGuid.HasValue) { DataView dataView = null; // if a DataViewId page parameter was specified, use that, otherwise use the blocksetting or filter selection if (dataViewId.HasValue) { dataView = new DataViewService(rockContext).Get(dataViewId.Value); } else { dataView = new DataViewService(rockContext).Get(dataViewGuid.Value); } if (dataView != null) { List <string> errorMessages; qryPersonIds = dataView.GetQuery(null, rockContext, null, out errorMessages).OfType <Person>().Select(a => a.Id); } } if (qryPersonIds == null) { // if no dataview was specified, show nothing qryPersonIds = new PersonService(rockContext).Queryable().Where(a => false).Select(a => a.Id); } var qryGroupMembers = groupMemberService.Queryable(); var campusIds = cpCampuses.SelectedCampusIds; if (campusIds.Any()) { qryGroupMembers = qryGroupMembers.Where(a => a.Group.CampusId.HasValue && campusIds.Contains(a.Group.CampusId.Value)); } var qryLocationGroupMembers = qryGroupMembers .Where(a => a.Group.GroupTypeId == groupTypeFamilyId) .Where(a => a.Group.IsActive) .Select(a => new { GroupGeoPoint = a.Group.GroupLocations.Where(gl => gl.IsMappedLocation && gl.GroupLocationTypeValueId == groupLocationTypeHomeId && gl.Location.IsActive && gl.Location.GeoPoint != null).Select(x => x.Location.GeoPoint).FirstOrDefault(), a.Group.CampusId, a.PersonId }) .Where(a => (a.GroupGeoPoint != null) && qryPersonIds.Contains(a.PersonId)) .GroupBy(a => new { a.GroupGeoPoint.Latitude, a.GroupGeoPoint.Longitude }) .Select(s => new { s.Key.Longitude, s.Key.Latitude, MemberCount = s.Count() }); var locationList = qryLocationGroupMembers.ToList() .Select(a => new LatLongWeighted(a.Latitude.Value, a.Longitude.Value, a.MemberCount)) .ToList(); List <LatLongWeighted> points = locationList; // cluster points that are close together double?milesPerGrouping = this.GetAttributeValue("PointGrouping").AsDoubleOrNull(); if (!milesPerGrouping.HasValue) { // default to a 1/10th of a mile milesPerGrouping = 0.10; } if (milesPerGrouping.HasValue && milesPerGrouping > 0) { var metersPerLatitudePHX = 110886.79; var metersPerLongitudePHX = 94493.11; double metersPerMile = 1609.34; var squareLengthHeightMeters = metersPerMile * milesPerGrouping.Value; var longitudeRoundFactor = metersPerLongitudePHX / squareLengthHeightMeters; var latitudeRoundFactor = metersPerLatitudePHX / squareLengthHeightMeters; // average the Lat/Lng, but make sure to round to 8 decimal points (otherwise Google Maps will silently not show the points due to too high of decimal precision) points = points.GroupBy(a => new { rLat = Math.Round(a.Lat * latitudeRoundFactor), rLong = Math.Round(a.Lat * longitudeRoundFactor), }).Select(a => new LatLongWeighted(Math.Round(a.Average(x => x.Lat), 8), Math.Round(a.Average(x => x.Long), 8), a.Sum(x => x.Weight))).ToList(); } this.HeatMapData = points.Select(a => a.Weight > 1 ? string.Format("{{ location: new google.maps.LatLng({0}, {1}), weight: {2} }}", a.Lat, a.Long, a.Weight) : string.Format("new google.maps.LatLng({0}, {1})", a.Lat, a.Long)).ToList().AsDelimited(",\n"); StyleCode = styleCode; hfPolygonColors.Value = polygonColors; hfCenterLatitude.Value = latitude.ToString(); hfCenterLongitude.Value = longitude.ToString(); hfZoom.Value = zoom.ToString(); }
/// <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).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.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; 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); }
/// <summary> /// Saves the family and persons to the database /// </summary> /// <param name="kioskCampusId">The kiosk campus identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext) { SaveResult saveResult = new SaveResult(); FamilyRegistrationState editFamilyState = this; var personService = new PersonService(rockContext); var groupService = new GroupService(rockContext); var recordTypePersonId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var maritalStatusMarried = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid()); var maritalStatusSingle = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_SINGLE.AsGuid()); var numberTypeValueMobile = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()); int groupTypeRoleAdultId = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id; int groupTypeRoleChildId = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id; int?groupTypeRoleCanCheckInId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()) ?.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN.AsGuid())?.Id; bool?groupTypeDefaultSmsEnabled = GroupTypeCache.GetFamilyGroupType().GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBooleanOrNull(); Group primaryFamily = null; if (editFamilyState.GroupId.HasValue) { primaryFamily = groupService.Get(editFamilyState.GroupId.Value); } // see if we can find matches for new people that were added, and also set the primary family if this is a new family, but a matching family was found foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.PersonId.HasValue && !a.IsDeleted)) { var personQuery = new PersonService.PersonMatchQuery(familyPersonState.FirstName, familyPersonState.LastName, familyPersonState.Email, familyPersonState.MobilePhoneNumber, familyPersonState.Gender, familyPersonState.BirthDate, familyPersonState.SuffixValueId); var matchingPerson = personService.FindPerson(personQuery, true); if (matchingPerson != null) { // newly added person, but a match was found, so set the PersonId, GroupId, and ConnectionStatusValueID to the matching person instead of creating a new person familyPersonState.PersonId = matchingPerson.Id; familyPersonState.GroupId = matchingPerson.GetFamily(rockContext)?.Id; familyPersonState.RecordStatusValueId = matchingPerson.RecordStatusValueId; familyPersonState.ConnectionStatusValueId = matchingPerson.ConnectionStatusValueId; familyPersonState.ConvertedToMatchedPerson = true; if (primaryFamily == null && familyPersonState.IsAdult) { // if this is a new family, but we found a matching adult person, use that person's family as the family primaryFamily = matchingPerson.GetFamily(rockContext); } } } // loop thru all people and add/update as needed foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted)) { Person person; if (!familyPersonState.PersonId.HasValue) { person = new Person(); personService.Add(person); saveResult.NewPersonList.Add(person); person.RecordTypeValueId = recordTypePersonId; person.FirstName = familyPersonState.FirstName; } else { person = personService.Get(familyPersonState.PersonId.Value); } // NOTE, Gender, MaritalStatusValueId, NickName, LastName are required fields so, always updated them to match the UI (even if a matched person was found) person.Gender = familyPersonState.Gender; person.MaritalStatusValueId = familyPersonState.IsMarried ? maritalStatusMarried.Id : maritalStatusSingle.Id; person.NickName = familyPersonState.FirstName; person.LastName = familyPersonState.LastName; // if the familyPersonState was converted to a Matched Person, don't overwrite existing values with blank values var saveEmptyValues = !familyPersonState.ConvertedToMatchedPerson; if (familyPersonState.SuffixValueId.HasValue || saveEmptyValues) { person.SuffixValueId = familyPersonState.SuffixValueId; } if (familyPersonState.BirthDate.HasValue || saveEmptyValues) { person.SetBirthDate(familyPersonState.BirthDate); } if (familyPersonState.Email.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.Email = familyPersonState.Email; } if (familyPersonState.GradeOffset.HasValue || saveEmptyValues) { person.GradeOffset = familyPersonState.GradeOffset; } // if a matching person was found, the familyPersonState's RecordStatusValueId and ConnectinoStatusValueId was already updated to match the matched person person.RecordStatusValueId = familyPersonState.RecordStatusValueId; person.ConnectionStatusValueId = familyPersonState.ConnectionStatusValueId; rockContext.SaveChanges(); bool isNewPerson = !familyPersonState.PersonId.HasValue; if (!familyPersonState.PersonId.HasValue) { // if we added a new person, we know now the personId after SaveChanges, so set it familyPersonState.PersonId = person.Id; } if (familyPersonState.AlternateID.IsNotNullOrWhiteSpace()) { PersonSearchKey personAlternateValueIdSearchKey; PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext); if (isNewPerson) { // if we added a new person, a default AlternateId was probably added in the service layer. If a specific Alternate ID was specified, make sure that their SearchKey is updated personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId).FirstOrDefault(); } else { // see if the key already exists. If if it doesn't already exist, let a new one get created personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId && a.SearchValue == familyPersonState.AlternateID).FirstOrDefault(); } if (personAlternateValueIdSearchKey == null) { personAlternateValueIdSearchKey = new PersonSearchKey(); personAlternateValueIdSearchKey.PersonAliasId = person.PrimaryAliasId; personAlternateValueIdSearchKey.SearchTypeValueId = _personSearchAlternateValueId; personSearchKeyService.Add(personAlternateValueIdSearchKey); } if (personAlternateValueIdSearchKey.SearchValue != familyPersonState.AlternateID) { personAlternateValueIdSearchKey.SearchValue = familyPersonState.AlternateID; rockContext.SaveChanges(); } } person.LoadAttributes(); foreach (var attributeValue in familyPersonState.PersonAttributeValuesState) { // only set attribute values that are editable so we don't accidently delete any attribute values if (familyPersonState.EditableAttributes.Contains(attributeValue.Value.AttributeId)) { if (attributeValue.Value.Value.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.SetAttributeValue(attributeValue.Key, attributeValue.Value.Value); } } } person.SaveAttributeValues(rockContext); if (familyPersonState.MobilePhoneNumber.IsNotNullOrWhiteSpace() || saveEmptyValues) { person.UpdatePhoneNumber(numberTypeValueMobile.Id, familyPersonState.MobilePhoneCountryCode, familyPersonState.MobilePhoneNumber, familyPersonState.MobilePhoneSmsEnabled ?? groupTypeDefaultSmsEnabled, false, rockContext); } rockContext.SaveChanges(); } if (primaryFamily == null) { // new family and no family found by looking up matching adults, so create a new family primaryFamily = new Group(); var familyLastName = editFamilyState.FamilyPersonListState.OrderBy(a => a.IsAdult).Where(a => !a.IsDeleted).Select(a => a.LastName).FirstOrDefault(); primaryFamily.Name = familyLastName + " Family"; primaryFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Set the Campus to the Campus of this Kiosk primaryFamily.CampusId = kioskCampusId; groupService.Add(primaryFamily); saveResult.NewFamilyList.Add(primaryFamily); rockContext.SaveChanges(); } if (!editFamilyState.GroupId.HasValue) { editFamilyState.GroupId = primaryFamily.Id; } primaryFamily.LoadAttributes(); foreach (var familyAttribute in editFamilyState.FamilyAttributeValuesState) { // only set attribute values that are editable so we don't accidently delete any attribute values if (editFamilyState.EditableFamilyAttributes.Contains(familyAttribute.Value.AttributeId)) { primaryFamily.SetAttributeValue(familyAttribute.Key, familyAttribute.Value.Value); } } primaryFamily.SaveAttributeValues(rockContext); var groupMemberService = new GroupMemberService(rockContext); // loop thru all people that are part of the same family (in the UI) and ensure they are all in the same primary family (in the database) foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily)) { var currentFamilyMember = primaryFamily.Members.FirstOrDefault(m => m.PersonId == familyPersonState.PersonId.Value); if (currentFamilyMember == null) { currentFamilyMember = new GroupMember { GroupId = primaryFamily.Id, PersonId = familyPersonState.PersonId.Value, GroupMemberStatus = GroupMemberStatus.Active }; if (familyPersonState.IsAdult) { currentFamilyMember.GroupRoleId = groupTypeRoleAdultId; } else { currentFamilyMember.GroupRoleId = groupTypeRoleChildId; } groupMemberService.Add(currentFamilyMember); rockContext.SaveChanges(); } } // make a dictionary of new related families (by lastname) so we can combine any new related children into a family with the same last name Dictionary <string, Group> newRelatedFamilies = new Dictionary <string, Group>(StringComparer.OrdinalIgnoreCase); // loop thru all people that are NOT part of the same family foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily == false)) { if (!familyPersonState.GroupId.HasValue) { // related person not in a family yet Group relatedFamily = newRelatedFamilies.GetValueOrNull(familyPersonState.LastName); if (relatedFamily == null) { relatedFamily = new Group(); relatedFamily.Name = familyPersonState.LastName + " Family"; relatedFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; // Set the Campus to the Campus of this Kiosk relatedFamily.CampusId = kioskCampusId; newRelatedFamilies.Add(familyPersonState.LastName, relatedFamily); groupService.Add(relatedFamily); saveResult.NewFamilyList.Add(relatedFamily); } rockContext.SaveChanges(); familyPersonState.GroupId = relatedFamily.Id; var familyMember = new GroupMember { GroupId = relatedFamily.Id, PersonId = familyPersonState.PersonId.Value, GroupMemberStatus = GroupMemberStatus.Active }; if (familyPersonState.IsAdult) { familyMember.GroupRoleId = groupTypeRoleAdultId; } else { familyMember.GroupRoleId = groupTypeRoleChildId; } groupMemberService.Add(familyMember); } // ensure there are known relationships between each adult in the primary family to this person that isn't in the primary family foreach (var primaryFamilyAdult in editFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.InPrimaryFamily)) { groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, familyPersonState.ChildRelationshipToAdult); // if this is something other than the CanCheckIn relationship, but is a relationship that should ensure a CanCheckIn relationship, create a CanCheckinRelationship if (groupTypeRoleCanCheckInId.HasValue && familyPersonState.CanCheckIn && groupTypeRoleCanCheckInId != familyPersonState.ChildRelationshipToAdult) { groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, groupTypeRoleCanCheckInId.Value); } } } return(saveResult); }
/// <summary> /// Does cleanup of Person Aliases and Metaphones /// </summary> /// <param name="dataMap">The data map.</param> private void PersonCleanup(JobDataMap dataMap) { // Add any missing person aliases using (var personRockContext = new Rock.Data.RockContext()) { PersonService personService = new PersonService(personRockContext); PersonAliasService personAliasService = new PersonAliasService(personRockContext); var personAliasServiceQry = personAliasService.Queryable(); foreach (var person in personService.Queryable("Aliases") .Where(p => !p.Aliases.Any() && !personAliasServiceQry.Any(pa => pa.AliasPersonId == p.Id)) .Take(300)) { person.Aliases.Add(new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid }); } personRockContext.SaveChanges(); } AddMissingAlternateIds(); using (var personRockContext = new Rock.Data.RockContext()) { PersonService personService = new PersonService(personRockContext); // Add any missing metaphones int namesToProcess = dataMap.GetString("MaxMetaphoneNames").AsIntegerOrNull() ?? 500; if (namesToProcess > 0) { var firstNameQry = personService.Queryable().Select(p => p.FirstName).Where(p => p != null); var nickNameQry = personService.Queryable().Select(p => p.NickName).Where(p => p != null); var lastNameQry = personService.Queryable().Select(p => p.LastName).Where(p => p != null); var nameQry = firstNameQry.Union(nickNameQry.Union(lastNameQry)); var metaphones = personRockContext.Metaphones; var existingNames = metaphones.Select(m => m.Name).Distinct(); // Get the names that have not yet been processed var namesToUpdate = nameQry .Where(n => !existingNames.Contains(n)) .Take(namesToProcess) .ToList(); foreach (string name in namesToUpdate) { string mp1 = string.Empty; string mp2 = string.Empty; Rock.Utility.DoubleMetaphone.doubleMetaphone(name, ref mp1, ref mp2); var metaphone = new Metaphone(); metaphone.Name = name; metaphone.Metaphone1 = mp1; metaphone.Metaphone2 = mp2; metaphones.Add(metaphone); } personRockContext.SaveChanges(disablePrePostProcessing: true); } } // Ensures the PrimaryFamily is correct for all person records in the database using (var personRockContext = new Rock.Data.RockContext()) { int primaryFamilyUpdates = PersonService.UpdatePrimaryFamilyAll(personRockContext); } // update any updated or incorrect age classifications on persons using (var personRockContext = new Rock.Data.RockContext()) { int ageClassificationUpdates = PersonService.UpdatePersonAgeClassificationAll(personRockContext); } //// Add any missing Implied/Known relationship groups // Known Relationship Group AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS), Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()); // Implied Relationship Group AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK), Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()); // Find family groups that have no members or that have only 'inactive' people (record status) and mark the groups inactive. using (var familyRockContext = new Rock.Data.RockContext()) { int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; int recordStatusInactiveValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()).Id; var activeFamilyWithNoActiveMembers = new GroupService(familyRockContext).Queryable() .Where(a => a.GroupTypeId == familyGroupTypeId && a.IsActive == true) .Where(a => !a.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveValueId).Any()); var currentDateTime = RockDateTime.Now; familyRockContext.BulkUpdate(activeFamilyWithNoActiveMembers, x => new Rock.Model.Group { IsActive = false }); } }
private void BindGrid() { string type = PageParameter("SearchType"); string term = PageParameter("SearchTerm"); if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term)) { term = term.Trim(); type = type.Trim(); var rockContext = new RockContext(); var personService = new PersonService(rockContext); IQueryable <Person> people = null; switch (type.ToLower()) { case ("name"): { bool allowFirstNameOnly = false; if (!bool.TryParse(PageParameter("AllowFirstNameOnly"), out allowFirstNameOnly)) { allowFirstNameOnly = false; } people = personService.GetByFullName(term, allowFirstNameOnly, true); break; } case ("phone"): { var phoneService = new PhoneNumberService(rockContext); var phoneNumberPersonIds = phoneService.GetPersonIdsByNumber(term); people = personService.Queryable(new PersonService.PersonQueryOptions { IncludeNameless = true }).Where(p => phoneNumberPersonIds.Contains(p.Id)); break; } case ("address"): { var groupMemberService = new GroupMemberService(rockContext); var groupMemberPersonIds = groupMemberService.GetPersonIdsByHomeAddress(term); people = personService.Queryable().Where(p => groupMemberPersonIds.Contains(p.Id)); break; } case ("email"): { var emailSearchTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_EMAIL.AsGuid()); var searchKeyQry = new PersonSearchKeyService(rockContext).Queryable(); people = personService.Queryable() .Where(p => (term != "" && p.Email.Contains(term)) || searchKeyQry.Any(a => emailSearchTypeValueId.HasValue && a.SearchTypeValueId == emailSearchTypeValueId.Value && a.PersonAlias.PersonId == p.Id && a.SearchValue.Contains(term))); break; } case ("birthdate"): { DateTime?birthDate = Request.QueryString["birthdate"].AsDateTime(); int? personId = Request.QueryString["person-id"].AsIntegerOrNull(); if (birthDate == null) { birthDate = term.AsDateTime(); } if (personId.HasValue) { people = personService.Queryable().Where(a => a.Id == personId.Value); } else { people = personService.Queryable().Where(p => p.BirthDate.HasValue && birthDate.HasValue && p.BirthDate == birthDate.Value); } break; } } IEnumerable <int> personIdList = people.Select(p => p.Id); // just leave the personIdList as a Queryable if it is over 10000 so that we don't throw a SQL exception due to the big list of ids if (people.Count() < 10000) { personIdList = personIdList.ToList(); } if (personIdList.Count() == 1) { // if there is exactly one result, just redirect to the person page int personId = personIdList.First(); Response.Redirect(string.Format("~/Person/{0}", personId), false); Context.ApplicationInstance.CompleteRequest(); return; } // since there is not exactly one person found, show the list of people in the grid var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int familyGroupTypeId = familyGroupType != null ? familyGroupType.Id : 0; var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); int homeAddressTypeId = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0; var birthDateCol = gPeople.ColumnsOfType <DateField>().First(c => c.DataField == "BirthDate"); var ageCol = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Age"); var genderCol = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Gender"); var envelopeNumberField = gPeople.ColumnsOfType <RockLiteralField>().First(c => c.ID == "lEnvelopeNumber"); var spouseCol = gPeople.ColumnsOfType <RockTemplateField>().First(c => c.HeaderText == "Spouse"); var personGivingEnvelopeAttribute = AttributeCache.Get(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); if (personGivingEnvelopeAttribute != null) { envelopeNumberField.Visible = GlobalAttributesCache.Get().EnableGivingEnvelopeNumber&& this.GetAttributeValue(AttributeKey.ShowEnvelopeNumber).AsBoolean(); } else { envelopeNumberField.Visible = false; } birthDateCol.Visible = GetAttributeValue(AttributeKey.ShowBirthdate).AsBoolean(); ageCol.Visible = GetAttributeValue(AttributeKey.ShowAge).AsBoolean(); genderCol.Visible = GetAttributeValue(AttributeKey.ShowGender).AsBoolean(); spouseCol.Visible = _showSpouse; people = personService.Queryable(true).Where(p => personIdList.Contains(p.Id)); SortProperty sortProperty = gPeople.SortProperty; if (sortProperty != null) { people = people.Sort(sortProperty); } else { people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName); } var personList = people.Select(p => new PersonSearchResult { Id = p.Id, FirstName = p.FirstName, NickName = p.NickName, LastName = p.LastName, BirthDate = p.BirthDate, DeceasedDate = p.DeceasedDate, BirthYear = p.BirthYear, BirthMonth = p.BirthMonth, BirthDay = p.BirthDay, ConnectionStatusValueId = p.ConnectionStatusValueId, RecordStatusValueId = p.RecordStatusValueId, RecordTypeValueId = p.RecordTypeValueId, AgeClassification = p.AgeClassification, SuffixValueId = p.SuffixValueId, IsDeceased = p.IsDeceased, Email = p.Email, Gender = p.Gender, PhotoId = p.PhotoId, CampusIds = p.Members .Where(m => m.Group.GroupTypeId == familyGroupTypeId && m.Group.CampusId.HasValue) .Select(m => m.Group.CampusId.Value) .ToList(), HomeAddresses = p.Members .Where(m => m.Group.GroupTypeId == familyGroupTypeId) .SelectMany(m => m.Group.GroupLocations) .Where(gl => gl.GroupLocationTypeValueId == homeAddressTypeId) .Select(gl => gl.Location), PhoneNumbers = p.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue) .Select(n => new PersonSearchResultPhone { NumberTypeValueId = n.NumberTypeValueId.Value, Number = n.NumberFormatted, PhoneTypeName = n.NumberTypeValue.Value }) .ToList(), TopSignalColor = p.TopSignalColor, TopSignalIconCssClass = p.TopSignalIconCssClass }).ToList(); if (type.ToLower() == "name") { var similarNames = personService.GetSimilarNames(term, personList.Select(p => p.Id).ToList(), true); if (similarNames.Any()) { var hyperlinks = new List <string>(); foreach (string name in similarNames.Distinct()) { var pageRef = CurrentPageReference; pageRef.Parameters["SearchTerm"] = name; hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name)); } string altNames = string.Join(", ", hyperlinks); nbNotice.Text = string.Format("Other Possible Matches: {0}", altNames); nbNotice.Visible = true; } } _inactiveStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); var personIds = personList.Select(a => a.Id).ToList(); if (envelopeNumberField != null && envelopeNumberField.Visible) { _envelopeNumbers = new AttributeValueService(rockContext).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id) .Where(a => personIds.Contains(a.EntityId.Value)) .Select(a => new { PersonId = a.EntityId.Value, Value = a.Value }).ToList().ToDictionary(k => k.PersonId, v => v.Value); } gPeople.EntityTypeId = EntityTypeCache.GetId <Person>(); gPeople.DataSource = personList; gPeople.DataBind(); } }
public bool FindDuplicates() { Duplicates = new Dictionary <Guid, List <Person> >(); var rockContext = new RockContext(); var locationService = new LocationService(rockContext); var groupService = new GroupService(rockContext); var personService = new PersonService(rockContext); // Find any other family members (any family) that have same location var othersAtAddress = new List <int>(); var familyGroupType = GroupTypeCache.GetFamilyGroupType(); string locationKey = GetLocationKey(); if (!string.IsNullOrWhiteSpace(locationKey) && _verifiedLocations.ContainsKey(locationKey)) { int?locationId = _verifiedLocations[locationKey]; if (locationId.HasValue) { var location = locationService.Get(locationId.Value); if (location != null) { othersAtAddress = groupService .Queryable().AsNoTracking() .Where(g => g.GroupTypeId == familyGroupType.Id && g.GroupLocations.Any(l => l.LocationId == location.Id)) .SelectMany(g => g.Members) .Select(m => m.PersonId) .ToList(); } } } foreach (var person in FamilyMembers .Where(m => m.Person != null && m.Person.FirstName != "") .Select(m => m.Person)) { bool otherCriteria = false; var personQry = personService .Queryable().AsNoTracking() .Where(p => p.FirstName == person.FirstName || p.NickName == person.FirstName); if (othersAtAddress.Any()) { personQry = personQry .Where(p => othersAtAddress.Contains(p.Id)); } if (person.BirthDate.HasValue) { otherCriteria = true; personQry = personQry .Where(p => p.BirthDate.HasValue && p.BirthDate.Value == person.BirthDate.Value); } if (_homePhone != null) { var homePhoneNumber = person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault(); if (homePhoneNumber != null) { otherCriteria = true; personQry = personQry .Where(p => p.PhoneNumbers.Any(n => n.NumberTypeValueId == _homePhone.Id && n.Number == homePhoneNumber.Number)); } } if (_cellPhone != null) { var cellPhoneNumber = person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault(); if (cellPhoneNumber != null) { otherCriteria = true; personQry = personQry .Where(p => p.PhoneNumbers.Any(n => n.NumberTypeValueId == _cellPhone.Id && n.Number == cellPhoneNumber.Number)); } } if (!string.IsNullOrWhiteSpace(person.Email)) { otherCriteria = true; personQry = personQry .Where(p => p.Email == person.Email); } var dups = new List <Person>(); if (otherCriteria) { // If a birthday, email, phone, or address was entered, find anyone with same info and same first name dups = personQry.ToList(); } else { // otherwise find people with same first and last name dups = personQry .Where(p => p.LastName == person.LastName) .ToList(); } if (dups.Any()) { Duplicates.Add(person.Guid, dups); } } return(Duplicates.Any()); }
/// <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); tbBusinessName.Text = tbBusinessName.Text.FixCase(); } // 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(); }); var queryParams = new Dictionary <string, string>(); queryParams.Add("businessId", hfBusinessId.Value); NavigateToCurrentPage(queryParams); }
/// <summary> /// Shows edit UI fo the family (or null adding a new family) /// </summary> /// <param name="checkInFamily">The check in family.</param> private void ShowFamilyDetail(CheckInFamily checkInFamily) { if (checkInFamily != null && checkInFamily.Group != null) { this.EditFamilyState = FamilyRegistrationState.FromGroup(checkInFamily.Group); hfGroupId.Value = checkInFamily.Group.Id.ToString(); mdEditFamily.Title = checkInFamily.Group.Name; int groupId = hfGroupId.Value.AsInteger(); var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupMembersQuery = groupMemberService.Queryable(false) .Include(a => a.Person) .Where(a => a.GroupId == groupId) .OrderBy(m => m.GroupRole.Order) .ThenBy(m => m.Person.BirthYear) .ThenBy(m => m.Person.BirthMonth) .ThenBy(m => m.Person.BirthDay) .ThenBy(m => m.Person.Gender); var groupMemberList = groupMembersQuery.ToList(); foreach (var groupMember in groupMemberList) { var familyPersonState = FamilyRegistrationState.FamilyPersonState.FromPerson(groupMember.Person, 0, true); familyPersonState.GroupMemberGuid = groupMember.Guid; familyPersonState.GroupId = groupMember.GroupId; familyPersonState.IsAdult = groupMember.GroupRoleId == _groupTypeRoleAdultId; this.EditFamilyState.FamilyPersonListState.Add(familyPersonState); } var adultIds = this.EditFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.PersonId.HasValue).Select(a => a.PersonId.Value).ToList(); var roleIds = CurrentCheckInState.CheckInType.Registration.KnownRelationships.Where(a => a.Key != 0).Select(a => a.Key).ToList(); IEnumerable <GroupMember> personRelationships = new PersonService(rockContext).GetRelatedPeople(adultIds, roleIds); foreach (GroupMember personRelationship in personRelationships) { if (!this.EditFamilyState.FamilyPersonListState.Any(a => a.PersonId == personRelationship.Person.Id)) { var familyPersonState = FamilyRegistrationState.FamilyPersonState.FromPerson(personRelationship.Person, personRelationship.GroupRoleId, false); familyPersonState.GroupMemberGuid = Guid.NewGuid(); var relatedFamily = personRelationship.Person.GetFamily(); if (relatedFamily != null) { familyPersonState.GroupId = relatedFamily.Id; } familyPersonState.IsAdult = false; familyPersonState.ChildRelationshipToAdult = personRelationship.GroupRoleId; familyPersonState.CanCheckIn = CurrentCheckInState.CheckInType.Registration.KnownRelationshipsCanCheckin.Any(k => k.Key == familyPersonState.ChildRelationshipToAdult); this.EditFamilyState.FamilyPersonListState.Add(familyPersonState); } } BindFamilyMembersGrid(); CreateDynamicFamilyControls(EditFamilyState); ShowFamilyView(); } else { this.EditFamilyState = FamilyRegistrationState.FromGroup(new Group() { GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id }); CreateDynamicFamilyControls(EditFamilyState); hfGroupId.Value = "0"; mdEditFamily.Title = "Add Family"; EditGroupMember(null); } _initialEditFamilyStateHash = this.EditFamilyState.GetStateHash(); // disable any idle redirect blocks that are on the page when the mdEditFamily modal is open DisableIdleRedirectBlocks(true); upContent.Update(); mdEditFamily.Show(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); _groupType = GroupTypeCache.Read(GetAttributeValue("GroupType").AsGuid()); if (_groupType == null) { _groupType = GroupTypeCache.GetFamilyGroupType(); } _groupTypeName = _groupType.Name; _isFamilyGroupType = _groupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()); _locationType = _groupType.LocationTypeValues.FirstOrDefault(v => v.Guid.Equals(GetAttributeValue("LocationType").AsGuid())); if (_locationType == null) { _locationType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME); } if (_isFamilyGroupType) { divGroupName.Visible = false; var campusi = GetAttributeValue("ShowInactiveCampuses").AsBoolean() ? CampusCache.All() : CampusCache.All().Where(c => c.IsActive == true).ToList(); cpCampus.Campuses = campusi; cpCampus.Visible = campusi.Any(); if (campusi.Count == 1) { cpCampus.SelectedCampusId = campusi.FirstOrDefault().Id; } ddlMaritalStatus.Visible = true; ddlMaritalStatus.BindToDefinedType(DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid()), true); var AdultMaritalStatus = DefinedValueCache.Read(GetAttributeValue("AdultMaritalStatus").AsGuid()); if (AdultMaritalStatus != null) { ddlMaritalStatus.SetValue(AdultMaritalStatus.Id); } _childRoleId = _groupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); } else { divGroupName.Visible = true; tbGroupName.Label = _groupTypeName + " Name"; cpCampus.Visible = false; ddlMaritalStatus.Visible = false; } nfmMembers.ShowGrade = _isFamilyGroupType; nfmMembers.RequireGender = GetAttributeValue("Gender").AsBoolean(); nfmMembers.RequireGrade = GetAttributeValue("Grade").AsBoolean(); _SMSEnabled = GetAttributeValue("SMS").AsBoolean(); lTitle.Text = string.Format("Add {0}", _groupType.Name).FormatAsHtmlTitle(); _homePhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); _cellPhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE); _confirmMaritalStatus = _isFamilyGroupType && GetAttributeValue("MaritalStatusConfirmation").AsBoolean(); if (_confirmMaritalStatus) { string script = string.Format(@" $('a.js-confirm-marital-status').click(function( e ){{ var anyAdults = false; $(""input[id$='_rblRole_0']"").each(function() {{ if ( $(this).prop('checked') ) {{ anyAdults = true; }} }}); if ( anyAdults ) {{ if ( $('#{0}').val() == '' ) {{ e.preventDefault(); Rock.dialogs.confirm('You have not selected a marital status for the adults in this new family. Are you sure you want to continue?', function (result) {{ if (result) {{ window.location = e.target.href ? e.target.href : e.target.parentElement.href; }} }}); }} }} }}); ", ddlMaritalStatus.ClientID); ScriptManager.RegisterStartupScript(btnNext, btnNext.GetType(), "confirm-marital-status", script, true); } }
/// <summary> /// Adds the group member. /// </summary> /// <param name="familyGroup">The family group.</param> /// <param name="person">The person.</param> /// <returns></returns> private Group AddGroupMembers(Group familyGroup, List <Person> newPeople) { var rockContext = new RockContext(); var familyGroupType = GroupTypeCache.GetFamilyGroupType(); // Create a new family group if one doesn't exist if (familyGroup == null) { familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyGroup.IsSecurityRole = false; familyGroup.IsSystem = false; familyGroup.IsPublic = true; familyGroup.IsActive = true; // Get oldest person's last name var familyName = newPeople.Where(p => p.BirthDate.HasValue) .OrderByDescending(p => p.BirthDate) .Select(p => p.LastName).FirstOrDefault(); familyGroup.Name = familyName + " Family"; new GroupService(rockContext).Add(familyGroup); } // Add group members var newGroupMembers = new List <GroupMember>(); foreach (var person in newPeople) { var groupMember = new GroupMember(); groupMember.IsSystem = false; groupMember.IsNotified = false; groupMember.GroupId = familyGroup.Id; groupMember.PersonId = person.Id; if (person.Age >= 18) { groupMember.GroupRoleId = familyGroupType.Roles.FirstOrDefault(r => r.Guid == new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; } else { groupMember.GroupRoleId = familyGroupType.Roles.FirstOrDefault(r => r.Guid == new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; } newGroupMembers.Add(groupMember); } // New family group, save as part of tracked entity if (familyGroup.Id == 0) { familyGroup.Members = newGroupMembers; } else // use GroupMemberService to save to an existing group { new GroupMemberService(rockContext).AddRange(newGroupMembers); } rockContext.SaveChanges(); return(familyGroup); }