diff --git a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs index 303782d2..8eec160f 100644 --- a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs +++ b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs @@ -308,25 +308,82 @@ public class AgentSummaryRepository : IAgentSummaryRepository public async Task UpdateAgentNameAsync(int userId, string agentName) { - var entity = await _context.AgentSummaries - .AsNoTracking() - .FirstOrDefaultAsync(a => a.UserId == userId); - - if (entity != null) + try { - entity.AgentName = agentName; - entity.UpdatedAt = DateTime.UtcNow; + // First, check if there's already a tracked entity with this key + var trackedEntity = _context.ChangeTracker.Entries() + .FirstOrDefault(e => e.Entity.UserId == userId); - _context.AgentSummaries.Update(entity); - await _context.SaveChangesAsync(); + AgentSummaryEntity? entityToUpdate = null; + bool wasTracked = false; - _logger.LogInformation("Agent name updated for user {UserId} to {AgentName}", userId, agentName); + if (trackedEntity != null) + { + // Entity is already tracked, update it directly + entityToUpdate = trackedEntity.Entity; + wasTracked = true; + + _logger.LogInformation("Found tracked entity for user {UserId}. Current agent name: {CurrentAgentName}, New agent name: {NewAgentName}", + userId, entityToUpdate.AgentName, agentName); + } + 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 agent name to {AgentName}", + userId, agentName); + return; + } + + _logger.LogInformation("Fetched entity for user {UserId}. Current agent name: {CurrentAgentName}, New agent name: {NewAgentName}", + userId, entityToUpdate.AgentName, agentName); + } + + // Check if the agent name is actually different + if (entityToUpdate.AgentName == agentName) + { + _logger.LogInformation("Agent name for user {UserId} is already {AgentName}, no update needed", userId, agentName); + return; + } + + // Update the entity + var oldAgentName = entityToUpdate.AgentName; + entityToUpdate.AgentName = agentName; + 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("Agent name updated for user {UserId} from '{OldAgentName}' to '{NewAgentName}'. Changes saved: {ChangesSaved}", + userId, oldAgentName, agentName, changesSaved); + + if (changesSaved == 0) + { + _logger.LogWarning("No changes were saved for user {UserId}. This might indicate a tracking issue.", userId); + } } - else + catch (Exception ex) { - _logger.LogWarning( - "No AgentSummary found for user {UserId} when trying to update agent name to {AgentName}", - userId, agentName); + _logger.LogError(ex, "Error updating agent name for user {UserId} to {AgentName}", userId, agentName); + throw; } } @@ -337,26 +394,75 @@ public class AgentSummaryRepository : IAgentSummaryRepository public async Task IncrementBacktestCountAsync(int userId) { - var entity = await _context.AgentSummaries - .AsNoTracking() - .FirstOrDefaultAsync(a => a.UserId == userId); - - if (entity != null) + try { - var newCount = entity.BacktestCount + 1; - entity.BacktestCount = newCount; - entity.UpdatedAt = DateTime.UtcNow; + // First, check if there's already a tracked entity with this key + var trackedEntity = _context.ChangeTracker.Entries() + .FirstOrDefault(e => e.Entity.UserId == userId); - _context.AgentSummaries.Update(entity); - await _context.SaveChangesAsync(); + AgentSummaryEntity? entityToUpdate = null; + bool wasTracked = false; - _logger.LogInformation("Backtest count incremented for user {UserId} to {BacktestCount}", - userId, entity.BacktestCount); + if (trackedEntity != null) + { + // Entity is already tracked, update it directly + entityToUpdate = trackedEntity.Entity; + wasTracked = true; + + _logger.LogInformation("Found tracked entity for user {UserId}. Current backtest count: {CurrentCount}", + userId, entityToUpdate.BacktestCount); + } + 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 increment backtest count", + userId); + return; + } + + _logger.LogInformation("Fetched entity for user {UserId}. Current backtest count: {CurrentCount}", + userId, entityToUpdate.BacktestCount); + } + + // Update the entity + var oldCount = entityToUpdate.BacktestCount; + var newCount = oldCount + 1; + entityToUpdate.BacktestCount = newCount; + 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("Backtest count incremented for user {UserId} from {OldCount} to {NewCount}. Changes saved: {ChangesSaved}", + userId, oldCount, newCount, changesSaved); + + if (changesSaved == 0) + { + _logger.LogWarning("No changes were saved for user {UserId}. This might indicate a tracking issue.", userId); + } } - else + catch (Exception ex) { - _logger.LogWarning("No AgentSummary found for user {UserId} when trying to increment backtest count", - userId); + _logger.LogError(ex, "Error incrementing backtest count for user {UserId}", userId); + throw; } } } \ No newline at end of file