Files
accounted/lib/reports/journal-register.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

175 lines
6.1 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
export interface JournalRegisterLine {
account_number: string
account_name: string
debit: number
credit: number
}
export interface JournalRegisterEntry {
voucher_series: string
voucher_number: number
date: string
description: string
source_type: string
status: string
lines: JournalRegisterLine[]
total_debit: number
total_credit: number
}
export interface JournalRegisterReport {
entries: JournalRegisterEntry[]
total_entries: number
total_debit: number
total_credit: number
period: { start: string; end: string }
}
/**
* Generate journal register (grundbok) for a fiscal period.
* BFL 5 kap. 1 § — registreringsordning: all vouchers in chronological registration order.
*
* Uses a joined query with pagination to handle any number of entries.
* Avoids the broken .in(entryIds) pattern that silently truncated at 1000 rows.
*
* Unlike the general ledger and trial balance, the grundbok includes ALL
* entries — the opening_balance_entry is NOT excluded, because it is a
* real voucher that should appear in registration order.
*/
export async function generateJournalRegister(
supabase: SupabaseClient,
companyId: string,
periodId: string
): Promise<JournalRegisterReport> {
// Get fiscal period dates
const { data: period } = await supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
if (!period) {
return { entries: [], total_entries: 0, total_debit: 0, total_credit: 0, period: { start: '', end: '' } }
}
// Fetch all lines with joined entry data — single paginated query,
// no entry ID array, no truncation at 1000 rows
// Supabase types !inner joins as arrays; for many-to-one (line → entry)
// it returns a single object at runtime. Cast via `as any` on the query.
const rawLines = await fetchAllRows<{
id: string
account_number: string
debit_amount: number
credit_amount: number
journal_entry_id: string
journal_entries: {
id: string
entry_date: string
voucher_number: number
voucher_series: string
description: string
source_type: string
status: string
}
}>(({ from, to }) => {
return supabase
.from('journal_entry_lines')
.select('id, account_number, debit_amount, credit_amount, journal_entry_id, journal_entries!inner(id, entry_date, voucher_number, voucher_series, description, source_type, status, company_id, fiscal_period_id)')
.eq('journal_entries.company_id', companyId)
.eq('journal_entries.fiscal_period_id', periodId)
.in('journal_entries.status', ['posted', 'reversed'])
// Stable total order on the line PK — without it, rows duplicate/skip
// across pages and entries appear twice or go missing (see fetch-all.ts).
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.order('id', { ascending: true }).range(from, to) as any
}, { dedupeBy: (r) => r.id })
if (rawLines.length === 0) {
return { entries: [], total_entries: 0, total_debit: 0, total_credit: 0, period: { start: period.period_start, end: period.period_end } }
}
// Fetch account names
const accounts = await fetchAllRows<{ account_number: string; account_name: string }>(({ from, to }) =>
supabase
.from('chart_of_accounts')
.select('account_number, account_name')
.eq('company_id', companyId)
.order('account_number', { ascending: true })
.range(from, to)
)
const accountNameMap = new Map<string, string>()
for (const acc of accounts) {
accountNameMap.set(acc.account_number, acc.account_name)
}
// Extract unique entries and group lines by entry
const entryMap = new Map<string, typeof rawLines[0]['journal_entries']>()
const linesByEntry = new Map<string, JournalRegisterLine[]>()
for (const line of rawLines) {
const entryId = line.journal_entry_id
const entry = line.journal_entries
if (!entryMap.has(entryId)) {
entryMap.set(entryId, entry)
}
if (!linesByEntry.has(entryId)) {
linesByEntry.set(entryId, [])
}
linesByEntry.get(entryId)!.push({
account_number: line.account_number,
account_name: accountNameMap.get(line.account_number) || `Konto ${line.account_number}`,
debit: Math.round((Number(line.debit_amount) || 0) * 100) / 100,
credit: Math.round((Number(line.credit_amount) || 0) * 100) / 100,
})
}
// Build entries sorted by voucher_series, then voucher_number (registration order)
const sortedEntries = Array.from(entryMap.entries())
.sort(([, a], [, b]) => {
const seriesCompare = (a.voucher_series || 'A').localeCompare(b.voucher_series || 'A')
if (seriesCompare !== 0) return seriesCompare
return a.voucher_number - b.voucher_number
})
const result: JournalRegisterEntry[] = sortedEntries.map(([entryId, entry]) => {
const entryLines = linesByEntry.get(entryId) || []
// Sort lines by account number within each entry
entryLines.sort((a, b) => a.account_number.localeCompare(b.account_number))
const totalDebit = entryLines.reduce((sum, l) => sum + l.debit, 0)
const totalCredit = entryLines.reduce((sum, l) => sum + l.credit, 0)
return {
voucher_series: entry.voucher_series || 'A',
voucher_number: entry.voucher_number,
date: entry.entry_date,
description: entry.description || '',
source_type: entry.source_type || '',
status: entry.status,
lines: entryLines,
total_debit: Math.round(totalDebit * 100) / 100,
total_credit: Math.round(totalCredit * 100) / 100,
}
})
const grandTotalDebit = result.reduce((sum, e) => sum + e.total_debit, 0)
const grandTotalCredit = result.reduce((sum, e) => sum + e.total_credit, 0)
return {
entries: result,
total_entries: result.length,
total_debit: Math.round(grandTotalDebit * 100) / 100,
total_credit: Math.round(grandTotalCredit * 100) / 100,
period: { start: period.period_start, end: period.period_end },
}
}