From d1c40c633f7bd5560a7a7c4d43282dc4a9d28e36 Mon Sep 17 00:00:00 2001 From: olsch01 Date: Fri, 27 Feb 2026 09:11:37 -0500 Subject: [PATCH] Fix dashboard KPIs: resolve nested aggregate and missing column errors - Wrap account interest query in subquery to avoid SUM(SUM(...)) nesting - Replace nonexistent interest_earned column with current_value - principal Co-Authored-By: Claude Opus 4.6 --- .../src/modules/reports/reports.service.ts | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/backend/src/modules/reports/reports.service.ts b/backend/src/modules/reports/reports.service.ts index ad1b52a..cbb9e99 100644 --- a/backend/src/modules/reports/reports.service.ts +++ b/backend/src/modules/reports/reports.service.ts @@ -508,26 +508,26 @@ export class ReportsService { // Monthly interest estimate from accounts + investments with rates const acctInterest = await this.tenant.query(` - SELECT COALESCE(SUM( - (COALESCE(SUM(jel.debit), 0) - COALESCE(SUM(jel.credit), 0)) * (a.interest_rate / 100) / 12 - ), 0) as total - FROM accounts a - LEFT JOIN journal_entry_lines jel ON jel.account_id = a.id - LEFT JOIN journal_entries je ON je.id = jel.journal_entry_id AND je.is_posted = true AND je.is_void = false - WHERE a.account_type = 'asset' AND a.is_active = true AND a.interest_rate > 0 - GROUP BY a.id + SELECT COALESCE(SUM(sub.monthly_interest), 0) as total FROM ( + SELECT (COALESCE(SUM(jel.debit), 0) - COALESCE(SUM(jel.credit), 0)) * (a.interest_rate / 100) / 12 as monthly_interest + FROM accounts a + LEFT JOIN journal_entry_lines jel ON jel.account_id = a.id + LEFT JOIN journal_entries je ON je.id = jel.journal_entry_id AND je.is_posted = true AND je.is_void = false + WHERE a.account_type = 'asset' AND a.is_active = true AND a.interest_rate > 0 + GROUP BY a.id, a.interest_rate + ) sub `); - const acctInterestTotal = (acctInterest || []).reduce((s: number, r: any) => s + parseFloat(r.total || '0'), 0); + const acctInterestTotal = parseFloat(acctInterest[0]?.total || '0'); const invInterest = await this.tenant.query(` SELECT COALESCE(SUM(current_value * interest_rate / 100 / 12), 0) as total FROM investment_accounts WHERE is_active = true AND interest_rate > 0 `); const estMonthlyInterest = acctInterestTotal + parseFloat(invInterest[0]?.total || '0'); - // Interest earned YTD from investment accounts + // Interest earned YTD: approximate from current_value - principal (unrealized gains) const interestEarned = await this.tenant.query(` - SELECT COALESCE(SUM(interest_earned), 0) as total - FROM investment_accounts WHERE is_active = true + SELECT COALESCE(SUM(current_value - principal), 0) as total + FROM investment_accounts WHERE is_active = true AND current_value > principal `); // Planned capital spend for current year