Fix update agent Summary when new balance fetch

This commit is contained in:
2025-10-11 13:10:47 +07:00
parent 04df72a6bd
commit b6a4c7661f
5 changed files with 116 additions and 4 deletions

View File

@@ -465,4 +465,84 @@ public class AgentSummaryRepository : IAgentSummaryRepository
throw;
}
}
public async Task UpdateTotalBalanceAsync(int userId, decimal totalBalance)
{
try
{
// First, check if there's already a tracked entity with this key
var trackedEntity = _context.ChangeTracker.Entries<AgentSummaryEntity>()
.FirstOrDefault(e => e.Entity.UserId == userId);
AgentSummaryEntity? entityToUpdate = null;
bool wasTracked = false;
if (trackedEntity != null)
{
// Entity is already tracked, update it directly
entityToUpdate = trackedEntity.Entity;
wasTracked = true;
_logger.LogInformation("Found tracked entity for user {UserId}. Current total balance: {CurrentBalance}, New total balance: {NewBalance}",
userId, entityToUpdate.TotalBalance, totalBalance);
}
else
{
// Entity is not tracked, fetch it normally
entityToUpdate = await _context.AgentSummaries
.FirstOrDefaultAsync(a => a.UserId == userId);
if (entityToUpdate == null)
{
_logger.LogWarning("No AgentSummary found for user {UserId} when trying to update total balance to {TotalBalance}",
userId, totalBalance);
return;
}
_logger.LogInformation("Fetched entity for user {UserId}. Current total balance: {CurrentBalance}, New total balance: {NewBalance}",
userId, entityToUpdate.TotalBalance, totalBalance);
}
// Check if the total balance is actually different
if (entityToUpdate.TotalBalance == totalBalance)
{
_logger.LogInformation("Total balance for user {UserId} is already {TotalBalance}, no update needed", userId, totalBalance);
return;
}
// Update the entity
var oldBalance = entityToUpdate.TotalBalance;
entityToUpdate.TotalBalance = totalBalance;
entityToUpdate.UpdatedAt = DateTime.UtcNow;
// If it wasn't tracked, explicitly mark it as modified
if (!wasTracked)
{
_context.Entry(entityToUpdate).State = EntityState.Modified;
}
// Log the change tracker state before saving
var modifiedEntries = _context.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Modified)
.ToList();
_logger.LogInformation("Change tracker has {Count} modified entries before save", modifiedEntries.Count);
// Save changes
var changesSaved = await _context.SaveChangesAsync();
_logger.LogInformation("Total balance updated for user {UserId} from {OldBalance} to {NewBalance}. Changes saved: {ChangesSaved}",
userId, oldBalance, totalBalance, changesSaved);
if (changesSaved == 0)
{
_logger.LogWarning("No changes were saved for user {UserId}. This might indicate a tracking issue.", userId);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating total balance for user {UserId} to {TotalBalance}", userId, totalBalance);
throw;
}
}
}