/// <summary> /// Gets the person. /// </summary> /// <param name="create">if set to <c>true</c> [create].</param> /// <returns></returns> private Person GetPerson( bool create ) { Person person = null; var rockContext = new RockContext(); var personService = new PersonService( rockContext ); Group familyGroup = null; int personId = ViewState["PersonId"] as int? ?? 0; if ( personId == 0 && _targetPerson != null ) { personId = _targetPerson.Id; } if ( personId != 0 ) { person = personService.Get( personId ); } if ( create && ( !phGiveAsOption.Visible || tglGiveAsOption.Checked ) ) // If tglGiveOption is not checked, then person should not be null { if ( person == null ) { // Check to see if there's only one person with same email, first name, and last name if ( !string.IsNullOrWhiteSpace( txtEmail.Text ) && !string.IsNullOrWhiteSpace( txtFirstName.Text ) && !string.IsNullOrWhiteSpace( txtLastName.Text ) ) { // Same logic as CreatePledge.ascx.cs var personMatches = personService.GetByMatch( txtFirstName.Text, txtLastName.Text, txtEmail.Text ); if ( personMatches.Count() == 1 ) { person = personMatches.FirstOrDefault(); } else { person = null; } } if ( person == null ) { DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); // Create Person person = new Person(); person.FirstName = txtFirstName.Text; person.LastName = txtLastName.Text; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { person.RecordStatusValueId = dvcRecordStatus.Id; } // Create Person/Family familyGroup = PersonService.SaveNewPerson( person, rockContext, null, false ); } ViewState["PersonId"] = person != null ? person.Id : 0; } } if ( create && person != null ) // person should never be null at this point { person.Email = txtEmail.Text; if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false ) { var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME ) ).Id; var phone = person.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId ); if ( phone == null ) { phone = new PhoneNumber(); person.PhoneNumbers.Add( phone ); phone.NumberTypeValueId = numberTypeId; } phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); } if ( familyGroup == null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( GroupLocationId.HasValue ) { familyGroup = groupLocationService.Queryable() .Where( gl => gl.Id == GroupLocationId.Value ) .Select( gl => gl.Group ) .FirstOrDefault(); } else { familyGroup = personService.GetFamilies( person.Id ).FirstOrDefault(); } } rockContext.SaveChanges(); if ( familyGroup != null ) { GroupService.AddNewGroupAddress( rockContext, familyGroup, GetAttributeValue( "AddressType" ), acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country, true ); } } return person; }
private Person GetPersonOrBusiness( Person person ) { if ( person != null && phGiveAsOption.Visible && !tglGiveAsOption.Checked ) { var rockContext = new RockContext(); var personService = new PersonService( rockContext ); var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); Group familyGroup = null; Person business = null; int? businessId = cblBusiness.SelectedValueAsInt(); if ( businessId.HasValue ) { business = personService.Get( businessId.Value ); } if ( business == null ) { DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() ); DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() ); // Create Person business = new Person(); business.LastName = txtLastName.Text; business.IsEmailActive = true; business.EmailPreference = EmailPreference.EmailAllowed; business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id; if ( dvcConnectionStatus != null ) { business.ConnectionStatusValueId = dvcConnectionStatus.Id; } if ( dvcRecordStatus != null ) { business.RecordStatusValueId = dvcRecordStatus.Id; } // Create Person/Family familyGroup = PersonService.SaveNewPerson( business, rockContext, null, false ); // Get the relationship roles to use var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); int businessContactRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); int businessRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); int ownerRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); if ( ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0 ) { // get the known relationship group of the business contact // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS var contactKnownRelationshipGroup = groupMemberService.Queryable() .Where( g => g.GroupRoleId == ownerRoleId && g.PersonId == person.Id ) .Select( g => g.Group ) .FirstOrDefault(); if ( contactKnownRelationshipGroup == null ) { // In some cases person may not yet have a know relationship group type contactKnownRelationshipGroup = new Group(); groupService.Add( contactKnownRelationshipGroup ); contactKnownRelationshipGroup.Name = "Known Relationship"; contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id; var ownerMember = new GroupMember(); ownerMember.PersonId = person.Id; ownerMember.GroupRoleId = ownerRoleId; contactKnownRelationshipGroup.Members.Add( ownerMember ); } var groupMember = new GroupMember(); groupMember.PersonId = business.Id; groupMember.GroupRoleId = businessRoleId; contactKnownRelationshipGroup.Members.Add( groupMember ); // get the known relationship group of the business // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT var businessKnownRelationshipGroup = groupMemberService.Queryable() .Where( g => g.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ) && g.PersonId == business.Id ) .Select( g => g.Group ) .FirstOrDefault(); if ( businessKnownRelationshipGroup == null ) { // In some cases business may not yet have a know relationship group type businessKnownRelationshipGroup = new Group(); groupService.Add( businessKnownRelationshipGroup ); businessKnownRelationshipGroup.Name = "Known Relationship"; businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id; var ownerMember = new GroupMember(); ownerMember.PersonId = business.Id; ownerMember.GroupRoleId = ownerRoleId; businessKnownRelationshipGroup.Members.Add( ownerMember ); } var businessGroupMember = new GroupMember(); businessGroupMember.PersonId = person.Id; businessGroupMember.GroupRoleId = businessContactRoleId; businessKnownRelationshipGroup.Members.Add( businessGroupMember ); rockContext.SaveChanges(); } } business.LastName = txtBusinessName.Text; business.Email = txtEmail.Text; if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false ) { var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id; var phone = business.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId ); if ( phone == null ) { phone = new PhoneNumber(); business.PhoneNumbers.Add( phone ); phone.NumberTypeValueId = numberTypeId; } phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); } if ( familyGroup == null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( GroupLocationId.HasValue ) { familyGroup = groupLocationService.Queryable() .Where( gl => gl.Id == GroupLocationId.Value ) .Select( gl => gl.Group ) .FirstOrDefault(); } else { familyGroup = personService.GetFamilies( business.Id ).FirstOrDefault(); } } rockContext.SaveChanges(); if ( familyGroup != null ) { GroupService.AddNewGroupAddress( rockContext, familyGroup, Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK, acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country, false ); } return business; } return person; }
/// <summary> /// Adds the new family address. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="family">The family.</param> /// <param name="locationTypeGuid">The location type unique identifier.</param> /// <param name="street1">The street1.</param> /// <param name="street2">The street2.</param> /// <param name="city">The city.</param> /// <param name="state">The state.</param> /// <param name="postalCode">The postal code.</param> /// <param name="country">The country.</param> /// <param name="moveExistingToPrevious">if set to <c>true</c> [move existing to previous].</param> public static void AddNewFamilyAddress( RockContext rockContext, Group family, string locationTypeGuid, string street1, string street2, string city, string state, string postalCode, string country, bool moveExistingToPrevious = false ) { if ( !String.IsNullOrWhiteSpace( street1 ) || !String.IsNullOrWhiteSpace( street2 ) || !String.IsNullOrWhiteSpace( city ) || !String.IsNullOrWhiteSpace( postalCode ) || !string.IsNullOrWhiteSpace( country ) ) { var locationType = Rock.Web.Cache.DefinedValueCache.Read( locationTypeGuid.AsGuid() ); if ( locationType != null ) { var location = new LocationService( rockContext ).Get( street1, street2, city, state, postalCode, country ); if ( location != null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( !groupLocationService.Queryable() .Where( gl => gl.GroupId == family.Id && gl.GroupLocationTypeValueId == locationType.Id && gl.LocationId == location.Id ) .Any() ) { var familyChanges = new List<string>(); if ( moveExistingToPrevious ) { var prevLocationType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS ); if ( prevLocationType != null ) { foreach ( var prevLoc in groupLocationService.Queryable( "Location,GroupLocationTypeValue" ) .Where( gl => gl.GroupId == family.Id && gl.GroupLocationTypeValueId == locationType.Id ) ) { History.EvaluateChange( familyChanges, prevLoc.Location.ToString(), prevLoc.GroupLocationTypeValue.Value, prevLocationType.Value ); prevLoc.GroupLocationTypeValueId = prevLocationType.Id; prevLoc.IsMailingLocation = false; prevLoc.IsMappedLocation = false; } } } string addressChangeField = locationType.Value; var groupLocation = groupLocationService.Queryable() .Where( gl => gl.GroupId == family.Id && gl.LocationId == location.Id ) .FirstOrDefault(); if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; family.GroupLocations.Add( groupLocation ); } groupLocation.GroupLocationTypeValueId = locationType.Id; History.EvaluateChange( familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString() ); History.EvaluateChange( familyChanges, addressChangeField + " Is Mailing", string.Empty, groupLocation.IsMailingLocation.ToString() ); History.EvaluateChange( familyChanges, addressChangeField + " Is Map Location", string.Empty, groupLocation.IsMappedLocation.ToString() ); rockContext.SaveChanges(); foreach ( var fm in family.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, family.Name, typeof( Group ), family.Id ); } } } } } }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService( rockContext ); var groupTypeService = new GroupTypeService( rockContext ); var groupService = new GroupService( rockContext ); IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable(); List<int> currentAndDescendantGroupTypeIds = new List<int>(); var currentGroupTypeIds = this.CurrentGroupTypeIds.ToList(); currentAndDescendantGroupTypeIds.AddRange( currentGroupTypeIds ); foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => currentGroupTypeIds.Contains( a.Id ) ) ) { foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) ) { currentAndDescendantGroupTypeIds.Add( childGroupType.Id ); currentAndDescendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() ); } } groupLocationQry = groupLocationQry.Where( a => currentAndDescendantGroupTypeIds.Contains( a.Group.GroupTypeId ) ); groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name ); List<int> currentDeviceLocationIdList = this.GetGroupTypesLocations( rockContext ).Select( a => a.Id ).Distinct().ToList(); var qryList = groupLocationQry .Where( a => currentDeviceLocationIdList.Contains( a.LocationId ) ) .Select( a => new { GroupLocationId = a.Id, a.Location, GroupId = a.GroupId, GroupName = a.Group.Name, ScheduleIdList = a.Schedules.Select( s => s.Id ), GroupTypeId = a.Group.GroupTypeId } ).ToList(); var locationService = new LocationService( rockContext ); // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add( "GroupLocationId" ); dataTable.Columns.Add( "GroupId" ); dataTable.Columns.Add( "GroupName" ); dataTable.Columns.Add( "GroupPath" ); dataTable.Columns.Add( "LocationName" ); dataTable.Columns.Add( "LocationPath" ); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { dataTable.Columns.Add( field.DataField, typeof( bool ) ); } var locationPaths = new Dictionary<int, string>(); foreach ( var row in qryList ) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = groupService.GroupAncestorPathName( row.GroupId ); dataRow["GroupPath"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault(); dataRow["LocationName"] = row.Location.Name; if ( row.Location.ParentLocationId.HasValue ) { int locationId = row.Location.ParentLocationId.Value; if ( !locationPaths.ContainsKey( locationId ) ) { var locationNames = new List<string>(); var parentLocation = locationService.Get( locationId ); while ( parentLocation != null ) { locationNames.Add( parentLocation.Name ); parentLocation = parentLocation.ParentLocation; } if ( locationNames.Any() ) { locationNames.Reverse(); locationPaths.Add( locationId, locationNames.AsDelimited( " > " ) ); } else { locationPaths.Add( locationId, string.Empty ); } } dataRow["LocationPath"] = locationPaths[locationId]; } foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) ); dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId ); } dataTable.Rows.Add( dataRow ); } gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read<GroupLocation>().Id; gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); Person business = null; if ( int.Parse( hfBusinessId.Value ) != 0 ) { business = personService.Get( int.Parse( hfBusinessId.Value ) ); } if ( business == null ) { business = new Person(); personService.Add( business ); } // Business Name History.EvaluateChange( changes, "Last Name", business.LastName, tbBusinessName.Text ); business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService( rockContext ).GetByGuid( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id; string oldPhoneNumber = string.Empty; string newPhoneNumber = string.Empty; var phoneNumber = business.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == businessPhoneTypeId ); if ( phoneNumber != null ) { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId }; business.PhoneNumbers.Add( phoneNumber ); } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } else { if ( phoneNumber != null ) { business.PhoneNumbers.Remove( phoneNumber ); new PhoneNumberService( rockContext ).Delete( phoneNumber ); } } History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( businessPhoneTypeId ) ), oldPhoneNumber, newPhoneNumber ); // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id; // Record Status int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( business.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) ); business.RecordStatusValueId = newRecordStatusId; // Record Status Reason int? newRecordStatusReasonId = null; if ( business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id ) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( business.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) ); business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; History.EvaluateChange( changes, "Email", business.Email, tbEmail.Text ); business.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "EmailPreference", business.EmailPreference, newEmailPreference ); business.EmailPreference = newEmailPreference; if ( business.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), business.Id, changes ); } } } // Add/Update Family Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var adultFamilyMember = UpdateGroupMember( business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext ); business.GivingGroup = adultFamilyMember.Group; // Add/Update Known Relationship Group Type var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var knownRelationshipOwner = UpdateGroupMember( business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext ); // Add/Update Implied Relationship Group Type var impliedRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid() ); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember( business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext ); rockContext.SaveChanges(); // Every business should have an alias record with same id. If it's missing, create it if ( !business.Aliases.Any( a => a.AliasPersonId == business.Id ) ) { // refetch the business to make sure we have an Id business = personService.Get( business.Id ); if ( business != null ) { business.Aliases.Add( new PersonAlias { AliasPersonId = business.Id, AliasPersonGuid = business.Guid } ); 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; History.EvaluateChange( changes, "Address", oldValue, newLocation.ToString() ); } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); } ); ShowSummary( hfBusinessId.Value.AsInteger() ); }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var rockContext = new RockContext(); var groupLocationService = new GroupLocationService( rockContext ); var groupTypeService = new GroupTypeService( rockContext ); IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>(); var groupLocationQry = groupLocationService.Queryable(); int groupTypeId; // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter int? groupTypeIdPageParam = this.PageParameter( "groupTypeId" ).AsIntegerOrNull(); if ( groupTypeIdPageParam.HasValue ) { groupTypeId = groupTypeIdPageParam ?? Rock.Constants.All.Id; } else { groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id; } if ( groupTypeId != Rock.Constants.All.Id ) { var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents( groupTypeId ).Select( a => a.Id ); // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor) groupLocationQry = groupLocationQry.Where( a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains( a.Group.GroupTypeId ) ); groupPaths = groupTypeService.GetAllAssociatedDescendentsPath( groupTypeId ); } else { // if no specific GroupType is specified, show all GroupTypes with GroupTypePurpose of Checkin Template and their descendents (since this blocktype is specifically for Checkin) int groupTypePurposeCheckInTemplateId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE ) ).Id; List<int> descendantGroupTypeIds = new List<int>(); foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId ) ) { foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) ) { descendantGroupTypeIds.Add( childGroupType.Id ); descendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() ); } } groupLocationQry = groupLocationQry.Where( a => descendantGroupTypeIds.Contains( a.Group.GroupTypeId ) ); } if ( gGroupLocationSchedule.SortProperty != null ) { groupLocationQry = groupLocationQry.Sort( gGroupLocationSchedule.SortProperty ); } else { groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name ); } var qryList = groupLocationQry.Select( a => new { GroupLocationId = a.Id, GroupName = a.Group.Name, LocationName = a.Location.Name, ScheduleIdList = a.Schedules.Select( s => s.Id ), a.LocationId, GroupTypeId = a.Group.GroupTypeId } ).ToList(); int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id; if ( parentLocationId != Rock.Constants.All.Id ) { var descendantLocationIds = new LocationService( rockContext ).GetAllDescendents( parentLocationId ).Select( a => a.Id ); qryList = qryList.Where( a => descendantLocationIds.Contains( a.LocationId ) ).ToList(); } // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add( "GroupLocationId" ); dataTable.Columns.Add( "GroupName" ); dataTable.Columns.Add( "LocationName" ); dataTable.Columns.Add( "Path" ); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { dataTable.Columns.Add( field.DataField, typeof( bool ) ); } foreach ( var row in qryList ) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = row.GroupName; dataRow["LocationName"] = row.LocationName; dataRow["Path"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault(); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) ); dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId ); } dataTable.Rows.Add( dataRow ); } gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
public IQueryable<MapItem> GetChildMapInfo( int groupId, string groupTypeIds = null, bool includeDescendants = false ) { var person = GetPerson(); var mapItems = new List<MapItem>(); // Enable proxy creation since security is being checked and need to navigate parent authorities SetProxyCreation( true ); var groupService = (GroupService)Service; var groupLocationService = new GroupLocationService( groupService.Context as RockContext ); IEnumerable<Group> childGroups; if ( !includeDescendants ) { childGroups = groupService.Queryable().Where( g => g.ParentGroupId == groupId ); } else { childGroups = groupService.GetAllDescendents( groupId ); } if ( !string.IsNullOrWhiteSpace( groupTypeIds ) ) { var groupTypeIdList = groupTypeIds.Split( ',' ).AsIntegerList(); if ( groupTypeIdList.Any() ) { childGroups = childGroups.Where( a => groupTypeIdList.Contains( a.GroupTypeId ) ); } } var childGroupIds = childGroups.Select( a => a.Id ).ToList(); // fetch all the groupLocations for all the groups we are going to show (to reduce SQL traffic) var groupsLocationList = groupLocationService.Queryable().Where( a => childGroupIds.Contains( a.GroupId ) && a.Location.GeoPoint != null || a.Location.GeoFence != null ).Select( a => new { a.GroupId, a.Location } ).ToList(); foreach ( var group in childGroups ) { if ( group != null && group.IsAuthorized( Rock.Security.Authorization.VIEW, person ) ) { var groupLocations = groupsLocationList.Where( a => a.GroupId == group.Id ).Select( a => a.Location ); foreach ( var location in groupLocations ) { var mapItem = new MapItem( location ); mapItem.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id; mapItem.EntityId = group.Id; mapItem.Name = group.Name; if ( mapItem.Point != null || mapItem.PolygonPoints.Any() ) { mapItems.Add( mapItem ); } } } } return mapItems.AsQueryable(); }
/// <summary> /// Adds the new group address. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="group">The group.</param> /// <param name="locationTypeGuid">The location type unique identifier.</param> /// <param name="location">The location.</param> /// <param name="moveExistingToPrevious">if set to <c>true</c> [move existing to previous].</param> public static void AddNewGroupAddress( RockContext rockContext, Group group, string locationTypeGuid, Location location, bool moveExistingToPrevious = false ) { if ( location != null ) { var groupType = GroupTypeCache.Read( group.GroupTypeId ); if ( groupType != null ) { var locationType = groupType.LocationTypeValues.FirstOrDefault( l => l.Guid.Equals( locationTypeGuid.AsGuid() ) ); if ( locationType != null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( !groupLocationService.Queryable() .Where( gl => gl.GroupId == group.Id && gl.GroupLocationTypeValueId == locationType.Id && gl.LocationId == location.Id ) .Any() ) { var familyChanges = new List<string>(); if ( moveExistingToPrevious ) { var prevLocationType = groupType.LocationTypeValues.FirstOrDefault( l => l.Guid.Equals( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() ) ); if ( prevLocationType != null ) { foreach ( var prevLoc in groupLocationService.Queryable( "Location,GroupLocationTypeValue" ) .Where( gl => gl.GroupId == group.Id && gl.GroupLocationTypeValueId == locationType.Id ) ) { History.EvaluateChange( familyChanges, prevLoc.Location.ToString(), prevLoc.GroupLocationTypeValue.Value, prevLocationType.Value ); prevLoc.GroupLocationTypeValueId = prevLocationType.Id; prevLoc.IsMailingLocation = false; prevLoc.IsMappedLocation = false; } } } string addressChangeField = locationType.Value; var groupLocation = groupLocationService.Queryable() .Where( gl => gl.GroupId == group.Id && gl.LocationId == location.Id ) .FirstOrDefault(); if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; group.GroupLocations.Add( groupLocation ); } groupLocation.GroupLocationTypeValueId = locationType.Id; History.EvaluateChange( familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString() ); History.EvaluateChange( familyChanges, addressChangeField + " Is Mailing", string.Empty, groupLocation.IsMailingLocation.ToString() ); History.EvaluateChange( familyChanges, addressChangeField + " Is Map Location", string.Empty, groupLocation.IsMappedLocation.ToString() ); rockContext.SaveChanges(); if ( groupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() ) ) { foreach ( var fm in group.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, group.Name, typeof( Group ), group.Id ); } } } } } } }
public IQueryable<Group> GetByLocation( int geofenceGroupTypeId, int groupTypeId, int locationId ) { var fenceGroups = new List<Group>(); // Get the location record var rockContext = (RockContext)Service.Context; var location = new LocationService( rockContext ).Get( locationId ); // If location was valid and address was geocoded succesfully if ( location != null && location.GeoPoint != null ) { // Find all the groupLocation records ( belonging to groups of the "geofenceGroupType" ) // where the geofence surrounds the location var groupLocationService = new GroupLocationService( rockContext ); foreach ( var fenceGroupLocation in groupLocationService .Queryable("Group,Location").AsNoTracking() .Where( gl => gl.Group.GroupTypeId == geofenceGroupTypeId && gl.Location.GeoFence != null && location.GeoPoint.Intersects( gl.Location.GeoFence ) ) .ToList() ) { var fenceGroup = fenceGroups.FirstOrDefault( g => g.Id == fenceGroupLocation.GroupId ); if ( fenceGroup == null ) { fenceGroup = fenceGroupLocation.Group; fenceGroups.Add( fenceGroup ); } fenceGroupLocation.Group = null; // Find all the group groupLocation records ( with group of the "groupTypeId" ) that have a location // within the fence foreach ( var group in Service .Queryable( "Schedule,GroupLocations.Location" ).AsNoTracking() .Where( g => g.GroupTypeId == groupTypeId && g.GroupLocations.Any( gl => gl.Location.GeoPoint != null && gl.Location.GeoPoint.Intersects( fenceGroupLocation.Location.GeoFence ) ) ) ) { // Remove any other group locations that do not belong to fence foreach ( var gl in group.GroupLocations.ToList() ) { if ( gl.Location.GeoPoint == null || !gl.Location.GeoPoint.Intersects( fenceGroupLocation.Location.GeoFence ) ) { group.GroupLocations.Remove( gl ); } else { // Calculate distance double meters = gl.Location.GeoPoint.Distance( location.GeoPoint ) ?? 0.0D; gl.Location.SetDistance( meters * Location.MilesPerMeter ); } } fenceGroup.Groups.Add( group ); } } } return fenceGroups.AsQueryable(); }
/// <summary> /// Binds the grid. /// </summary> protected void BindGrid() { AddScheduleColumns(); var groupLocationService = new GroupLocationService(); var groupLocationQry = groupLocationService.Queryable(); int groupTypeId; // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter int? groupTypeIdPageParam = this.PageParameter( "groupTypeId" ).AsInteger( false ); if ( groupTypeIdPageParam.HasValue ) { groupTypeId = groupTypeIdPageParam ?? Rock.Constants.All.Id; } else { groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id; } if ( groupTypeId != Rock.Constants.All.Id ) { // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent groupLocationQry = groupLocationQry.Where( a => a.Group.GroupType.Id == groupTypeId || a.Group.GroupType.ParentGroupTypes.Select( p => p.Id ).Contains( groupTypeId ) ); } var qryList = groupLocationQry.Select( a => new { GroupLocationId = a.Id, GroupName = a.Group.Name, LocationName = a.Location.Name, ScheduleIdList = a.Schedules.Select( s => s.Id ), a.LocationId } ).ToList(); int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id; if ( parentLocationId != Rock.Constants.All.Id ) { var descendantLocationIds = new LocationService().GetAllDescendents( parentLocationId ).Select( a => a.Id ); qryList = qryList.Where( a => descendantLocationIds.Contains( a.LocationId ) ).ToList(); } // put stuff in a datatable so we can dynamically have columns for each Schedule DataTable dataTable = new DataTable(); dataTable.Columns.Add( "GroupLocationId" ); dataTable.Columns.Add( "GroupName" ); dataTable.Columns.Add( "LocationName" ); foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { dataTable.Columns.Add( field.DataField, typeof( bool ) ); } foreach ( var row in qryList ) { DataRow dataRow = dataTable.NewRow(); dataRow["GroupLocationId"] = row.GroupLocationId; dataRow["GroupName"] = row.GroupName; dataRow["LocationName"] = row.LocationName; foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() ) { int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) ); dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId ); } dataTable.Rows.Add( dataRow ); } gGroupLocationSchedule.DataSource = dataTable; gGroupLocationSchedule.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { // if a Location is getting edited, validate and save it if ( gLocations.EditIndex >= 0 ) { var row = gLocations.Rows[gLocations.EditIndex]; AddressControl acAddress = row.FindControl( "acAddress" ) as AddressControl; if ( acAddress.IsValid ) { gLocations_RowUpdating( sender, new GridViewUpdateEventArgs( gLocations.EditIndex ) ); } else { // acAddress will render an error message return; } } if ( !IsUserAuthorized( Rock.Security.Authorization.EDIT ) ) { return; } // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if ( Page.IsValid ) { confirmExit.Enabled = true; var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var personService = new PersonService( rockContext ); var historyService = new HistoryService( rockContext ); var groupChanges = new List<string>(); // SAVE GROUP _group = groupService.Get( _group.Id ); History.EvaluateChange( groupChanges, "Group Name", _group.Name, tbGroupName.Text ); _group.Name = tbGroupName.Text; int? campusId = cpCampus.SelectedValueAsInt(); if ( _group.CampusId != campusId ) { History.EvaluateChange( groupChanges, "Campus", _group.CampusId.HasValue ? CampusCache.Read( _group.CampusId.Value ).Name : string.Empty, campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty ); _group.CampusId = campusId; } rockContext.SaveChanges(); // SAVE GROUP MEMBERS int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int? reasonValueId = ddlReason.SelectedValueAsInt(); var newGroups = new List<Group>(); foreach ( var groupMemberInfo in GroupMembers ) { var memberChanges = new List<string>(); var demographicChanges = new List<string>(); var role = _groupType.Roles.Where( r => r.Guid.Equals( groupMemberInfo.RoleGuid ) ).FirstOrDefault(); if ( role == null ) { role = _groupType.Roles.FirstOrDefault(); } bool isAdult = role != null && role.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ); // People added to group (new or from other group ) if ( !groupMemberInfo.ExistingGroupMember ) { Person person = null; if ( groupMemberInfo.Id == -1 ) { // added new person demographicChanges.Add( "Created" ); person = new Person(); person.TitleValueId = groupMemberInfo.TitleValueId; person.FirstName = groupMemberInfo.FirstName; person.NickName = groupMemberInfo.NickName; person.LastName = groupMemberInfo.LastName; person.SuffixValueId = groupMemberInfo.SuffixValueId; person.Gender = groupMemberInfo.Gender; DateTime? birthdate = groupMemberInfo.BirthDate; if ( birthdate.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthdate.Value.CompareTo( today ) > 0 ) { birthdate = birthdate.Value.AddYears( -100 ); } } person.SetBirthDate( birthdate ); person.MaritalStatusValueId = groupMemberInfo.MaritalStatusValueId; person.GradeOffset = groupMemberInfo.GradeOffset; person.ConnectionStatusValueId = groupMemberInfo.ConnectionStatusValueId; if ( isAdult ) { person.GivingGroupId = _group.Id; } person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; } else { person = personService.Get( groupMemberInfo.Id ); } if ( person == null ) { // shouldn't happen return; } if ( _isFamilyGroupType ) { if ( person.RecordStatusValueId != recordStatusValueID ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); person.RecordStatusValueId = recordStatusValueID; } if ( person.RecordStatusValueId != recordStatusValueID ) { History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); person.RecordStatusReasonValueId = reasonValueId; } } PersonService.AddPersonToGroup( person, person.Id == 0, _group.Id, role.Id, rockContext ); } else { // existing group members var groupMember = groupMemberService.Queryable( "Person", true ).Where( m => m.PersonId == groupMemberInfo.Id && m.Group.GroupTypeId == _groupType.Id && m.GroupId == _group.Id ).FirstOrDefault(); if ( groupMember != null ) { if ( groupMemberInfo.Removed ) { if ( !groupMemberInfo.IsInOtherGroups ) { var newFamilyChanges = new List<string>(); // Family member was removed and should be created in their own new family var newGroup = new Group(); newGroup.Name = groupMemberInfo.LastName + " " + _groupType.Name; History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newGroup.Name ); newGroup.GroupTypeId = _groupType.Id; if ( _group.CampusId.HasValue ) { History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _group.CampusId.Value ).Name ); } newGroup.CampusId = _group.CampusId; groupService.Add( newGroup ); rockContext.SaveChanges(); // If person's previous giving group was this family, set it to their new family id if ( _isFamilyGroupType && groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _group.Id ) { History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _group.Name ); groupMember.Person.GivingGroupId = newGroup.Id; } groupMember.Group = newGroup; rockContext.SaveChanges(); var newMemberChanges = new List<string>(); if ( _isFamilyGroupType ) { History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMember.Person.Id, newFamilyChanges, newGroup.Name, typeof( Group ), newGroup.Id ); } newGroups.Add( newGroup ); History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty ); } else { History.EvaluateChange( groupChanges, "Family", groupMember.Group.Name, string.Empty ); groupMemberService.Delete( groupMember ); rockContext.SaveChanges(); } } else { // Existing member was not remvoved if ( role != null ) { History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; if ( _isFamilyGroupType ) { if ( recordStatusValueID > 0 ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; } } rockContext.SaveChanges(); } } } } // Remove anyone that was moved from another family if ( groupMemberInfo.RemoveFromOtherGroups ) { PersonService.RemovePersonFromOtherFamilies( _group.Id, groupMemberInfo.Id, rockContext ); } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), groupMemberInfo.Id, demographicChanges ); if ( _isFamilyGroupType ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMemberInfo.Id, memberChanges, _group.Name, typeof( Group ), _group.Id ); } } // SAVE LOCATIONS var groupLocationService = new GroupLocationService( rockContext ); // delete any group locations that were removed var remainingLocationIds = GroupAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList(); foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" ) .Where( l => l.GroupId == _group.Id && !remainingLocationIds.Contains( l.Id ) ) ) { History.EvaluateChange( groupChanges, ( removedLocation.GroupLocationTypeValue != null ? removedLocation.GroupLocationTypeValue.Value : "Unknown" ) + " Location", removedLocation.Location.ToString(), string.Empty ); groupLocationService.Delete( removedLocation ); } rockContext.SaveChanges(); foreach ( var groupAddressInfo in GroupAddresses.Where( a => a.Id >= 0 ) ) { Location updatedAddress = null; if ( groupAddressInfo.LocationIsDirty ) { updatedAddress = new LocationService( rockContext ).Get( groupAddressInfo.Street1, groupAddressInfo.Street2, groupAddressInfo.City, groupAddressInfo.State, groupAddressInfo.PostalCode, groupAddressInfo.Country ); } GroupLocation groupLocation = null; if ( groupAddressInfo.Id > 0 ) { groupLocation = groupLocationService.Get( groupAddressInfo.Id ); } if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.GroupId = _group.Id; groupLocationService.Add( groupLocation ); } History.EvaluateChange( groupChanges, "Location Type", groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Value : string.Empty, groupAddressInfo.LocationTypeName ); groupLocation.GroupLocationTypeValueId = groupAddressInfo.LocationTypeId; History.EvaluateChange( groupChanges, groupAddressInfo.LocationTypeName + " Is Mailing", groupLocation.IsMailingLocation.ToString(), groupAddressInfo.IsMailing.ToString() ); groupLocation.IsMailingLocation = groupAddressInfo.IsMailing; History.EvaluateChange( groupChanges, groupAddressInfo.LocationTypeName + " Is Map Location", groupLocation.IsMappedLocation.ToString(), groupAddressInfo.IsLocation.ToString() ); groupLocation.IsMappedLocation = groupAddressInfo.IsLocation; if ( updatedAddress != null ) { History.EvaluateChange( groupChanges, groupAddressInfo.LocationTypeName + " Location", groupLocation.Location != null ? groupLocation.Location.ToString() : string.Empty, updatedAddress.ToString() ); groupLocation.Location = updatedAddress; } rockContext.SaveChanges(); // Add the same locations to any new families created by removing an existing family member if ( newGroups.Any() ) { // reload grouplocation for access to child properties groupLocation = groupLocationService.Get( groupLocation.Id ); foreach ( var newGroup in newGroups ) { var newGroupLocation = new GroupLocation(); newGroupLocation.GroupId = newGroup.Id; newGroupLocation.LocationId = groupLocation.LocationId; newGroupLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newGroupLocation.IsMailingLocation = groupLocation.IsMailingLocation; newGroupLocation.IsMappedLocation = groupLocation.IsMappedLocation; groupLocationService.Add( newGroupLocation ); } rockContext.SaveChanges(); } } _group.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phGroupAttributes, _group ); _group.SaveAttributeValues( rockContext ); if ( _isFamilyGroupType ) { foreach ( var fm in _group.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, groupChanges, _group.Name, typeof( Group ), _group.Id ); } } Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } ); } }
public IQueryable<Group> GetByLocation( int geofenceGroupTypeId, int groupTypeId, string street, string city, string state, string postalCode ) { var fenceGroups = new List<Group>(); string street2 = string.Empty; string country = GlobalAttributesCache.Read().OrganizationCountry; // Get a new location record for the address var rockContext = (RockContext)Service.Context; var location = new LocationService( rockContext ).Get( street, street2, city, state, postalCode, country ); // If address was geocoded succesfully if ( location.GeoPoint != null ) { // Find all the groupLocation records ( belonging to groups of the "geofenceGroupType" ) // where the geofence surrounds the location var groupLocationService = new GroupLocationService( rockContext ); foreach ( var fenceGroupLocation in groupLocationService .Queryable("Group,Location").AsNoTracking() .Where( gl => gl.Group.GroupTypeId == geofenceGroupTypeId && gl.Location.GeoFence != null && location.GeoPoint.Intersects( gl.Location.GeoFence ) ) .ToList() ) { var fenceGroup = fenceGroups.FirstOrDefault( g => g.Id == fenceGroupLocation.GroupId ); if ( fenceGroup == null ) { fenceGroup = fenceGroupLocation.Group; fenceGroups.Add( fenceGroup ); } fenceGroupLocation.Group = null; // Find all the group groupLocation records ( with group of the "groupTypeId" ) that have a location // within the fence var groups = new List<Group>(); foreach ( var groupLocation in groupLocationService .Queryable( "Group,Location" ).AsNoTracking() .Where( gl => gl.Group.GroupTypeId == groupTypeId && gl.Location.GeoPoint != null && gl.Location.GeoPoint.Intersects( fenceGroupLocation.Location.GeoFence ) ) ) { var group = groups.FirstOrDefault( g => g.Id == groupLocation.GroupId ); if ( group == null ) { group = groupLocation.Group; group.LoadAttributes(); groups.Add( group ); } groupLocation.Group = null; } // Add the group as a child of the fence group groups.ForEach( g => fenceGroup.Groups.Add( g ) ); } } return fenceGroups.AsQueryable(); }
/// <summary> /// Adds the new family address. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="family">The family.</param> /// <param name="locationTypeGuid">The location type unique identifier.</param> /// <param name="location">The location.</param> /// <param name="moveExistingToPrevious">if set to <c>true</c> [move existing to previous].</param> public static void AddNewFamilyAddress(RockContext rockContext, Group family, string locationTypeGuid, Location location, bool moveExistingToPrevious = false) { if (location != null) { var locationType = Rock.Web.Cache.DefinedValueCache.Read(locationTypeGuid.AsGuid()); if (locationType != null) { var groupLocationService = new GroupLocationService(rockContext); if (!groupLocationService.Queryable() .Where(gl => gl.GroupId == family.Id && gl.GroupLocationTypeValueId == locationType.Id && gl.LocationId == location.Id) .Any()) { var familyChanges = new List <string>(); if (moveExistingToPrevious) { var prevLocationType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS); if (prevLocationType != null) { foreach (var prevLoc in groupLocationService.Queryable("Location,GroupLocationTypeValue") .Where(gl => gl.GroupId == family.Id && gl.GroupLocationTypeValueId == locationType.Id)) { History.EvaluateChange(familyChanges, prevLoc.Location.ToString(), prevLoc.GroupLocationTypeValue.Value, prevLocationType.Value); prevLoc.GroupLocationTypeValueId = prevLocationType.Id; prevLoc.IsMailingLocation = false; prevLoc.IsMappedLocation = false; } } } string addressChangeField = locationType.Value; var groupLocation = groupLocationService.Queryable() .Where(gl => gl.GroupId == family.Id && gl.LocationId == location.Id) .FirstOrDefault(); if (groupLocation == null) { groupLocation = new GroupLocation(); groupLocation.Location = location; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; family.GroupLocations.Add(groupLocation); } groupLocation.GroupLocationTypeValueId = locationType.Id; History.EvaluateChange(familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString()); History.EvaluateChange(familyChanges, addressChangeField + " Is Mailing", string.Empty, groupLocation.IsMailingLocation.ToString()); History.EvaluateChange(familyChanges, addressChangeField + " Is Map Location", string.Empty, groupLocation.IsMappedLocation.ToString()); rockContext.SaveChanges(); foreach (var fm in family.Members) { HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, family.Name, typeof(Group), family.Id); } } } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { // confirmation was disabled by btnSave on client-side. So if returning without a redirect, // it should be enabled. If returning with a redirect, the control won't be updated to reflect // confirmation being enabled, so it's ok to enable it here confirmExit.Enabled = true; if ( Page.IsValid ) { confirmExit.Enabled = true; RockTransactionScope.WrapTransaction( () => { var rockContext = new RockContext(); var familyService = new GroupService( rockContext ); var familyMemberService = new GroupMemberService( rockContext ); var personService = new PersonService( rockContext ); var historyService = new HistoryService( rockContext ); var familyChanges = new List<string>(); // SAVE FAMILY _family = familyService.Get( _family.Id ); History.EvaluateChange( familyChanges, "Family Name", _family.Name, tbFamilyName.Text ); _family.Name = tbFamilyName.Text; int? campusId = cpCampus.SelectedValueAsInt(); if ( _family.CampusId != campusId ) { History.EvaluateChange( familyChanges, "Campus", _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty, campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty ); _family.CampusId = campusId; } var familyGroupTypeId = _family.GroupTypeId; rockContext.SaveChanges(); // SAVE FAMILY MEMBERS int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt(); int? reasonValueId = ddlReason.SelectedValueAsInt(); var newFamilies = new List<Group>(); foreach ( var familyMember in FamilyMembers ) { var memberChanges = new List<string>(); var demographicChanges = new List<string>(); var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault(); if ( role == null ) { role = familyRoles.FirstOrDefault(); } bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ); // People added to family (new or from other family) if ( !familyMember.ExistingFamilyMember ) { var groupMember = new GroupMember(); if ( familyMember.Id == -1 ) { // added new person demographicChanges.Add( "Created" ); var person = new Person(); person.FirstName = familyMember.FirstName; person.NickName = familyMember.NickName; History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName ); person.LastName = familyMember.LastName; History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); person.Gender = familyMember.Gender; History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); person.BirthDate = familyMember.BirthDate; History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); if ( !isChild ) { person.GivingGroupId = _family.Id; History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name ); } person.EmailPreference = EmailPreference.EmailAllowed; groupMember.Person = person; } else { // added from other family groupMember.Person = personService.Get( familyMember.Id ); } if ( recordStatusValueID > 0 ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; } groupMember.GroupId = _family.Id; if ( role != null ) { History.EvaluateChange( memberChanges, "Role", string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; } if ( groupMember.Person != null ) { familyMemberService.Add( groupMember ); rockContext.SaveChanges(); familyMember.Id = groupMember.Person.Id; } } else { // existing family members var groupMember = familyMemberService.Queryable( "Person" ).Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId == _family.Id ).FirstOrDefault(); if ( groupMember != null ) { if ( familyMember.Removed ) { var newFamilyChanges = new List<string>(); // Family member was removed and should be created in their own new family var newFamily = new Group(); newFamily.Name = familyMember.LastName + " Family"; History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newFamily.Name ); newFamily.GroupTypeId = familyGroupTypeId; if ( _family.CampusId.HasValue ) { History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name ); } newFamily.CampusId = _family.CampusId; familyService.Add( newFamily ); rockContext.SaveChanges(); // If person's previous giving group was this family, set it to their new family id if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id ) { History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name ); groupMember.Person.GivingGroupId = newFamily.Id; } groupMember.Group = newFamily; rockContext.SaveChanges(); var newMemberChanges = new List<string>(); History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id ); newFamilies.Add( newFamily ); History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty ); } else { // Existing member was not remvoved if ( role != null ) { History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name ); groupMember.GroupRoleId = role.Id; if ( recordStatusValueID > 0 ) { History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) ); groupMember.Person.RecordStatusValueId = recordStatusValueID; History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) ); groupMember.Person.RecordStatusReasonValueId = reasonValueId; } rockContext.SaveChanges(); } } } } // Remove anyone that was moved from another family if ( familyMember.RemoveFromOtherFamilies ) { var otherFamilies = familyMemberService.Queryable() .Where( m => m.PersonId == familyMember.Id && m.Group.GroupTypeId == familyGroupTypeId && m.GroupId != _family.Id ) .ToList(); foreach ( var otherFamilyMember in otherFamilies ) { var fm = familyMemberService.Get( otherFamilyMember.Id ); // If the person's giving group id was the family they are being removed from, update it to this new family's id if ( fm.Person.GivingGroupId == fm.GroupId ) { var person = personService.Get( fm.PersonId ); History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name ); person.GivingGroupId = _family.Id; rockContext.SaveChanges(); } var oldMemberChanges = new List<string>(); History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty ); History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id ); familyMemberService.Delete( fm ); rockContext.SaveChanges(); var f = familyService.Queryable() .Where( g => g.Id == otherFamilyMember.GroupId && !g.Members.Any() ) .FirstOrDefault(); if ( f != null ) { familyService.Delete( f ); rockContext.SaveChanges(); } } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), familyMember.Id, demographicChanges ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id ); } // SAVE LOCATIONS var groupLocationService = new GroupLocationService( rockContext ); // delete any group locations that were removed var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList(); foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" ) .Where( l => l.GroupId == _family.Id && !remainingLocationIds.Contains( l.Id ) ) ) { History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location", removedLocation.Location.ToString(), string.Empty ); groupLocationService.Delete( removedLocation ); } rockContext.SaveChanges(); foreach ( var familyAddress in FamilyAddresses ) { Location updatedAddress = null; if ( familyAddress.LocationIsDirty ) { updatedAddress = new LocationService( rockContext ).Get( familyAddress.Street1, familyAddress.Street2, familyAddress.City, familyAddress.State, familyAddress.Zip ); } GroupLocation groupLocation = null; if ( familyAddress.Id > 0 ) { groupLocation = groupLocationService.Get( familyAddress.Id ); } if ( groupLocation == null ) { groupLocation = new GroupLocation(); groupLocation.GroupId = _family.Id; groupLocationService.Add( groupLocation ); } History.EvaluateChange( familyChanges, "Location Type", groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty, familyAddress.LocationTypeName ); groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Mailing", groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() ); groupLocation.IsMailingLocation = familyAddress.IsMailing; History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location", groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() ); groupLocation.IsMappedLocation = familyAddress.IsLocation; if ( updatedAddress != null ) { History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location", groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() ); groupLocation.Location = updatedAddress; } rockContext.SaveChanges(); // Add the same locations to any new families created by removing an existing family member if ( newFamilies.Any() ) { //reload grouplocation for access to child properties groupLocation = groupLocationService.Get( groupLocation.Id ); foreach ( var newFamily in newFamilies ) { var newFamilyLocation = new GroupLocation(); newFamilyLocation.GroupId = newFamily.Id; newFamilyLocation.LocationId = groupLocation.LocationId; newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId; newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation; newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation; groupLocationService.Add( newFamilyLocation ); } rockContext.SaveChanges(); } } foreach ( var fm in _family.Members ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id ); } _family = familyService.Get( _family.Id ); if ( _family.Members.Any( m => m.PersonId == Person.Id ) ) { Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false ); } else { var fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) && m.Person.Gender == Gender.Male ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); if ( fm == null ) { fm = _family.Members .Where( m => m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) ) .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm == null ) { fm = _family.Members .OrderByDescending( m => m.Person.Age ) .FirstOrDefault(); } if ( fm != null ) { Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false ); } else { Response.Redirect( "~", false ); } } } ); } }
/// <summary> /// Gets a list of groups surrounding the specified geopoint of the specified GroupTypeid /// If geofenceGroupTypeId is specified, the list of GeoFence groups will be returned with the groups as child groups of that geofence group. /// </summary> /// <param name="groupTypeId">The group type identifier.</param> /// <param name="geoPoint">The geo point.</param> /// <param name="sortByDistance">if set to <c>true</c> [sort by distance].</param> /// <param name="maxDistanceMiles">The maximum distance miles.</param> /// <param name="geofenceGroupTypeId">The geofence group type identifier.</param> /// <param name="queryOptions">The query options.</param> /// <returns></returns> private IQueryable GetByGeoPoint( int groupTypeId, DbGeography geoPoint, bool? sortByDistance, double? maxDistanceMiles, int? geofenceGroupTypeId, System.Web.Http.OData.Query.ODataQueryOptions<Group> queryOptions ) { var rockContext = (RockContext)Service.Context; IEnumerable<Group> resultGroups = new List<Group>(); if ( geoPoint != null ) { if ( geofenceGroupTypeId.HasValue && geofenceGroupTypeId.Value > 0 ) { var fenceGroups = new List<Group>(); // Find all the groupLocation records ( belonging to groups of the "geofenceGroupType" ) // where the geofence surrounds the location var groupLocationService = new GroupLocationService( rockContext ); foreach ( var fenceGroupLocation in groupLocationService .Queryable( "Group,Location" ).AsNoTracking() .Where( gl => gl.Group.GroupTypeId == geofenceGroupTypeId && gl.Location.GeoFence != null && geoPoint.Intersects( gl.Location.GeoFence ) ) .ToList() ) { var fenceGroup = fenceGroups.FirstOrDefault( g => g.Id == fenceGroupLocation.GroupId ); if ( fenceGroup == null ) { fenceGroup = fenceGroupLocation.Group; fenceGroups.Add( fenceGroup ); } fenceGroupLocation.Group = null; // Find all the group groupLocation records ( with group of the "groupTypeId" ) that have a location // within the fence foreach ( var group in Service .Queryable( "Schedule,GroupLocations.Location" ).AsNoTracking() .Where( g => g.GroupTypeId == groupTypeId && g.GroupLocations.Any( gl => gl.Location.GeoPoint != null && gl.Location.GeoPoint.Intersects( fenceGroupLocation.Location.GeoFence ) ) ) ) { // Remove any other group locations that do not belong to fence foreach ( var gl in group.GroupLocations.ToList() ) { if ( gl.Location.GeoPoint == null || !gl.Location.GeoPoint.Intersects( fenceGroupLocation.Location.GeoFence ) ) { group.GroupLocations.Remove( gl ); } } fenceGroup.Groups.Add( group ); } } resultGroups = fenceGroups; } else { // if a geoFence is not specified, just get all groups of this group type resultGroups = Service.Queryable( "Schedule,GroupLocations.Location" ).AsNoTracking().Where( a => a.GroupTypeId == groupTypeId ).Include( a => a.GroupLocations ).ToList(); } } // calculate the distance of each of the groups locations from the specified geoFence foreach ( var group in resultGroups ) { foreach ( var gl in group.GroupLocations ) { // Calculate distance if ( gl.Location.GeoPoint != null ) { double meters = gl.Location.GeoPoint.Distance( geoPoint ) ?? 0.0D; gl.Location.SetDistance( meters * Location.MilesPerMeter ); } } } // remove groups that don't have a GeoPoint resultGroups = resultGroups.Where( a => a.GroupLocations.Any( x => x.Location.GeoPoint != null ) ); // remove groups that don't have a location within the specified radius if ( maxDistanceMiles.HasValue ) { resultGroups = resultGroups.Where( a => a.GroupLocations.Any( x => x.Location.Distance <= maxDistanceMiles.Value ) ); } var querySettings = new System.Web.Http.OData.Query.ODataQuerySettings(); if ( sortByDistance.HasValue && sortByDistance.Value ) { resultGroups = resultGroups.OrderBy( a => a.GroupLocations.FirstOrDefault() != null ? a.GroupLocations.FirstOrDefault().Location.Distance : int.MaxValue ).ToList(); // if we are sorting by distance, tell OData not to re-sort them by Id querySettings.EnsureStableOrdering = false; } // manually apply any OData parameters to the InMemory Query var qryResults = queryOptions.ApplyTo( resultGroups.AsQueryable(), querySettings ); return qryResults.AsQueryable(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var person = personService.Get( CurrentPersonId ?? 0 ); if ( person != null ) { int? orphanedPhotoId = null; if ( person.PhotoId != imgPhoto.BinaryFileId ) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if ( orphanedPhotoId.HasValue ) { if ( person.PhotoId.HasValue ) { changes.Add( "Modified the photo." ); } else { changes.Add( "Deleted the photo." ); } } else if ( person.PhotoId.HasValue ) { changes.Add( "Added a photo." ); } } int? newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) ); person.TitleValueId = newTitleId; History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text ); person.FirstName = tbFirstName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text); person.NickName = tbNickName.Text; History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text ); person.LastName = tbLastName.Text; int? newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) ); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if ( birthday.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate( null ); } History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { int phoneNumberTypeId; if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId ); string oldPhoneNumber = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add( phoneNumber ); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); foreach ( var phoneNumber in person.PhoneNumbers .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) ) .ToList() ) { History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ), phoneNumber.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference; if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if ( imgPhoto.CropBinaryFileId.HasValue ) { if ( imgPhoto.CropBinaryFileId != person.PhotoId ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } } // save address if ( pnlAddress.Visible ) { Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroup = new GroupService( rockContext ).Queryable() .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value && f.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyGroup != null ) { Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull(); if ( addressTypeGuid.HasValue ) { var groupLocationService = new GroupLocationService( rockContext ); var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value ); var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault(); if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { // delete the current address History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty ); groupLocationService.Delete( familyAddress ); rockContext.SaveChanges(); } else { if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { if ( familyAddress == null ) { familyAddress = new GroupLocation(); groupLocationService.Add( familyAddress ); familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id; familyAddress.GroupId = familyGroup.Id; familyAddress.IsMailingLocation = true; familyAddress.IsMappedLocation = true; } else if ( hfStreet1.Value != string.Empty ) { // user clicked move so create a previous address var previousAddress = new GroupLocation(); groupLocationService.Add( previousAddress ); var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() ); if ( previousAddressValue != null ) { previousAddress.GroupLocationTypeValueId = previousAddressValue.Id; previousAddress.GroupId = familyGroup.Id; Location previousAddressLocation = new Location(); previousAddressLocation.Street1 = hfStreet1.Value; previousAddressLocation.Street2 = hfStreet2.Value; previousAddressLocation.City = hfCity.Value; previousAddressLocation.State = hfState.Value; previousAddressLocation.PostalCode = hfPostalCode.Value; previousAddressLocation.Country = hfCountry.Value; previousAddress.Location = previousAddressLocation; } } familyAddress.IsMailingLocation = cbIsMailingAddress.Checked; familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked; var updatedHomeAddress = new Location(); acAddress.GetValues( updatedHomeAddress ); History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() ); familyAddress.Location = updatedHomeAddress; rockContext.SaveChanges(); } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } } } } NavigateToParentPage(); } } } ); }
/// <summary> /// Gets the person. /// </summary> /// <param name="create">if set to <c>true</c> [create].</param> /// <returns></returns> private Person GetPerson( bool create ) { Person person = null; var rockContext = new RockContext(); var personService = new PersonService( rockContext ); Group familyGroup = null; int personId = ViewState["PersonId"] as int? ?? 0; if ( personId == 0 && TargetPerson != null ) { person = TargetPerson; } else { if ( personId != 0 ) { person = personService.Get( personId ); } if ( person == null && create ) { // Check to see if there's only one person with same email, first name, and last name if ( !string.IsNullOrWhiteSpace( txtEmail.Text ) && !string.IsNullOrWhiteSpace( txtFirstName.Text ) && !string.IsNullOrWhiteSpace( txtLastName.Text ) ) { // Same logic as CreatePledge.ascx.cs var personMatches = personService.GetByMatch( txtFirstName.Text, txtLastName.Text, txtEmail.Text ); if ( personMatches.Count() == 1 ) { person = personMatches.FirstOrDefault(); } else { person = null; } } if ( person == null ) { // Create Person person = new Person(); person.FirstName = txtFirstName.Text; person.LastName = txtLastName.Text; person.Email = txtEmail.Text; person.EmailPreference = EmailPreference.EmailAllowed; if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false ) { var phone = new PhoneNumber(); phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); phone.NumberTypeValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME ) ).Id; person.PhoneNumbers.Add( phone ); } // Create Family familyGroup = GroupService.SaveNewFamily( rockContext, person, null, false ); } ViewState["PersonId"] = person != null ? person.Id : 0; } } if ( create && person != null ) // person should never be null at this point { if ( familyGroup == null ) { var groupLocationService = new GroupLocationService( rockContext ); if ( GroupLocationId.HasValue ) { familyGroup = groupLocationService.Queryable() .Where( gl => gl.Id == GroupLocationId.Value ) .Select( gl => gl.Group ) .FirstOrDefault(); } else { familyGroup = personService.GetFamilies( person.Id ).FirstOrDefault(); } } if ( familyGroup != null ) { GroupService.AddNewFamilyAddress( rockContext, familyGroup, GetAttributeValue( "AddressType" ), acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country, true ); } } return person; }