/// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            using ( new UnitOfWorkScope() )
            {
                GroupLocationService groupLocationService = new GroupLocationService();
                ScheduleService scheduleService = new ScheduleService();

                RockTransactionScope.WrapTransaction( () =>
                {
                    var gridViewRows = gGroupLocationSchedule.Rows;
                    foreach ( GridViewRow row in gridViewRows.OfType<GridViewRow>() )
                    {
                        int groupLocationId = int.Parse( gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string );
                        GroupLocation groupLocation = groupLocationService.Get( groupLocationId );
                        if ( groupLocation != null )
                        {
                            foreach ( var fieldCell in row.Cells.OfType<DataControlFieldCell>() )
                            {
                                CheckBoxEditableField checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField;
                                if ( checkBoxTemplateField != null )
                                {
                                    CheckBox checkBox = fieldCell.Controls[0] as CheckBox;
                                    string dataField = ( fieldCell.ContainingField as CheckBoxEditableField ).DataField;
                                    int scheduleId = int.Parse( dataField.Replace( "scheduleField_", string.Empty ) );

                                    // update GroupLocationSchedule depending on if the Schedule is Checked or not
                                    if ( checkBox.Checked )
                                    {
                                        // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it
                                        if ( !groupLocation.Schedules.Any( a => a.Id == scheduleId ) )
                                        {
                                            var schedule = scheduleService.Get( scheduleId );
                                            groupLocation.Schedules.Add( schedule );
                                        }
                                    }
                                    else
                                    {
                                        // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it
                                        if ( groupLocation.Schedules.Any( a => a.Id == scheduleId ) )
                                        {
                                            groupLocation.Schedules.Remove( groupLocation.Schedules.FirstOrDefault( a => a.Id == scheduleId ) );
                                        }
                                    }
                                }
                            }

                            groupLocationService.Save( groupLocation, this.CurrentPersonId );
                        }
                    }

                } );
            }

            NavigateToParentPage();
        }
Esempio n. 2
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            // 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( () =>
                {

                    using ( new UnitOfWorkScope() )
                    {
                        var familyService = new GroupService();
                        var familyMemberService = new GroupMemberService();
                        var personService = new PersonService();
                        var historyService = new HistoryService();

                        var familyChanges = new List<string>();

                        // SAVE FAMILY
                        _family = familyService.Get( _family.Id );

                        History.EvaluateChange( familyChanges, "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;

                        familyService.Save( _family, CurrentPersonId );

                        // SAVE FAMILY MEMBERS
                        int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt();
                        int? reasonValueId = ddlReason.SelectedValueAsInt();
                        var newFamilies = new List<Group>();

                        foreach ( var familyMember in FamilyMembers )
                        {
                            var 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;
                                    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 );
                                    }

                                    groupMember.Person = person;
                                }
                                else
                                {
                                    // added from other family
                                    groupMember.Person = personService.Get( familyMember.Id );
                                }

                                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, string.Format( "Role", _family.Name ), string.Empty, role.Name );
                                    groupMember.GroupRoleId = role.Id;
                                }

                                if ( groupMember.Person != null )
                                {
                                    familyMemberService.Add( groupMember, CurrentPersonId );
                                    familyMemberService.Save( groupMember, CurrentPersonId );
                                }

                            }
                            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>();
                                        newFamilyChanges.Add( "Created" );

                                        // 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, "Name", 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, CurrentPersonId );
                                        familyService.Save( newFamily, CurrentPersonId );

                                        historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                            newFamily.Id, newFamilyChanges, CurrentPersonId );

                                        // 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;
                                        familyMemberService.Save( groupMember, CurrentPersonId );

                                        var newMemberChanges = new List<string>();
                                        History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name );
                                        historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                            groupMember.Person.Id, newMemberChanges, CurrentPersonId );

                                        History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty );

                                        newFamilies.Add( newFamily );
                                    }
                                    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;

                                            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;

                                            familyMemberService.Save( groupMember, CurrentPersonId );
                                        }
                                    }
                                }
                            }

                            // Remove anyone that was moved from another family
                            if ( familyMember.RemoveFromOtherFamilies )
                            {
                                var otherFamilies = familyMemberService.Queryable()
                                    .Where( m =>
                                        m.PersonId == familyMember.Id &&
                                        m.Group.GroupTypeId == familyGroupTypeId &&
                                        m.GroupId != _family.Id )
                                    .ToList();

                                foreach ( var otherFamilyMember in otherFamilies )
                                {
                                    var fm = familyMemberService.Get( otherFamilyMember.Id );

                                    // 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;

                                        personService.Save( person, CurrentPersonId );
                                    }

                                    var oldMemberChanges = new List<string>();
                                    History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty );

                                    familyMemberService.Delete( fm, CurrentPersonId );
                                    familyMemberService.Save( fm, CurrentPersonId );

                                    historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                        fm.Person.Id, oldMemberChanges, CurrentPersonId );

                                    var f = familyService.Queryable()
                                        .Where( g =>
                                            g.Id == otherFamilyMember.GroupId &&
                                            !g.Members.Any() )
                                        .FirstOrDefault();

                                    if ( f != null )
                                    {
                                        var oldFamilyChanges = new List<string>();
                                        oldFamilyChanges.Add( "Deleted" );
                                        historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                            f.Id, oldFamilyChanges, CurrentPersonId );

                                        familyService.Delete( f, CurrentPersonId );
                                        familyService.Save( f, CurrentPersonId );
                                    }
                                }
                            }

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

                            historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id, CurrentPersonId );
                        }

                        // SAVE LOCATIONS
                        var groupLocationService = new GroupLocationService();

                        // delete any group locations that were removed
                        var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList();
                        foreach ( var removedLocation in groupLocationService.Queryable( "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, CurrentPersonId );
                            groupLocationService.Save( removedLocation, CurrentPersonId );
                        }

                        foreach ( var familyAddress in FamilyAddresses )
                        {
                            Location updatedAddress = null;
                            if ( familyAddress.LocationIsDirty )
                            {
                                updatedAddress = new LocationService().Get(
                                    familyAddress.Street1, familyAddress.Street2, familyAddress.City,
                                    familyAddress.State, familyAddress.Zip );
                            }

                            GroupLocation groupLocation = null;
                            if ( familyAddress.Id > 0 )
                            {
                                groupLocation = groupLocationService.Get( familyAddress.Id );
                            }
                            if ( groupLocation == null )
                            {
                                groupLocation = new GroupLocation();
                                groupLocation.GroupId = _family.Id;
                                groupLocationService.Add( groupLocation, CurrentPersonId );
                            }

                            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 + " Location Is Mailing",
                                groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() );
                            groupLocation.IsMailingLocation = familyAddress.IsMailing;

                            History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location Is Location",
                                groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() );
                            groupLocation.IsMappedLocation = familyAddress.IsLocation;

                            if ( updatedAddress != null )
                            {
                                History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location",
                                    groupLocation.Location.ToString(), updatedAddress.ToString() );
                                groupLocation.Location = updatedAddress;
                            }

                            groupLocationService.Save( groupLocation, CurrentPersonId );

                            // Add the same locations to any new families created by removing an existing family member
                            if ( newFamilies.Any() )
                            {
                                //reload grouplocation for access to child properties
                                groupLocation = groupLocationService.Get( groupLocation.Id );
                                foreach ( var newFamily in newFamilies )
                                {
                                    var newFamilyLocation = new GroupLocation();
                                    newFamilyLocation.GroupId = newFamily.Id;
                                    newFamilyLocation.LocationId = groupLocation.LocationId;
                                    newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId;
                                    newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation;
                                    newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation;
                                    groupLocationService.Add( newFamilyLocation, CurrentPersonId );
                                    groupLocationService.Save( newFamilyLocation, CurrentPersonId );
                                }
                            }
                        }

                        historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            _family.Id, familyChanges, CurrentPersonId );

                        _family = familyService.Get( _family.Id );
                        if ( _family.Members.Any( m => m.PersonId == Person.Id ) )
                        {
                            Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                        }
                        else
                        {
                            var fm = _family.Members
                                .Where( m =>
                                    m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) &&
                                    m.Person.Gender == Gender.Male )
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                            if ( fm == null )
                            {
                                fm = _family.Members
                                    .Where( m =>
                                        m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) )
                                    .OrderByDescending( m => m.Person.Age )
                                    .FirstOrDefault();
                            }
                            if ( fm == null )
                            {
                                fm = _family.Members
                                    .OrderByDescending( m => m.Person.Age )
                                    .FirstOrDefault();
                            }
                            if ( fm != null )
                            {
                                Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false );
                            }
                            else
                            {
                                Response.Redirect( "~", false );
                            }
                        }

                    }
                } );
            }
        }