public static SaveChanges ( |
||
rockContext | The rock context. | |
modelType | Type of the model. | |
categoryGuid | System.Guid | The category unique identifier. |
entityId | int | The entity identifier. |
changes | List |
The changes. |
commitSave | bool | if set to |
modifiedByPersonAliasId | int | The modified by person alias identifier. |
return | void |
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { var rockContext = dbContext as RockContext; if (GroupHistoryChanges != null && GroupHistoryChanges.Any()) { HistoryService.SaveChanges(rockContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), GroupId, GroupHistoryChanges, true, this.ModifiedByPersonAliasId); } // If this is a Group of type Family, update the ModifiedDateTime on the Persons that are members of this family (since one of their Addresses changed) int groupTypeIdFamily = GroupTypeCache.GetFamilyGroupType().Id; var groupService = new GroupService(rockContext); int groupTypeId = groupService.GetSelect(this.GroupId, s => s.GroupTypeId); if (groupTypeId == groupTypeIdFamily) { var currentDateTime = RockDateTime.Now; var qryPersonsToUpdate = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == this.GroupId).Select(a => a.Person); rockContext.BulkUpdate(qryPersonsToUpdate, p => new Person { ModifiedDateTime = currentDateTime, ModifiedByPersonAliasId = this.ModifiedByPersonAliasId }); } base.PostSaveChanges(dbContext); }
/// <summary> /// Called after the save operation has been executed /// </summary> protected override void PostSave() { var rockContext = ( RockContext )this.RockContext; if (PersonHistoryChangeList?.Any() == true) { var personAlias = Entity.PersonAlias ?? new PersonAliasService(rockContext).Get(Entity.PersonAliasId); HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_STEP.AsGuid(), personAlias.PersonId, PersonHistoryChangeList, Entity.Caption, typeof(Step), Entity.Id, true, Entity.ModifiedByPersonAliasId, (rockContext.SourceOfChange)); } base.PostSave(); UpdateStepProgramCompletion(rockContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChanges != null) { foreach (var historyItem in HistoryChanges) { int personId = historyItem.PersonId > 0 ? historyItem.PersonId : PersonId; // if GroupId is 0, it is probably a Group that wasn't saved yet, so get the GroupId from historyItem.Group.Id instead if (historyItem.GroupId == 0) { historyItem.GroupId = historyItem.Group?.Id; } HistoryService.SaveChanges( ( RockContext )dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), personId, historyItem.PersonHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); HistoryService.SaveChanges( ( RockContext )dbContext, typeof(GroupMember), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), this.Id, historyItem.GroupMemberHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } base.PostSaveChanges(dbContext); // if this is a GroupMember record on a Family, ensure that AgeClassification, PrimaryFamily is updated // NOTE: This is also done on Person.PostSaveChanges in case Birthdate changes var groupTypeFamilyRoleIds = GroupTypeCache.GetFamilyGroupType()?.Roles?.Select(a => a.Id).ToList(); if (groupTypeFamilyRoleIds?.Any() == true) { if (groupTypeFamilyRoleIds.Contains(this.GroupRoleId)) { PersonService.UpdatePersonAgeClassification(this.PersonId, dbContext as RockContext); PersonService.UpdatePrimaryFamily(this.PersonId, dbContext as RockContext); PersonService.UpdateGivingLeaderId(this.PersonId, dbContext as RockContext); } } }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges( Data.DbContext dbContext ) { if ( HistoryChanges != null && HistoryChanges.Any() && HistoryPersonId.HasValue ) { HistoryService.SaveChanges( (RockContext)dbContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), HistoryPersonId.Value, HistoryChanges, true, this.ModifiedByPersonAliasId ); } base.PostSaveChanges( dbContext ); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChangeList?.Any() == true) { HistoryService.SaveChanges(( RockContext )dbContext, typeof(FinancialScheduledTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), this.ScheduledTransactionId, HistoryChangeList, true, this.ModifiedByPersonAliasId); } base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (GroupHistoryChanges != null && GroupHistoryChanges.Any()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), GroupId, GroupHistoryChanges, true, this.ModifiedByPersonAliasId); } base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChangeList != null && HistoryChangeList.Any()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), this.Id, HistoryChangeList, this.Name, null, null, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } base.PostSaveChanges(dbContext); }
/// <summary> /// Called after the save operation has been executed /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { var rockContext = ( RockContext )this.RockContext; if (HistoryChanges?.Any() == true && HistoryPersonId.HasValue) { HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), HistoryPersonId.Value, HistoryChanges, true, Entity.ModifiedByPersonAliasId); } base.PostSave(); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (PersonHistoryChanges != null) { foreach (var keyVal in PersonHistoryChanges) { int personId = keyVal.Key > 0 ? keyVal.Key : PersonId; HistoryService.SaveChanges((RockContext)dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId, keyVal.Value, true, this.ModifiedByPersonAliasId); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChanges != null) { foreach (var historyItem in HistoryChanges.Where(h => h.Changes.Any())) { int personId = historyItem.PersonId > 0 ? historyItem.PersonId : PersonId; HistoryService.SaveChanges((RockContext)dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), personId, historyItem.Changes, historyItem.Caption, typeof(Group), historyItem.GroupId, true, this.ModifiedByPersonAliasId); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved by context /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { if (_declinedScheduledAttendance) { new LaunchGroupScheduleCancellationWorkflow.Message() { AttendanceId = Entity.Id }.Send(); } if (!_isDeleted) { // Process any streaks that may occur as a result of adding/modifying an attendance record. // If there are any, they need to be processed in this thread in case there are any achievement changes // that need to be detected as a result of this attendance. StreakTypeService.HandleAttendanceRecord(Entity.Id); } var rockContext = ( RockContext )this.RockContext; if (PersonAttendanceHistoryChangeList?.Any() == true) { var attendanceId = Entity.Id; if (preSavePersonAliasId.HasValue) { var attendeePersonId = new PersonAliasService(this.RockContext).GetPersonId(preSavePersonAliasId.Value); if (attendeePersonId.HasValue) { var entityTypeType = typeof(Person); var relatedEntityTypeType = typeof(Attendance); HistoryService.SaveChanges( rockContext, entityTypeType, Rock.SystemGuid.Category.HISTORY_ATTENDANCE_CHANGES.AsGuid(), attendeePersonId.Value, this.PersonAttendanceHistoryChangeList, $"Attendance {attendanceId}", relatedEntityTypeType, attendanceId, true, Entity.ModifiedByPersonAliasId, rockContext.SourceOfChange); } } } base.PostSave(); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { int?historyEntityId = (HistoryEntityId.HasValue && HistoryEntityId.Value > 0) ? HistoryEntityId.Value : this.EntityId; var rockContext = dbContext as RockContext; if (HistoryChanges != null && HistoryChanges.Any() && HistoryEntityTypeId.HasValue && historyEntityId.HasValue) { if (HistoryEntityTypeId.Value == EntityTypeCache.Get(typeof(Person)).Id) { HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), historyEntityId.Value, HistoryChanges, string.Empty, typeof(Attribute), AttributeId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } else { HistoryService.SaveChanges(rockContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), historyEntityId.Value, HistoryChanges, string.Empty, typeof(Attribute), AttributeId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } if (this.PostSaveAttributeValueHistoryCurrent) { var attributeValueHistoricalService = new AttributeValueHistoricalService(rockContext); var attributeValueHistoricalPreviousCurrentRow = attributeValueHistoricalService.Queryable().Where(a => a.AttributeValueId == this.Id && a.CurrentRowIndicator == true).FirstOrDefault(); var saveChangesDateTime = RockDateTime.Now; if (attributeValueHistoricalPreviousCurrentRow != null) { attributeValueHistoricalPreviousCurrentRow.CurrentRowIndicator = false; attributeValueHistoricalPreviousCurrentRow.ExpireDateTime = saveChangesDateTime; } var attributeValueHistoricalCurrent = AttributeValueHistorical.CreateCurrentRowFromAttributeValue(this, saveChangesDateTime); attributeValueHistoricalService.Add(attributeValueHistoricalCurrent); rockContext.SaveChanges(); } // If this a Person Attribute, Update the ModifiedDateTime on the Person that this AttributeValue is associated with if (this.EntityId.HasValue && AttributeCache.Get(this.AttributeId)?.EntityTypeId == EntityTypeCache.Get <Rock.Model.Person>().Id) { var currentDateTime = RockDateTime.Now; int personId = this.EntityId.Value; var qryPersonsToUpdate = new PersonService(rockContext).Queryable(true, true).Where(a => a.Id == personId); rockContext.BulkUpdate(qryPersonsToUpdate, p => new Person { ModifiedDateTime = currentDateTime, ModifiedByPersonAliasId = this.ModifiedByPersonAliasId }); } base.PostSaveChanges(dbContext); }
/// <summary> /// Called after the save operation has been executed /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { var rockContext = ( RockContext )this.RockContext; if (HistoryChangeList?.Any() == true) { HistoryService.SaveChanges(rockContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), Entity.Id, HistoryChangeList, Entity.Name, null, null, true, Entity.ModifiedByPersonAliasId, rockContext.SourceOfChange); } if (_FamilyCampusIsChanged) { PersonService.UpdatePrimaryFamilyByGroup(Entity.Id, rockContext); } base.PostSave(); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChangeList.Any()) { HistoryService.SaveChanges(( RockContext )dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), this.TransactionId, HistoryChangeList, true, this.ModifiedByPersonAliasId); var txn = new FinancialTransactionService(( RockContext )dbContext).GetSelect(this.TransactionId, s => new { s.Id, s.BatchId }); if (txn != null && txn.BatchId != null) { var batchHistory = new History.HistoryChangeList(); batchHistory.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, $"Transaction ID:{txn.Id}"); HistoryService.SaveChanges(( RockContext )dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.BatchId.Value, batchHistory, string.Empty, typeof(FinancialTransaction), this.TransactionId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(DbContext dbContext) { if (HistoryChangeList.Any()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), this.Id, HistoryChangeList, true, this.ModifiedByPersonAliasId); } foreach (var keyVal in BatchHistoryChangeList) { if (keyVal.Value.Any()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), keyVal.Key, keyVal.Value, string.Empty, typeof(FinancialTransaction), this.Id, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { int?historyEntityId = (HistoryEntityId.HasValue && HistoryEntityId.Value > 0) ? HistoryEntityId.Value : this.EntityId; if (HistoryChanges != null && HistoryChanges.Any() && HistoryEntityTypeId.HasValue && historyEntityId.HasValue) { if (HistoryEntityTypeId.Value == EntityTypeCache.Read(typeof(Person)).Id) { HistoryService.SaveChanges((RockContext)dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), historyEntityId.Value, HistoryChanges, string.Empty, typeof(Attribute), AttributeId, true, this.ModifiedByPersonAliasId); } else { HistoryService.SaveChanges((RockContext)dbContext, typeof(Group), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), historyEntityId.Value, HistoryChanges, string.Empty, typeof(Attribute), AttributeId, true, this.ModifiedByPersonAliasId); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(DbContext dbContext) { if (HistoryChanges.Any()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), this.TransactionId, HistoryChanges, true, this.ModifiedByPersonAliasId); var txn = new FinancialTransactionService((RockContext)dbContext).Get(this.TransactionId); if (txn != null && txn.BatchId != null) { var batchHistory = new List <string> { string.Format("Updated <span class='field-name'>Transaction</span> ID: <span class='field-value'>{0}</span>.", txn.Id) }; HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.BatchId.Value, batchHistory, string.Empty, typeof(FinancialTransaction), this.TransactionId, true, this.ModifiedByPersonAliasId); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved by context /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChangeList.Any()) { foreach (var txn in new FinancialTransactionService((RockContext)dbContext) .Queryable().AsNoTracking() .Where(t => t.FinancialPaymentDetailId == this.Id) .Select(t => new { t.Id, t.BatchId }) .ToList()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.Id, HistoryChangeList, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); var batchHistory = new History.HistoryChangeList(); batchHistory.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Property, "Transaction"); HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.BatchId.Value, batchHistory, string.Empty, typeof(FinancialTransaction), txn.Id, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Called after the save operation has been executed /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { var personId = Entity.PersonId; if (personId.HasValue && State == EntityContextState.Added) { // if EntityPerson doesn't lazy load, get it from the database using the same RockContext as this UserLogin record. var userLoginPerson = Entity.Person ?? new PersonService(this.RockContext).Get(personId.Value); // If this is a new userLogin for this person, ensure that the AccountProtection profile is at least Medium. // Note that if this UserLogin is deleted, we'll let the RockCleanup job re-calculate their AccountProtectionProfile. if (userLoginPerson != null && userLoginPerson.AccountProtectionProfile < Utility.Enums.AccountProtectionProfile.Medium) { // use a new RockContext to elevate the AccountProtection level to Medium using (var rockContext = new RockContext()) { var accountProtectionProfilePerson = new PersonService(rockContext).Get(personId.Value); // double check that account protection profile needs to be elevated to medium if (accountProtectionProfilePerson != null && accountProtectionProfilePerson.AccountProtectionProfile < Utility.Enums.AccountProtectionProfile.Medium) { accountProtectionProfilePerson.AccountProtectionProfile = Utility.Enums.AccountProtectionProfile.Medium; rockContext.SaveChanges(); } } } } if (HistoryChanges?.Any() == true && Entity.PersonId.HasValue) { try { HistoryService.SaveChanges(RockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), Entity.PersonId.Value, HistoryChanges, Entity.UserName, typeof(UserLogin), Entity.Id, true, Entity.ModifiedByPersonAliasId, null); } catch (Exception ex) { // Just log the problem and move on... ExceptionLogService.LogException(ex); } } base.PostSave(); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved by context /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChanges.Any()) { foreach (var txn in new FinancialTransactionService((RockContext)dbContext) .Queryable().AsNoTracking() .Where(t => t.FinancialPaymentDetailId == this.Id) .Select(t => new { t.Id, t.BatchId }) .ToList()) { HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.Id, HistoryChanges, true, this.ModifiedByPersonAliasId); var batchHistory = new List <string> { string.Format("Updated <span class='field-name'>Transaction</span> ID: <span class='field-value'>{0}</span>.", txn.Id) }; HistoryService.SaveChanges((RockContext)dbContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), txn.BatchId.Value, batchHistory, string.Empty, typeof(FinancialTransaction), txn.Id, true, this.ModifiedByPersonAliasId); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately after the item is saved. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { var rockContext = ( RockContext )dbContext; // It is possible that we have a UserLogin without a PersonId, in these cases we don't want to save a person history record. if (HistoryChanges != null && HistoryChanges.Any() && this.PersonId.HasValue) { try { HistoryService.SaveChanges(( RockContext )dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), this.PersonId.Value, HistoryChanges, this.UserName, typeof(UserLogin), this.Id, true, this.ModifiedByPersonAliasId, null); } catch (Exception ex) { // Just log the problem and move on... ExceptionLogService.LogException(ex); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { var rockContext = dbContext as RockContext; if (PersonHistoryChanges != null) { foreach (var keyVal in PersonHistoryChanges) { int personId = keyVal.Key > 0 ? keyVal.Key : PersonId; HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId, keyVal.Value, true, this.ModifiedByPersonAliasId); } } // update the ModifiedDateTime on the Person that this phone number is associated with var currentDateTime = RockDateTime.Now; var qryPersonsToUpdate = new PersonService(rockContext).Queryable(true, true).Where(a => a.Id == this.PersonId); rockContext.BulkUpdate(qryPersonsToUpdate, p => new Person { ModifiedDateTime = currentDateTime, ModifiedByPersonAliasId = this.ModifiedByPersonAliasId }); base.PostSaveChanges(dbContext); }
/// <summary> /// Posts the save changes. /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Data.DbContext dbContext) { if (HistoryChanges != null) { foreach (var historyItem in HistoryChanges) { int personId = historyItem.PersonId > 0 ? historyItem.PersonId : PersonId; // if GroupId is 0, it is probably a Group that wasn't saved yet, so get the GroupId from historyItem.Group.Id instead if (historyItem.GroupId == 0) { historyItem.GroupId = historyItem.Group?.Id; } HistoryService.SaveChanges((RockContext)dbContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), personId, historyItem.PersonHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); HistoryService.SaveChanges(( RockContext )dbContext, typeof(GroupMember), Rock.SystemGuid.Category.HISTORY_GROUP_CHANGES.AsGuid(), this.Id, historyItem.GroupMemberHistoryChangeList, historyItem.Caption, typeof(Group), historyItem.GroupId, true, this.ModifiedByPersonAliasId, dbContext.SourceOfChange); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Method that will be called on an entity immediately before the item is saved by context. Takes /// care of logging any particular change history for user login. /// </summary> /// <param name="dbContext"></param> /// <param name="entry"></param> public override void PreSaveChanges(Rock.Data.DbContext dbContext, DbEntityEntry entry) { var rockContext = ( RockContext )dbContext; HistoryChanges = new History.HistoryChangeList(); switch (entry.State) { case EntityState.Added: { // Get the authentication provider entity type var entityType = EntityTypeCache.Get(this.EntityTypeId ?? 0); var change = HistoryChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Authentication Provider").SetNewValue(entityType?.FriendlyName); // Don't log Pin Authentication user names. var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false; if (isUserNameSensitive) { change.SetCaption("User Account"); } History.EvaluateChange(HistoryChanges, "User Login", string.Empty, UserName, isUserNameSensitive); History.EvaluateChange(HistoryChanges, "Is Confirmed", null, IsConfirmed); History.EvaluateChange(HistoryChanges, "Is Password Change Required", null, IsPasswordChangeRequired); History.EvaluateChange(HistoryChanges, "Is Locked Out", null, IsLockedOut); break; } case EntityState.Modified: { var entityType = EntityTypeCache.Get(this.EntityTypeId ?? 0); // Don't log Pin Authentication user names. var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false; History.EvaluateChange(HistoryChanges, "User Login", entry.OriginalValues["UserName"].ToStringSafe(), UserName, isUserNameSensitive); History.EvaluateChange(HistoryChanges, "Is Confirmed", entry.OriginalValues["IsConfirmed"].ToStringSafe().AsBooleanOrNull(), IsConfirmed); History.EvaluateChange(HistoryChanges, "Is Password Change Required", entry.OriginalValues["IsPasswordChangeRequired"].ToStringSafe().AsBooleanOrNull(), IsPasswordChangeRequired); History.EvaluateChange(HistoryChanges, "Is Locked Out", entry.OriginalValues["IsLockedOut"].ToStringSafe().AsBooleanOrNull(), IsLockedOut); History.EvaluateChange(HistoryChanges, "Password", entry.OriginalValues["Password"].ToStringSafe(), Password, true); // Did the provider type change? int?origEntityTypeId = entry.OriginalValues["EntityTypeId"].ToStringSafe().AsIntegerOrNull(); int?entityTypeId = EntityType != null ? EntityType.Id : EntityTypeId; if (!entityTypeId.Equals(origEntityTypeId)) { var origProviderType = EntityTypeCache.Get(origEntityTypeId ?? 0)?.FriendlyName; var providerType = EntityTypeCache.Get(this.EntityTypeId ?? 0)?.FriendlyName; History.EvaluateChange(HistoryChanges, "User Login", origProviderType, providerType); } // Change the caption if this is a sensitive user account if (HistoryChanges.Count > 0 && isUserNameSensitive) { var change = HistoryChanges.FirstOrDefault(); change.SetCaption("User Account"); } break; } case EntityState.Deleted: { // By this point EF has stripped out some of the data we need to save history // Reload the data using a new context. RockContext newRockContext = new RockContext(); var userLogin = new UserLoginService(newRockContext).Get(this.Id); if (userLogin != null && userLogin.PersonId != null) { try { var entityType = EntityTypeCache.Get(userLogin.EntityTypeId ?? 0); var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false; if (!isUserNameSensitive) { HistoryChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "User Login").SetOldValue(userLogin.UserName); HistoryService.SaveChanges(newRockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), userLogin.PersonId.Value, HistoryChanges, UserName, typeof(UserLogin), this.Id, true, userLogin.ModifiedByPersonAliasId, null); } else { HistoryChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Authentication Provider").SetOldValue(entityType?.FriendlyName).SetCaption("User Account"); HistoryService.SaveChanges(newRockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), userLogin.PersonId.Value, HistoryChanges, entityType?.FriendlyName, typeof(UserLogin), this.Id, true, userLogin.ModifiedByPersonAliasId, null); } } catch (Exception ex) { // Just log the problem and move on... ExceptionLogService.LogException(ex); } } HistoryChanges.Clear(); return; } } base.PreSaveChanges(dbContext, entry); }
protected void btnNext_Click( object sender, EventArgs e ) { if ( Page.IsValid ) { if ( CurrentCategoryIndex < attributeControls.Count ) { CurrentCategoryIndex++; ShowAttributeCategory( CurrentCategoryIndex ); } else { var familyMembers = GetControlData(); if ( familyMembers.Any() ) { RockTransactionScope.WrapTransaction( () => { using ( new UnitOfWorkScope() ) { var familyGroupType = GroupTypeCache.GetFamilyGroupType(); var familyChanges = new List<string>(); var familyMemberChanges = new Dictionary<Guid, List<string>>(); var familyDemographicChanges = new Dictionary<Guid, List<string>>(); if ( familyGroupType != null ) { var groupService = new GroupService(); var groupTypeRoleService = new GroupTypeRoleService(); var familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyChanges.Add("Created"); familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family"; History.EvaluateChange( familyChanges, "Name", string.Empty, familyGroup.Name ); int? campusId = cpCampus.SelectedValueAsInt(); if (campusId.HasValue) { History.EvaluateChange( familyChanges, "Campus", string.Empty, CampusCache.Read( campusId.Value ).Name ); } familyGroup.CampusId = campusId; foreach(var familyMember in familyMembers) { var person = familyMember.Person; if ( person != null ) { familyGroup.Members.Add( familyMember ); var demographicChanges = new List<string>(); demographicChanges.Add( "Created" ); History.EvaluateChange( demographicChanges, "Record Status", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusReasonValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Title", string.Empty, person.TitleValueId.HasValue ? DefinedValueCache.GetName( person.TitleValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName); History.EvaluateChange( demographicChanges, "Nick Name", string.Empty, person.NickName ); History.EvaluateChange( demographicChanges, "Middle Name", string.Empty, person.MiddleName ); History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); History.EvaluateChange( demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName( person.ConnectionStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Graduation Date", null, person.GraduationDate ); familyDemographicChanges.Add( person.Guid, demographicChanges ); var memberChanges = new List<string>(); string roleName = familyGroupType.Roles[familyMember.GroupRoleId] ?? string.Empty; History.EvaluateChange( memberChanges, "Role", string.Empty, roleName ); familyMemberChanges.Add( person.Guid, memberChanges ); } } if ( !String.IsNullOrWhiteSpace( tbStreet1.Text ) || !String.IsNullOrWhiteSpace( tbStreet2.Text ) || !String.IsNullOrWhiteSpace( tbCity.Text ) || !String.IsNullOrWhiteSpace( tbZip.Text ) ) { string addressChangeField = "Address"; var groupLocation = new GroupLocation(); var location = new LocationService().Get( tbStreet1.Text, tbStreet2.Text, tbCity.Text, ddlState.SelectedValue, tbZip.Text ); groupLocation.Location = location; Guid locationTypeGuid = Guid.Empty; if ( Guid.TryParse( GetAttributeValue( "LocationType" ), out locationTypeGuid ) ) { var locationType = Rock.Web.Cache.DefinedValueCache.Read( locationTypeGuid ); if ( locationType != null ) { addressChangeField = string.Format("{0} Address", locationType.Name); groupLocation.GroupLocationTypeValueId = locationType.Id; } } familyGroup.GroupLocations.Add( groupLocation ); History.EvaluateChange( familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString() ); } groupService.Add( familyGroup, CurrentPersonId ); groupService.Save( familyGroup, CurrentPersonId ); var historyService = new HistoryService(); historyService.SaveChanges( typeof( Group ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyGroup.Id, familyChanges, CurrentPersonId ); var personService = new PersonService(); foreach ( var groupMember in familyMembers ) { var person = personService.Get( groupMember.PersonId ); if ( person != null ) { var changes = familyDemographicChanges[person.Guid]; if ( groupMember.GroupRoleId != _childRoleId ) { person.GivingGroupId = familyGroup.Id; personService.Save( person, CurrentPersonId ); History.EvaluateChange( changes, "Giving Group", string.Empty, familyGroup.Name ); } foreach ( var attributeControl in attributeControls ) { foreach ( var attribute in attributeControl.AttributeList ) { string attributeValue = person.GetAttributeValue( attribute.Key ); if ( !string.IsNullOrWhiteSpace( attributeValue ) ) { Rock.Attribute.Helper.SaveAttributeValue( person, attribute, attributeValue, CurrentPersonId ); attributeValue = attribute.FieldType.Field.FormatValue( null, attributeValue, attribute.QualifierValues, false ); History.EvaluateChange( changes, attribute.Name, string.Empty, attributeValue ); } } } historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes, CurrentPersonId ); historyService.SaveChanges( typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof( Group), familyGroup.Id, CurrentPersonId ); } } } } } ); Response.Redirect( string.Format( "~/Person/{0}", familyMembers[0].Person.Id ), false ); } } } }
/// <summary> /// Creates a new <see cref="Rock.Model.UserLogin" /> /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="person">The <see cref="Rock.Model.Person" /> that this <see cref="UserLogin" /> will be associated with.</param> /// <param name="serviceType">The <see cref="Rock.Model.AuthenticationServiceType" /> type of Login</param> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="username">A <see cref="System.String" /> containing the UserName.</param> /// <param name="password">A <see cref="System.String" /> containing the unhashed/unencrypted password.</param> /// <param name="isConfirmed">A <see cref="System.Boolean" /> flag indicating if the user has been confirmed.</param> /// <returns></returns> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the Username already exists.</exception> /// <exception cref="System.ArgumentException">Thrown when the service does not exist or is not active.</exception> public static UserLogin Create(RockContext rockContext, Rock.Model.Person person, AuthenticationServiceType serviceType, int entityTypeId, string username, string password, bool isConfirmed) { if (person != null) { var userLoginService = new UserLoginService(rockContext); var entityType = EntityTypeCache.Read(entityTypeId); if (entityType != null) { UserLogin user = userLoginService.GetByUserName(username); if (user != null) { throw new ArgumentOutOfRangeException("username", "Username already exists"); } DateTime createDate = RockDateTime.Now; user = new UserLogin(); user.Guid = Guid.NewGuid(); user.EntityTypeId = entityTypeId; user.UserName = username; user.IsConfirmed = isConfirmed; user.LastPasswordChangedDateTime = createDate; user.PersonId = person.Id; if (serviceType == AuthenticationServiceType.Internal) { var authenticationComponent = AuthenticationContainer.GetComponent(entityType.Name); if (authenticationComponent == null || !authenticationComponent.IsActive) { throw new ArgumentException(string.Format("'{0}' service does not exist, or is not active", entityType.FriendlyName), "entityTypeId"); } user.Password = authenticationComponent.EncodePassword(user, password); } userLoginService.Add(user); rockContext.SaveChanges(); var historyCategory = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext); if (historyCategory != null) { var changes = new List <string>(); History.EvaluateChange(changes, "User Login", string.Empty, username); HistoryService.SaveChanges(rockContext, typeof(Person), historyCategory.Guid, person.Id, changes); } return(user); } else { throw new ArgumentException("Invalid EntityTypeId, entity does not exist", "entityTypeId"); } } else { throw new ArgumentException("Invalid Person, person does not exist", "person"); } }
/// <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 ); } } } } ); } }
/// <summary> /// Called after the save operation has been executed /// </summary> /// <remarks> /// This method is only called if <see cref="M:Rock.Data.EntitySaveHook`1.PreSave" /> returns /// without error. /// </remarks> protected override void PostSave() { // Get the current person's alias ID from the current context. var currentPersonAliasId = DbContext.GetCurrentPersonAlias()?.Id; var connectionRequest = this.Entity as ConnectionRequest; // Create and send the change notification message now that the connection request has been saved. var processConnectionRequestChangeMessage = GetProcessConnectionRequestChangeMessage(Entry, connectionRequest, currentPersonAliasId); processConnectionRequestChangeMessage.SendWhen(this.DbContext.WrappedTransactionCompletedTask); var rockContext = ( RockContext )this.RockContext; if (Entity.ConnectionStatus == null) { Entity.ConnectionStatus = new ConnectionStatusService(rockContext).Get(Entity.ConnectionStatusId); } if (Entity.ConnectionStatus != null && Entity.ConnectionStatus.AutoInactivateState && Entity.ConnectionState != ConnectionState.Inactive) { Entity.ConnectionState = ConnectionState.Inactive; rockContext.SaveChanges(); } var connectionStatusAutomationsQuery = new ConnectionStatusAutomationService(rockContext).Queryable().Where(a => a.SourceStatusId == Entity.ConnectionStatusId); if (this.Entity._runAutomationsInPostSaveChanges && connectionStatusAutomationsQuery.Any()) { var connectionStatusAutomationsList = connectionStatusAutomationsQuery.AsNoTracking().OrderBy(a => a.AutomationName).ToList(); var connectionStatusAutomations = connectionStatusAutomationsList; int changedStatusCount = 0; foreach (var connectionStatusAutomation in connectionStatusAutomations) { if (this.Entity.processedConnectionStatusAutomations.Contains(connectionStatusAutomation.Id)) { // to avoid recursion, skip over automations that have already been processed in this thread. continue; } if (Entity.ConnectionStatusId == connectionStatusAutomation.DestinationStatusId) { // If already have this status, no need to figure out if it needs to be set to this status, // or to set the status. this.Entity.processedConnectionStatusAutomations.Add(connectionStatusAutomation.Id); continue; } bool isAutomationValid = true; if (connectionStatusAutomation.DataViewId.HasValue) { // Get the dataview configured for the connection request var dataViewService = new DataViewService(rockContext); var dataview = dataViewService.Get(connectionStatusAutomation.DataViewId.Value); if (dataview != null) { var dataViewQuery = new ConnectionRequestService(rockContext).GetQueryUsingDataView(dataview); isAutomationValid = dataViewQuery.Any(a => a.Id == Entity.Id); } } if (isAutomationValid && connectionStatusAutomation.GroupRequirementsFilter != GroupRequirementsFilter.Ignore) { // Group Requirement can't be meet when either placement group or placement group role id is missing if (!Entity.AssignedGroupId.HasValue || !Entity.AssignedGroupMemberRoleId.HasValue) { isAutomationValid = false; } else { var isRequirementMeet = true; var group = new GroupService(rockContext).Get(Entity.AssignedGroupId.Value); var hasGroupRequirement = new GroupRequirementService(rockContext).Queryable().Where(a => (a.GroupId.HasValue && a.GroupId == group.Id) || (a.GroupTypeId.HasValue && a.GroupTypeId == group.GroupTypeId)).Any(); if (hasGroupRequirement) { var requirementsResults = group.PersonMeetsGroupRequirements( rockContext, Entity.PersonAlias.PersonId, Entity.AssignedGroupMemberRoleId.Value); if (requirementsResults != null && requirementsResults .Where(a => a.MeetsGroupRequirement != MeetsGroupRequirement.NotApplicable) .Any(r => r.MeetsGroupRequirement != MeetsGroupRequirement.Meets && r.MeetsGroupRequirement != MeetsGroupRequirement.MeetsWithWarning) ) { isRequirementMeet = false; } } // connection request based on if group requirement is meet or not is added to list for status update isAutomationValid = (connectionStatusAutomation.GroupRequirementsFilter == GroupRequirementsFilter.DoesNotMeet && !isRequirementMeet) || (connectionStatusAutomation.GroupRequirementsFilter == GroupRequirementsFilter.MustMeet && isRequirementMeet); } } if (isAutomationValid) { if (Entity.SetConnectionStatusFromAutomationLoop(connectionStatusAutomation)) { changedStatusCount++; rockContext.SaveChanges(); } } } } var hasHistoryChanges = HistoryChangeList?.Any() == true; var hasPersonHistoryChanges = PersonHistoryChangeList?.Any() == true; if (hasHistoryChanges || hasPersonHistoryChanges) { using (var historyRockContext = new RockContext()) { if (hasHistoryChanges) { HistoryService.SaveChanges(historyRockContext, typeof(ConnectionRequest), Rock.SystemGuid.Category.HISTORY_CONNECTION_REQUEST.AsGuid(), Entity.Id, HistoryChangeList, false, Entity.ModifiedByPersonAliasId); } if (hasPersonHistoryChanges) { var personId = Entity.PersonAlias?.PersonId ?? new PersonAliasService(rockContext).GetPersonId(Entity.PersonAliasId); if (personId.HasValue) { HistoryService.SaveChanges( historyRockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_CONNECTION_REQUEST.AsGuid(), personId.Value, PersonHistoryChangeList, "Request", typeof(ConnectionRequest), Entity.Id, false, Entity.ModifiedByPersonAliasId, rockContext.SourceOfChange); } } historyRockContext.SaveChanges(false); } } base.PostSave(); }
/// <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> /// Saves the new family. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="familyMembers">The family members.</param> /// <param name="campusId">The campus identifier.</param> /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param> /// <returns></returns> public static Group SaveNewFamily( RockContext rockContext, List<GroupMember> familyMembers, int? campusId, bool savePersonAttributes ) { var familyGroupType = GroupTypeCache.GetFamilyGroupType(); var familyChanges = new List<string>(); var familyMemberChanges = new Dictionary<Guid, List<string>>(); var familyDemographicChanges = new Dictionary<Guid, List<string>>(); if ( familyGroupType != null ) { var groupService = new GroupService( rockContext ); var familyGroup = new Group(); familyGroup.GroupTypeId = familyGroupType.Id; familyGroup.Name = familyMembers.FirstOrDefault().Person.LastName + " Family"; History.EvaluateChange( familyChanges, "Family", string.Empty, familyGroup.Name ); if ( campusId.HasValue ) { History.EvaluateChange( familyChanges, "Campus", string.Empty, CampusCache.Read( campusId.Value ).Name ); } familyGroup.CampusId = campusId; int? childRoleId = null; var childRole = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ); if ( childRole != null ) { childRoleId = childRole.Id; } foreach ( var familyMember in familyMembers ) { var person = familyMember.Person; if ( person != null ) { familyGroup.Members.Add( familyMember ); var demographicChanges = new List<string>(); demographicChanges.Add( "Created" ); History.EvaluateChange( demographicChanges, "Record Type", string.Empty, person.RecordTypeValueId.HasValue ? DefinedValueCache.GetName( person.RecordTypeValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Record Status", string.Empty, person.RecordStatusValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Record Status Reason", string.Empty, person.RecordStatusReasonValueId.HasValue ? DefinedValueCache.GetName( person.RecordStatusReasonValueId.Value ) : string.Empty ); History.EvaluateChange( demographicChanges, "Connection Status", string.Empty, person.ConnectionStatusValueId.HasValue ? DefinedValueCache.GetName( person.ConnectionStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Deceased", false.ToString(), ( person.IsDeceased ?? false ).ToString() ); History.EvaluateChange( demographicChanges, "Title", string.Empty, person.TitleValueId.HasValue ? DefinedValueCache.GetName( person.TitleValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName ); History.EvaluateChange( demographicChanges, "Nick Name", string.Empty, person.NickName ); History.EvaluateChange( demographicChanges, "Middle Name", string.Empty, person.MiddleName ); History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName ); History.EvaluateChange( demographicChanges, "Suffix", string.Empty, person.SuffixValueId.HasValue ? DefinedValueCache.GetName( person.SuffixValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate ); History.EvaluateChange( demographicChanges, "Gender", null, person.Gender ); History.EvaluateChange( demographicChanges, "Marital Status", string.Empty, person.MaritalStatusValueId.HasValue ? DefinedValueCache.GetName( person.MaritalStatusValueId ) : string.Empty ); History.EvaluateChange( demographicChanges, "Anniversary Date", null, person.AnniversaryDate ); History.EvaluateChange( demographicChanges, "Graduation Year", null, person.GraduationYear ); History.EvaluateChange( demographicChanges, "Email", string.Empty, person.Email ); History.EvaluateChange( demographicChanges, "Email Active", false.ToString(), ( person.IsEmailActive ?? false ).ToString() ); History.EvaluateChange( demographicChanges, "Email Note", string.Empty, person.EmailNote ); History.EvaluateChange( demographicChanges, "Email Preference", null, person.EmailPreference ); History.EvaluateChange( demographicChanges, "Inactive Reason Note", string.Empty, person.InactiveReasonNote ); History.EvaluateChange( demographicChanges, "System Note", string.Empty, person.SystemNote ); familyDemographicChanges.Add( person.Guid, demographicChanges ); var memberChanges = new List<string>(); string roleName = familyGroupType.Roles .Where( r => r.Id == familyMember.GroupRoleId ) .Select( r => r.Name ) .FirstOrDefault(); History.EvaluateChange( memberChanges, "Role", string.Empty, roleName ); familyMemberChanges.Add( person.Guid, memberChanges ); } } groupService.Add( familyGroup ); rockContext.SaveChanges(); var personService = new PersonService( rockContext ); foreach ( var groupMember in familyMembers ) { var person = groupMember.Person; if ( savePersonAttributes ) { var newValues = person.AttributeValues; person.LoadAttributes(); foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) ) { string oldValue = person.GetAttributeValue( attributeCache.Key ) ?? string.Empty; string newValue = string.Empty; if ( newValues != null && newValues.ContainsKey( attributeCache.Key ) && newValues[attributeCache.Key] != null ) { newValue = newValues[attributeCache.Key].Value ?? string.Empty; } if ( !oldValue.Equals( newValue ) ) { History.EvaluateChange( familyDemographicChanges[person.Guid], attributeCache.Name, attributeCache.FieldType.Field.FormatValue( null, oldValue, attributeCache.QualifierValues, false ), attributeCache.FieldType.Field.FormatValue( null, newValue, attributeCache.QualifierValues, false ) ); Rock.Attribute.Helper.SaveAttributeValue( person, attributeCache, newValue ); } } } person = personService.Get( groupMember.PersonId ); if ( person != null ) { bool updateRequired = false; if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); updateRequired = true; } var changes = familyDemographicChanges[person.Guid]; if ( groupMember.GroupRoleId != childRoleId ) { person.GivingGroupId = familyGroup.Id; updateRequired = true; History.EvaluateChange( changes, "Giving Group", string.Empty, familyGroup.Name ); } if ( updateRequired ) { rockContext.SaveChanges(); } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyMemberChanges[person.Guid], familyGroup.Name, typeof( Group ), familyGroup.Id ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges, familyGroup.Name, typeof( Group ), familyGroup.Id ); } } return familyGroup; } return null; }
/// <summary> /// Updates the last login and writes to the person's history log /// </summary> /// <param name="userName">Name of the user.</param> public static void UpdateLastLogin(string userName) { if (!string.IsNullOrWhiteSpace(userName)) { using (var rockContext = new RockContext()) { int? personId = null; bool impersonated = userName.StartsWith("rckipid="); if (!impersonated) { var userLogin = new UserLoginService(rockContext).GetByUserName(userName); if (userLogin != null) { userLogin.LastLoginDateTime = RockDateTime.Now; personId = userLogin.PersonId; } } else { var impersonationToken = userName.Substring(8); personId = new PersonService(rockContext).GetByImpersonationToken(impersonationToken, false, null)?.Id; } if (personId.HasValue) { var relatedDataBuilder = new System.Text.StringBuilder(); int?relatedEntityTypeId = null; int?relatedEntityId = null; if (impersonated) { var impersonatedByUser = HttpContext.Current?.Session["ImpersonatedByUser"] as UserLogin; relatedEntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>(); relatedEntityId = impersonatedByUser?.PersonId; if (impersonatedByUser != null) { relatedDataBuilder.Append($" impersonated by { impersonatedByUser.Person.FullName }"); } } if (HttpContext.Current != null && HttpContext.Current.Request != null) { string cleanUrl = PersonToken.ObfuscateRockMagicToken(HttpContext.Current.Request.Url.AbsoluteUri); // obfuscate the url specified in the returnurl, just in case it contains any sensitive information (like a rckipid) Regex returnurlRegEx = new Regex(@"returnurl=([^&]*)"); cleanUrl = returnurlRegEx.Replace(cleanUrl, "returnurl=XXXXXXXXXXXXXXXXXXXXXXXXXXXX"); relatedDataBuilder.AppendFormat(" to <span class='field-value'>{0}</span>, from <span class='field-value'>{1}</span>", cleanUrl, HttpContext.Current.Request.UserHostAddress); } var historyChangeList = new History.HistoryChangeList(); var historyChange = historyChangeList.AddChange(History.HistoryVerb.Login, History.HistoryChangeType.Record, userName); if (relatedDataBuilder.Length > 0) { historyChange.SetRelatedData(relatedDataBuilder.ToString(), null, null); } HistoryService.SaveChanges(rockContext, typeof(Rock.Model.Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), personId.Value, historyChangeList, true); } } } }
/// <summary> /// Process a refund for a transaction. /// </summary> /// <param name="transaction">The refund transaction.</param> /// <param name="amount">The amount.</param> /// <param name="reasonValueId">The reason value identifier.</param> /// <param name="summary">The summary.</param> /// <param name="process">if set to <c>true</c> [process].</param> /// <param name="batchNameSuffix">The batch name suffix.</param> /// <param name="errorMessage">The error message.</param> /// <returns></returns> public FinancialTransaction ProcessRefund(FinancialTransaction transaction, decimal?amount, int?reasonValueId, string summary, bool process, string batchNameSuffix, out string errorMessage) { errorMessage = string.Empty; // Validate parameters if (transaction == null) { errorMessage = "A valid transaction is required"; return(null); } if (transaction.Batch == null) { errorMessage = "Transaction must belong to a batch"; return(null); } if (!amount.HasValue || amount.Value <= 0.0m) { amount = transaction.TotalAmount; } if (!amount.HasValue || amount.Value <= 0.0m) { errorMessage = string.Format("Amount must be greater than {0}", 0.0m.FormatAsCurrency()); return(null); } FinancialTransaction refundTransaction = null; // If processing the refund through gateway, get the gateway component and process a "Credit" transaction. if (process) { if (transaction.FinancialGateway == null || transaction.TransactionCode.IsNullOrWhiteSpace()) { errorMessage = "When processing the refund through the Gateway, the transaction must have a valid Gateway and Transaction Code"; return(null); } var gatewayComponent = transaction.FinancialGateway.GetGatewayComponent(); if (gatewayComponent == null) { errorMessage = "Could not get the Gateway component in order to process the refund"; return(null); } refundTransaction = gatewayComponent.Credit(transaction, amount.Value, summary, out errorMessage); if (refundTransaction == null) { return(null); } } else { refundTransaction = new FinancialTransaction(); } refundTransaction.AuthorizedPersonAliasId = transaction.AuthorizedPersonAliasId; refundTransaction.TransactionDateTime = RockDateTime.Now; refundTransaction.FinancialGatewayId = transaction.FinancialGatewayId; refundTransaction.TransactionTypeValueId = transaction.TransactionTypeValueId; refundTransaction.SourceTypeValueId = transaction.SourceTypeValueId; if (transaction.FinancialPaymentDetail != null) { refundTransaction.FinancialPaymentDetail = new FinancialPaymentDetail(); refundTransaction.FinancialPaymentDetail.AccountNumberMasked = transaction.FinancialPaymentDetail.AccountNumberMasked; refundTransaction.FinancialPaymentDetail.BillingLocationId = transaction.FinancialPaymentDetail.BillingLocationId; refundTransaction.FinancialPaymentDetail.CreditCardTypeValueId = transaction.FinancialPaymentDetail.CreditCardTypeValueId; refundTransaction.FinancialPaymentDetail.CurrencyTypeValueId = transaction.FinancialPaymentDetail.CurrencyTypeValueId; refundTransaction.FinancialPaymentDetail.ExpirationMonthEncrypted = transaction.FinancialPaymentDetail.ExpirationMonthEncrypted; refundTransaction.FinancialPaymentDetail.ExpirationYearEncrypted = transaction.FinancialPaymentDetail.ExpirationYearEncrypted; refundTransaction.FinancialPaymentDetail.NameOnCardEncrypted = transaction.FinancialPaymentDetail.NameOnCardEncrypted; } decimal remainingBalance = amount.Value; foreach (var account in transaction.TransactionDetails.Where(a => a.Amount > 0)) { var transactionDetail = new FinancialTransactionDetail(); transactionDetail.AccountId = account.AccountId; transactionDetail.EntityId = account.EntityId; transactionDetail.EntityTypeId = account.EntityTypeId; refundTransaction.TransactionDetails.Add(transactionDetail); if (remainingBalance >= account.Amount) { transactionDetail.Amount = 0 - account.Amount; remainingBalance -= account.Amount; } else { transactionDetail.Amount = 0 - remainingBalance; remainingBalance = 0.0m; } if (remainingBalance <= 0.0m) { break; } } if (remainingBalance > 0 && refundTransaction.TransactionDetails.Any()) { refundTransaction.TransactionDetails.Last().Amount += remainingBalance; } var rockContext = this.Context as Rock.Data.RockContext; var registrationEntityType = EntityTypeCache.Get(typeof(Rock.Model.Registration)); if (registrationEntityType != null) { foreach (var transactionDetail in refundTransaction.TransactionDetails .Where(d => d.EntityTypeId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && d.EntityId.HasValue)) { var registrationChanges = new History.HistoryChangeList(); registrationChanges.AddChange(History.HistoryVerb.Process, History.HistoryChangeType.Record, $"{transactionDetail.Amount.FormatAsCurrency()} Refund"); HistoryService.SaveChanges( rockContext, typeof(Registration), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), transactionDetail.EntityId.Value, registrationChanges ); } } refundTransaction.RefundDetails = new FinancialTransactionRefund(); refundTransaction.RefundDetails.RefundReasonValueId = reasonValueId; refundTransaction.RefundDetails.RefundReasonSummary = summary; refundTransaction.RefundDetails.OriginalTransactionId = transaction.Id; string batchName = transaction.Batch.Name; if (batchNameSuffix.IsNotNullOrWhiteSpace() && !batchName.EndsWith(batchNameSuffix)) { batchName += batchNameSuffix; } // Get the batch var batchService = new FinancialBatchService(rockContext); TimeSpan timespan = new TimeSpan(); if (transaction.FinancialGateway != null) { timespan = transaction.FinancialGateway.GetBatchTimeOffset(); } var batch = batchService.GetByNameAndDate(batchName, refundTransaction.TransactionDateTime.Value, timespan); // If this is a new Batch, SaveChanges so that we can get the Batch.Id if (batch.Id == 0) { rockContext.SaveChanges(); } refundTransaction.BatchId = batch.Id; Add(refundTransaction); rockContext.SaveChanges(); batchService.IncrementControlAmount(batch.Id, refundTransaction.TotalAmount, null); rockContext.SaveChanges(); return(refundTransaction); }