From 2ee1322ba0c5123311375626e12cc5b45511ffd0 Mon Sep 17 00:00:00 2001 From: cryptooda Date: Tue, 20 May 2025 22:42:06 +0700 Subject: [PATCH] Fix Get agent balance --- .../Services/IStatisticService.cs | 5 +- .../StatisticService.cs | 18 +++--- .../AgentBalanceRepository.cs | 3 +- .../dashboardPage/analytics/bestAgents.tsx | 58 +++++++++++++++---- 4 files changed, 59 insertions(+), 25 deletions(-) diff --git a/src/Managing.Application.Abstractions/Services/IStatisticService.cs b/src/Managing.Application.Abstractions/Services/IStatisticService.cs index d85319c..5baf556 100644 --- a/src/Managing.Application.Abstractions/Services/IStatisticService.cs +++ b/src/Managing.Application.Abstractions/Services/IStatisticService.cs @@ -6,9 +6,10 @@ namespace Managing.Application.Abstractions.Services; public interface IStatisticService { - Task> GetAgentBalances(string agentName, DateTime start, DateTime? end = null); + Task GetAgentBalances(string agentName, DateTime start, DateTime? end = null); - Task<(IList Agents, int TotalCount)> GetBestAgents(DateTime start, DateTime? end = null, int page = 1, + Task<(IList Agents, int TotalCount)> GetBestAgents(DateTime start, DateTime? end = null, + int page = 1, int pageSize = 10); List GetBadTraders(); diff --git a/src/Managing.Application.Workers/StatisticService.cs b/src/Managing.Application.Workers/StatisticService.cs index 937a333..edfcd38 100644 --- a/src/Managing.Application.Workers/StatisticService.cs +++ b/src/Managing.Application.Workers/StatisticService.cs @@ -378,14 +378,14 @@ public class StatisticService : IStatisticService await _messengerService.SendBadTraders(lastBadTrader); } - public async Task> GetAgentBalances(string agentName, DateTime start, + public async Task GetAgentBalances(string agentName, DateTime start, DateTime? end = null) { var effectiveEnd = end ?? DateTime.UtcNow; string cacheKey = $"AgentBalances_{agentName}_{start:yyyyMMdd}_{effectiveEnd:yyyyMMdd}"; // Check if the balances are already cached - var cachedBalances = _cacheService.GetValue>(cacheKey); + var cachedBalances = _cacheService.GetValue(cacheKey); if (cachedBalances != null) { @@ -393,15 +393,12 @@ public class StatisticService : IStatisticService } var balances = await _agentBalanceRepository.GetAgentBalances(agentName, start, end); - + // Create a single AgentBalanceHistory with all balances - var result = new List + var result = new AgentBalanceHistory { - new AgentBalanceHistory - { - AgentName = agentName, - AgentBalances = balances.OrderBy(b => b.Time).ToList() - } + AgentName = agentName, + AgentBalances = balances.OrderBy(b => b.Time).ToList() }; // Cache the results for 5 minutes @@ -434,7 +431,8 @@ public class StatisticService : IStatisticService } // Get all agents with their balance history - var (fetchedAgents, fetchedTotalCount) = await _agentBalanceRepository.GetAllAgentBalancesWithHistory(start, end); + var (fetchedAgents, fetchedTotalCount) = + await _agentBalanceRepository.GetAllAgentBalancesWithHistory(start, end); // Cache all results for 5 minutes _cacheService.SaveValue(cacheKey, (fetchedAgents, fetchedTotalCount), TimeSpan.FromMinutes(5)); diff --git a/src/Managing.Infrastructure.Database/AgentBalanceRepository.cs b/src/Managing.Infrastructure.Database/AgentBalanceRepository.cs index d67e549..68d155a 100644 --- a/src/Managing.Infrastructure.Database/AgentBalanceRepository.cs +++ b/src/Managing.Infrastructure.Database/AgentBalanceRepository.cs @@ -49,7 +49,8 @@ public class AgentBalanceRepository : IAgentBalanceRepository $"|> range(start: {start:s}Z" + (end.HasValue ? $", stop: {end.Value:s}Z" : "") + $") " + - $"|> filter(fn: (r) => r[\"agent_name\"] == \"{agentName}\")"; + $"|> filter(fn: (r) => r[\"agent_name\"] == \"{agentName}\") " + + $"|> pivot(rowKey: [\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")"; var result = await query.QueryAsync(flux, _influxDbRepository.Organization); diff --git a/src/Managing.WebApp/src/pages/dashboardPage/analytics/bestAgents.tsx b/src/Managing.WebApp/src/pages/dashboardPage/analytics/bestAgents.tsx index c873699..901be4a 100644 --- a/src/Managing.WebApp/src/pages/dashboardPage/analytics/bestAgents.tsx +++ b/src/Managing.WebApp/src/pages/dashboardPage/analytics/bestAgents.tsx @@ -14,6 +14,15 @@ export interface AgentBalanceWithBalances extends AgentBalanceHistory { }>; } +const FILTERS = [ + { label: '24H', value: '24H', days: 1 }, + { label: '3D', value: '3D', days: 3 }, + { label: '1W', value: '1W', days: 7 }, + { label: '1M', value: '1M', days: 30 }, + { label: '1Y', value: '1Y', days: 365 }, + { label: 'Total', value: 'Total', days: null }, +] + function BestAgents() { const { apiUrl } = useApiUrlStore() const [data, setData] = useState([]) @@ -21,37 +30,52 @@ function BestAgents() { const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(10) const [totalPages, setTotalPages] = useState(1) - const [expandedAgent, setExpandedAgent] = useState(null) + const [selectedFilter, setSelectedFilter] = useState('Total') useEffect(() => { setIsLoading(true) const client = new DataClient({}, apiUrl) const now = new Date() - const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30) + + // Calculate start date based on selected filter + const filterObj = FILTERS.find(f => f.value === selectedFilter) + let startDate: Date + if (filterObj?.days) { + // Use the filter's days value to calculate start date + startDate = new Date(now.getTime() - filterObj.days * 24 * 60 * 60 * 1000) + } else { + // For 'Total', fetch from a far past date (e.g., 5 years ago) + startDate = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate()) + } + client.data_GetBestAgents(startDate, now, page, pageSize).then((res: BestAgentsResponse) => { setData(res.agents as AgentBalanceWithBalances[] ?? []) setTotalPages(res.totalPages ?? 1) console.log(res) }).finally(() => setIsLoading(false)) - }, [apiUrl, page, pageSize]) + }, [apiUrl, page, pageSize, selectedFilter]) - // Type guard for agentBalances - function hasAgentBalances(agent: AgentBalanceWithBalances): agent is Required { - return Array.isArray(agent.agentBalances) && agent.agentBalances.length > 0; + function filterBalancesByRange(agent: AgentBalanceWithBalances) { + if (!agent.agentBalances || selectedFilter === 'Total') return agent.agentBalances ?? [] + const days = FILTERS.find(f => f.value === selectedFilter)?.days + if (!days) return agent.agentBalances ?? [] + const now = new Date() + const cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1000) + return agent.agentBalances.filter(b => b.time && new Date(b.time) >= cutoff) } // Get the latest balance for each agent const latestBalances = data.map(agent => { - if (hasAgentBalances(agent)) { - const lastBalance = agent.agentBalances[agent.agentBalances.length - 1] + const filteredBalances = filterBalancesByRange(agent) + if (filteredBalances.length > 0) { + const lastBalance = filteredBalances[filteredBalances.length - 1] return { agentName: agent.agentName, - originalAgent: agent, // Store the original agent for row details + originalAgent: { ...agent, agentBalances: filteredBalances }, ...lastBalance } } - // fallback: just agentName - return { agentName: agent.agentName, originalAgent: agent } + return { agentName: agent.agentName, originalAgent: { ...agent, agentBalances: filteredBalances } } }) const columns = [ @@ -63,10 +87,20 @@ function BestAgents() { { Header: 'Last Update', accessor: 'time', Cell: ({ value }: any) => value ? new Date(value).toLocaleString() : '' }, ] - return (
+
+ {FILTERS.map(f => ( + + ))} +
{isLoading ? ( ) : (