diff --git a/src/routes/(app)/companies/[companyId]/accounts/+page.server.ts b/src/routes/(app)/companies/[companyId]/accounts/+page.server.ts index b29e2bf..2be3760 100644 --- a/src/routes/(app)/companies/[companyId]/accounts/+page.server.ts +++ b/src/routes/(app)/companies/[companyId]/accounts/+page.server.ts @@ -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`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`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);