Files
accounted/lib/reports/opening-balances.ts
T
Jakob WennbergandClaude Opus 4.8 fce6faff2c fix(api): stabilize report pagination + declare real { data, meta } envelope on v1 single/write endpoints (#811)
* fix(reports): stabilize fetchAllRows paging to stop doubled/dropped balances (#790, #791)

PostgREST `.range()` paging is only correct when the underlying query has a
stable TOTAL order. Several aggregating report queries (general ledger, trial
balance, grundbok, supplier/AR ledgers, etc.) paginated without `.order()`, so
on datasets larger than one 1000-row page Postgres could return rows in a
different order between requests — silently DUPLICATING or SKIPPING rows on a
page boundary and doubling or dropping financial totals.

- fetch-all.ts: document the ordering invariant and add an optional
  `dedupeBy` defense-in-depth that drops cross-page duplicates and warns when
  it fires (surfaces a missing `.order()` in logs instead of corrupting money).
- Add a stable `.order()` (line PK or account_number) to every paginated query
  in lib/reports/ and the account-balances route; pass `dedupeBy` on the
  money-aggregating line queries.
- Add fetch-all unit tests and update report test fixtures to carry row ids.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): declare the real { data, meta } envelope on v1 single/write/204 endpoints (#794)

The OpenAPI generator derives each endpoint's documented body purely from its
registered `response.success` Zod schema, and that schema is never validated at
runtime — so a route could advertise a shape its handler never sends. #802
fixed this for list endpoints; the same drift was latent on single-resource and
write endpoints, which declared the bare resource schema instead of the
`{ data, meta }` envelope the handlers actually return.

- registry.ts: extend `ResponseMetaSchema` with the optional `audit` block and
  `partial_expansions` list that writes/expansions emit; add the `NoBodyResponse`
  sentinel so 204 DELETE handlers document a bare 204 instead of a phantom 200.
- Wrap every single/write endpoint's `response.success` in `dataEnvelope(...)`
  (or `NoBodyResponse` for 204s) across the v1 routes.
- Add a response-envelope contract test that fails CI if any JSON endpoint
  forgets to wrap its schema, with binary downloads and 204s as the only
  exemptions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(reports): extend paging dedupeBy to rc-basis-gaps and opening-balances

Address PR review: these two money-aggregating line queries already had the
stable `.order('id')` (so paging was correct) but didn't carry `id` in the
select, so they couldn't use the `dedupeBy` defense-in-depth that general-ledger
and trial-balance got. Select `id` and pass `dedupeBy: r => r.id` so the whole
report layer applies the ordering invariant consistently.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 13:42:50 +02:00

94 lines
3.6 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
/**
* 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. Uses fetchAllRows
// for consistency (avoids silent truncation) and joins journal_entries
// to enforce company_id ownership (defense in depth alongside RLS).
const obLines = await fetchAllRows<{
id: string
account_number: string
debit_amount: number
credit_amount: number
}>(({ from, to }) =>
supabase
.from('journal_entry_lines')
.select('id, account_number, debit_amount, credit_amount, journal_entries!inner(company_id)')
.eq('journal_entry_id', obEntryId)
.eq('journal_entries.company_id', companyId)
// Stable total order for correct paging (see fetch-all.ts).
.order('id', { ascending: true })
.range(from, to),
{ dedupeBy: (r) => r.id }
)
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 }
}