diff --git a/src/Purrse.Api/Services/DashboardService.cs b/src/Purrse.Api/Services/DashboardService.cs index 80e10eb..07e8d0a 100644 --- a/src/Purrse.Api/Services/DashboardService.cs +++ b/src/Purrse.Api/Services/DashboardService.cs @@ -51,18 +51,24 @@ public class DashboardService : IDashboardService var changePercent = lastMonthSpending == 0 ? 0 : ((thisMonthSpending - lastMonthSpending) / lastMonthSpending) * 100; - var topCategories = await _db.Transactions - .Include(t => t.Category) + var spendingByCategory = await _db.Transactions .Where(t => t.Account.UserId == userId && t.Date >= startOfMonth && t.Amount < 0 && !t.IsVoid && t.CategoryId.HasValue) - .GroupBy(t => new { t.CategoryId, CategoryName = t.Category!.Name }) - .Select(g => new CategorySpending(g.Key.CategoryName, -g.Sum(t => t.Amount), 0, null)) - .OrderByDescending(c => c.Amount) + .GroupBy(t => t.CategoryId) + .Select(g => new { CategoryId = g.Key, Total = -g.Sum(t => t.Amount) }) + .OrderByDescending(x => x.Total) .Take(5) .ToListAsync(); - var totalSpending = topCategories.Sum(c => c.Amount); - topCategories = topCategories.Select(c => new CategorySpending(c.CategoryName, c.Amount, - totalSpending > 0 ? (c.Amount / totalSpending) * 100 : 0, null)).ToList(); + var categoryNames = await _db.Categories + .Where(c => spendingByCategory.Select(x => x.CategoryId).Contains(c.Id)) + .ToDictionaryAsync(c => c.Id, c => c.Name); + + var totalSpending = spendingByCategory.Sum(x => x.Total); + var topCategories = spendingByCategory.Select(x => new CategorySpending( + categoryNames.GetValueOrDefault(x.CategoryId!.Value, "Unknown"), + x.Total, + totalSpending > 0 ? (x.Total / totalSpending) * 100 : 0, + null)).ToList(); var spendingSummary = new SpendingSummary(thisMonthSpending, lastMonthSpending, changePercent, topCategories);