Fix zero balance on accounts list page

The correlated subquery in the SELECT was returning 0 for every row.
Replaced with a separate grouped-sum query joined in JS — same data, more
reliable SQL generation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-16 14:17:33 +07:00
parent 77c5d72e43
commit c1a575241f
@@ -207,44 +207,29 @@ export const load: PageServerLoad = async ({ locals, params, parent, url }) => {
const showArchived = url.searchParams.get('archived') === '1';
const accountsWithBalance = await db
.select({
id: companyAccounts.id,
accountType: companyAccounts.accountType,
name: companyAccounts.name,
currency: companyAccounts.currency,
isActive: companyAccounts.isActive,
isArchived: companyAccounts.isArchived,
notes: companyAccounts.notes,
sortOrder: companyAccounts.sortOrder,
bankName: companyAccounts.bankName,
accountNumber: companyAccounts.accountNumber,
branch: companyAccounts.branch,
swiftBic: companyAccounts.swiftBic,
iban: companyAccounts.iban,
accountHolderName: companyAccounts.accountHolderName,
cardBrand: companyAccounts.cardBrand,
last4: companyAccounts.last4,
cardholderName: companyAccounts.cardholderName,
expiryMonth: companyAccounts.expiryMonth,
expiryYear: companyAccounts.expiryYear,
creditLimit: companyAccounts.creditLimit,
statementCloseDay: companyAccounts.statementCloseDay,
paymentDueDay: companyAccounts.paymentDueDay,
externalAccountId: companyAccounts.externalAccountId,
createdAt: companyAccounts.createdAt,
balance: sql<string>`coalesce((
select sum(${companyAccountTransactions.amount})
from ${companyAccountTransactions}
where ${companyAccountTransactions.accountId} = ${companyAccounts.id}
), '0')::text`
})
const accountsRaw = await db
.select()
.from(companyAccounts)
.where(
and(eq(companyAccounts.companyId, params.companyId), isNull(companyAccounts.deletedAt))
)
.orderBy(asc(companyAccounts.isArchived), asc(companyAccounts.sortOrder), asc(companyAccounts.name));
const balanceRows = await db
.select({
accountId: companyAccountTransactions.accountId,
balance: sql<string>`coalesce(sum(${companyAccountTransactions.amount}), '0')::text`
})
.from(companyAccountTransactions)
.where(eq(companyAccountTransactions.companyId, params.companyId))
.groupBy(companyAccountTransactions.accountId);
const balanceMap = new Map(balanceRows.map((r) => [r.accountId, r.balance]));
const accountsWithBalance = accountsRaw.map((a) => ({
...a,
balance: balanceMap.get(a.id) ?? '0'
}));
const visibleAccounts = showArchived
? accountsWithBalance
: accountsWithBalance.filter((a) => !a.isArchived);