From b6a4c7661f0ef8d8d4df0a790109e972f53961b9 Mon Sep 17 00:00:00 2001 From: cryptooda Date: Sat, 11 Oct 2025 13:10:47 +0700 Subject: [PATCH] Fix update agent Summary when new balance fetch --- .../Repositories/IAgentSummaryRepository.cs | 7 ++ .../Services/IAgentService.cs | 7 ++ .../Agents/AgentService.cs | 25 +++++- .../Bots/TradingBotBase.cs | 1 + .../PostgreSql/AgentSummaryRepository.cs | 80 +++++++++++++++++++ 5 files changed, 116 insertions(+), 4 deletions(-) diff --git a/src/Managing.Application.Abstractions/Repositories/IAgentSummaryRepository.cs b/src/Managing.Application.Abstractions/Repositories/IAgentSummaryRepository.cs index c66c9eb0..63f3aa58 100644 --- a/src/Managing.Application.Abstractions/Repositories/IAgentSummaryRepository.cs +++ b/src/Managing.Application.Abstractions/Repositories/IAgentSummaryRepository.cs @@ -47,4 +47,11 @@ public interface IAgentSummaryRepository /// /// The user ID Task IncrementBacktestCountAsync(int userId); + + /// + /// Updates the total balance for a specific user's agent summary + /// + /// The user ID + /// The new total balance value + Task UpdateTotalBalanceAsync(int userId, decimal totalBalance); } \ No newline at end of file diff --git a/src/Managing.Application.Abstractions/Services/IAgentService.cs b/src/Managing.Application.Abstractions/Services/IAgentService.cs index a395d010..d976c3e0 100644 --- a/src/Managing.Application.Abstractions/Services/IAgentService.cs +++ b/src/Managing.Application.Abstractions/Services/IAgentService.cs @@ -30,4 +30,11 @@ public interface IAgentService /// /// The user ID Task IncrementBacktestCountAsync(int userId); + + /// + /// Updates the total balance for a specific user's agent summary + /// + /// The user ID + /// The new total balance value + Task UpdateAgentSummaryTotalBalanceAsync(int userId, decimal totalBalance); } \ No newline at end of file diff --git a/src/Managing.Application/Agents/AgentService.cs b/src/Managing.Application/Agents/AgentService.cs index 948a48f3..e2b65c12 100644 --- a/src/Managing.Application/Agents/AgentService.cs +++ b/src/Managing.Application/Agents/AgentService.cs @@ -1,13 +1,12 @@ +using Managing.Application.Abstractions; using Managing.Application.Abstractions.Repositories; using Managing.Application.Abstractions.Services; -using Managing.Application.Abstractions; using Managing.Core; +using Managing.Domain.Accounts; +using Managing.Domain.Bots; using Managing.Domain.Statistics; using Managing.Domain.Trades; using Managing.Domain.Users; -using Managing.Domain.Accounts; -using Managing.Domain.Bots; -using Managing.Domain.Shared.Helpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using static Managing.Common.Enums; @@ -95,6 +94,9 @@ public class AgentService : IAgentService // Insert the fresh balance data into InfluxDB _agentBalanceRepository.InsertAgentBalance(freshBalance); + // Update the AgentSummary TotalBalance with the fresh balance data + await UpdateAgentSummaryTotalBalanceAsync(userId, freshBalance.TotalBalanceValue); + // Add the fresh balance to our results if it falls within the requested time range if (freshBalance.Time >= start && freshBalance.Time <= effectiveEnd) { @@ -186,6 +188,21 @@ public class AgentService : IAgentService } } + public async Task UpdateAgentSummaryTotalBalanceAsync(int userId, decimal totalBalance) + { + try + { + await _agentSummaryRepository.UpdateTotalBalanceAsync(userId, totalBalance); + + _logger.LogInformation("Total balance updated for user {UserId} to {TotalBalance}", userId, totalBalance); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error updating total balance for user {UserId} to {TotalBalance}", userId, totalBalance); + throw; + } + } + /// /// Determines if fresh balance data should be calculated based on the last balance timestamp /// diff --git a/src/Managing.Application/Bots/TradingBotBase.cs b/src/Managing.Application/Bots/TradingBotBase.cs index 9ee51450..02511ddc 100644 --- a/src/Managing.Application/Bots/TradingBotBase.cs +++ b/src/Managing.Application/Bots/TradingBotBase.cs @@ -1969,6 +1969,7 @@ public class TradingBotBase : ITradingBot // Add the signal to our collection await AddSignal(signal); + await ManagePositions(); return signal; } diff --git a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs index 8eec160f..e27dd620 100644 --- a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs +++ b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs @@ -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() + .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; + } + } } \ No newline at end of file