Files
accounted/lib/reports/opening-balances.ts
T
Jakob Wennberg a8801430f4 fix(reports): stop driving report queries from the unfiltered journal_entry_lines side (#971)
* fix(reports): drive report line queries from journal_entries, not the unfiltered lines side

Every report generator fetched journal_entry_lines with a
journal_entries!inner(...) embed and put the tenant filter on the
embedded side (.eq('journal_entries.company_id', ...)). PostgREST
compiles that to a correlated INNER JOIN LATERAL with a parameterized
LIMIT inside, which blocks join reordering: Postgres walked the ENTIRE
journal_entry_lines table (603k rows, all tenants) per report query.
Measured in production: 13.6 s vs 2.7 ms for the equivalent plain join,
against Supabase's 8 s statement_timeout; nightly cloud backups failed
for 5 of 11 companies on 2026-07-09 and a GL report 500'd.

Introduce lib/bookkeeping/entry-lines.ts with a shared two-step fetch:

1. fetch matching journal_entries (id + caller-selected columns)
   filtered by company_id / fiscal_period_id / status / entry_date /
   source_type, paginated via fetchAllRows;
2. fetch journal_entry_lines with .in('journal_entry_id', chunk) in
   chunks of 100 ids (URL-length safety), paginated per chunk;
3. reattach the parent entry to each line under the embed's key shape
   (line.journal_entries = {...}, aliasable) and sort lines by id
   ascending to preserve the old .order('id') semantics.

Converted call sites (selected columns and filters preserved):
trial-balance (x2), general-ledger, journal-register, sie-export
(reuses its existing entry list via fetchLinesByEntryIds),
vat-declaration, dimension-pnl, opening-balances, monthly-breakdown,
periodisk-sammanstallning, rc-basis-gaps (sibling-line fetch now also
chunked), ar-reconciliation, supplier-reconciliation,
bank-reconciliation, asset-service (x2), bolagsskatt-calculator,
sarskild-loneskatt-calculator.

Tests: unit tests for the helper (chunk size, reattachment shape,
forced id/journal_entry_id columns, empty result, cross-chunk sort,
error propagation); existing report/reconciliation/bokslut test mocks
updated to the two-step query shape, preserving every assertion about
report output.

From the 2026-07-09 production log triage.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reports): stop echoing raw error messages from the general-ledger route

The catch handler returned err.message to the client in
details.reason; internal error strings (SQL fragments, table names,
timeout messages) must not reach the browser. The error is already
logged server-side with the request id, so the client envelope keeps
only the REPORT_GENERATION_FAILED code.

From the 2026-07-09 production log triage.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:03:28 +02:00

91 lines
3.5 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
/**
* Get opening balances (ingående balans) for a fiscal period.
*
* Uses the opening_balance_entry set by year-end closing when available
* (O(accounts): typically ~50 rows). Falls back to a server-side
* aggregate via the compute_prior_opening_balances RPC when no OB entry
* is set, which returns one row per balance-sheet account (class 1-2)
* regardless of how many prior journal lines there are.
*
* Returns per-account debit/credit opening balances and the OB entry ID
* (if any) so the caller can exclude it from period queries to prevent
* double-counting.
*
* NOTE: The account range filter (accountFrom/accountTo in the GL) is
* applied post-hoc by the caller, not here. This is consistent with the
* existing behavior and avoids complicating the queries for the common
* unfiltered case.
*/
export async function getOpeningBalances(
supabase: SupabaseClient,
companyId: string,
period: { period_start: string; opening_balance_entry_id: string | null } | null
): Promise<{
balances: Map<string, { debit: number; credit: number }>
obEntryId: string | null
}> {
const balances = new Map<string, { debit: number; credit: number }>()
if (!period) {
return { balances, obEntryId: null }
}
const obEntryId = period.opening_balance_entry_id
if (obEntryId) {
// Use the explicit opening balance entry (set by year-end closing).
// Typically ~50 rows: one per balance sheet account. The two-step
// entry-lines fetch verifies company_id ownership on the entry side
// (defense in depth alongside RLS) and paginates (avoids silent
// truncation). See lib/bookkeeping/entry-lines.ts.
const obLines = await fetchEntryLines<{
id: string
account_number: string
debit_amount: number
credit_amount: number
}>({
supabase,
lineColumns: 'id, account_number, debit_amount, credit_amount',
filterEntries: (q: EntryLinesQuery) =>
q.eq('id', obEntryId).eq('company_id', companyId),
attachEntriesAs: null,
})
for (const line of obLines) {
const existing = balances.get(line.account_number) || { debit: 0, credit: 0 }
existing.debit += Number(line.debit_amount) || 0
existing.credit += Number(line.credit_amount) || 0
balances.set(line.account_number, existing)
}
} else {
// Fallback: server-side aggregate of all prior posted/reversed lines.
// The RPC filters to balance-sheet accounts (class 1-2) and returns
// one row per account. P&L accounts (class 3-8) reset to zero at each
// year transition: their balances are absorbed into årets resultat
// (2099) and rolled into equity, so carrying them forward as IB would
// violate BFNAR 2013:2. Filtering them in SQL keeps the payload small
// and the round-trip count at one regardless of history size.
const { data: priorRows, error } = await supabase.rpc('compute_prior_opening_balances', {
p_company_id: companyId,
p_period_start: period.period_start,
})
if (error) throw new Error(error.message)
for (const row of (priorRows ?? []) as Array<{
account_number: string
debit: number | string
credit: number | string
}>) {
balances.set(row.account_number, {
debit: Number(row.debit) || 0,
credit: Number(row.credit) || 0,
})
}
}
return { balances, obEntryId }
}