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 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 09:11:37 -05:00
parent 0e82e238c1
commit d1c40c633f

View File

@@ -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