Files
accounted/tests/pg/closing-entry-detach.pg.test.ts
T
MattssonandClaude Fable 5 cd344b6dbb fix(db): enforce balance check on directly inserted posted journal entries (v2) (#1439)
* fix(db): enforce balance check on directly inserted posted journal entries

check_balance_on_post only fires on the draft-to-posted UPDATE transition,
so any code path that INSERTs a row with status 'posted' directly skipped
balance validation entirely. The invariant sum(debit) = sum(credit) on
every posted entry was DB-enforced only for the engine's commit lifecycle.

Add check_balance_on_posted_insert, a deferred constraint trigger on
AFTER INSERT WHEN (NEW.status = 'posted') reusing the existing
check_journal_entry_balance() function, which already handles the
journal_entries INSERT context via NEW.id/NEW.status. Deferred semantics
let an atomic transaction insert header and lines together; zero-line and
unbalanced posted inserts are rejected at constraint evaluation. All
existing checks stay intact; this only adds coverage.

The one first-party posted-INSERT path outside an RPC, the sandbox seed,
now books through the bookkeeping engine (createJournalEntry) instead of
raw inserts. SIE import already inserts header and lines in a single
transaction via its structured RPC and passes unchanged.

pg tests cover the new path (zero-line rejected, unbalanced rejected at
SET CONSTRAINTS IMMEDIATE, balanced same-transaction insert accepted) and
existing posted-entry fixtures move to a transactional
insertPostedJournalEntry helper so they stay valid setup.

Fixes #327

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

* fix(tests): insert list-filters pg fixtures in one transaction

The list-filters suite (landed via a sibling merge) inserted posted
headers with getPool().query, where each query autocommits: the deferred
check_balance_on_posted_insert constraint fired at the header's own
commit with zero lines and correctly rejected the fixture. Header and
balanced lines now share one BEGIN/COMMIT so the constraint evaluates
the complete entry, mirroring the insertPostedJournalEntry helper.

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

* fix(seed): insert journal headers as drafts, post after lines land

check_balance_on_posted_insert (renamed to apply-time version
20260806130000) rejects a posted header whose transaction has no lines.
PostgREST autocommits each request, so every seed path that inserted
posted headers first would die with "has zero total": the sandbox seed
(ledger history, invoice vouchers, salary vouchers), seed-demo-account
and seed-export-data. All now insert draft headers, insert lines, then
flip to posted so check_balance_on_post validates the finished
verifikat. The sandbox seed keeps its documented no-events design.

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

* fix(db): preserve a preset committed_at on draft-to-posted transition

set_committed_at() stamped now() unconditionally, so the seed flows that
post backdated drafts lost their historical booking timestamps and every
demo verifikat read as booked today (CodeRabbit finding on PR 1439).
Stamp only when committed_at is NULL: the engine path (drafts carry no
committed_at) behaves exactly as before and a posted entry still always
has a committed_at; an explicitly supplied value now survives posting.

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

* fix(db): preserve preset committed_at only for trusted roles

The IS NULL guard alone (20260806150000, never shipped; replaced by
20260806160000) let any RLS-permitted member backdate committed_at
through PostgREST by presetting it on a draft and posting, which the
Swedish accounting review flagged: committed_at is what the BFL 5 kap
timeliness checks and behandlingshistorik treat as the genuine
transition time. Preset values now survive posting only for
service_role/postgres/supabase_admin; authenticated and anon writers
always get the now() stamp. Consequence: the sandbox seed (runs as the
requesting user) gets committed_at = posting time, accepted and
documented in the route; the demo scripts run as service_role and keep
their backdated history. pg tests cover all four paths, with the upper
timestamp bound CodeRabbit asked for.

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

* fix(db): restore superseded migration so the preview tracker stays consistent

The preview branch had already applied 20260806150000 when the previous
commit deleted the file, orphaning the preview's migration tracker
("Remote migration versions not found in local migrations directory").
Restored with a header explaining it is superseded in the same deploy by
20260806160000, so the unguarded semantics are never live on their own.

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

* fix(db): decide committed_at trust by JWT claims, not current_user

The Swedish review found the current_user guard bypassable:
commit_journal_entry is SECURITY DEFINER and granted to authenticated,
so inside it current_user is the function owner and a member could
preset a backdated committed_at on a direct-inserted draft and launder
it through the RPC. The guard now reads the JWT claims role (same
primitive as the RPC's own tenant guard): preset values survive only
for service_role or claim-less backend connections; authenticated and
anon callers are always stamped now(), on both the direct UPDATE and
the RPC path (new pg test). Both migration files now carry the
identical final body so no unguarded intermediate exists as a
standalone applyable unit. Behandlingshistorik logging of trusted
overrides is follow-up #1444.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 23:00:05 +02:00

269 lines
8.1 KiB
TypeScript

import { describe, it, expect, beforeAll } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from './setup'
import { seedCompany, insertDraftJournalEntry } from './fixtures'
// Escape hatch in enforce_opening_balance_immutability (migration
// 20260720140000): closing_entry_id may only change once set when the
// previously referenced closing entry is status='reversed' AND a posted
// storno entry with reverses_id pointing at it exists (the chain only the
// engine's reverseEntry() produces). A non-NULL replacement must be a posted
// year_end entry in the same company and period. Used by the administrative
// year-end undo flow (scripts/undo-year-end-closing.ts).
async function insertStornoOf(params: {
userId: string
companyId: string
fiscalPeriodId: string
reversesId: string
voucherNumber: number
status?: string
sourceType?: string
}): Promise<string> {
const id = randomUUID()
const status = params.status ?? 'posted'
const client = await getPool().connect()
try {
await client.query('BEGIN')
await client.query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status, reverses_id)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-12-31', 'Makulering', $6, $7, $8)`,
[
id,
params.userId,
params.companyId,
params.fiscalPeriodId,
params.voucherNumber,
params.sourceType ?? 'storno',
status,
params.reversesId,
],
)
if (status === 'posted') {
// Mirror the default closing-entry fixture so the storno is a valid,
// balanced voucher while this suite focuses on the reversal chain.
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '3001', 1000, 0),
($1, '1930', 0, 1000)`,
[id],
)
await client.query('SET CONSTRAINTS check_balance_on_posted_insert IMMEDIATE')
}
await client.query('COMMIT')
return id
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
}
describe('closing_entry_id detach escape hatch', () => {
let companyId: string
let userId: string
let fiscalPeriodId: string
let closingEntryId: string
beforeAll(async () => {
const seeded = await seedCompany()
companyId = seeded.companyId
userId = seeded.userId
fiscalPeriodId = seeded.fiscalPeriodId
closingEntryId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-12-31',
description: 'Årsbokslut',
sourceType: 'year_end',
status: 'posted',
voucherNumber: 1,
})
await getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = $1 WHERE id = $2`,
[closingEntryId, fiscalPeriodId],
)
})
it('blocks detaching a posted (live) closing entry', async () => {
await expect(
getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = NULL WHERE id = $1`,
[fiscalPeriodId],
),
).rejects.toThrow(/year-end closing is immutable/)
})
it('blocks detaching when status is reversed but no storno chain exists', async () => {
await getPool().query(
`UPDATE public.journal_entries SET status = 'reversed' WHERE id = $1`,
[closingEntryId],
)
await expect(
getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = NULL WHERE id = $1`,
[fiscalPeriodId],
),
).rejects.toThrow(/year-end closing is immutable/)
})
it('blocks the escape hatch when the storno is not posted', async () => {
// closingEntryId is status='reversed' from the previous test.
await insertStornoOf({
userId,
companyId,
fiscalPeriodId,
reversesId: closingEntryId,
voucherNumber: 2,
status: 'cancelled',
})
await expect(
getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = NULL WHERE id = $1`,
[fiscalPeriodId],
),
).rejects.toThrow(/year-end closing is immutable/)
})
it('blocks replacing a reversed closing entry with a non-year_end entry', async () => {
// Complete the storno chain so the reversal itself is now legitimate.
await insertStornoOf({
userId,
companyId,
fiscalPeriodId,
reversesId: closingEntryId,
voucherNumber: 3,
})
const manualId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-12-31',
sourceType: 'manual',
status: 'posted',
voucherNumber: 4,
})
await expect(
getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = $1 WHERE id = $2`,
[manualId, fiscalPeriodId],
),
).rejects.toThrow(/must reference a posted year_end entry/)
})
it('allows detaching once the closing entry is reversed with a posted storno', async () => {
await getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = NULL WHERE id = $1`,
[fiscalPeriodId],
)
const { rows } = await getPool().query(
`SELECT closing_entry_id FROM public.fiscal_periods WHERE id = $1`,
[fiscalPeriodId],
)
expect(rows[0].closing_entry_id).toBeNull()
})
it('still allows setting closing_entry_id from NULL (normal year-end run)', async () => {
const newClosingId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-12-31',
sourceType: 'year_end',
status: 'posted',
voucherNumber: 5,
})
await getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = $1 WHERE id = $2`,
[newClosingId, fiscalPeriodId],
)
const { rows } = await getPool().query(
`SELECT closing_entry_id FROM public.fiscal_periods WHERE id = $1`,
[fiscalPeriodId],
)
expect(rows[0].closing_entry_id).toBe(newClosingId)
})
it('allows replacing a properly reversed closing entry with a posted year_end entry', async () => {
// Reverse the current closing entry with a full storno chain, then swap
// directly to a new posted year_end entry (re-run without detach first).
const { rows: current } = await getPool().query(
`SELECT closing_entry_id FROM public.fiscal_periods WHERE id = $1`,
[fiscalPeriodId],
)
const currentClosingId = current[0].closing_entry_id
await getPool().query(
`UPDATE public.journal_entries SET status = 'reversed' WHERE id = $1`,
[currentClosingId],
)
await insertStornoOf({
userId,
companyId,
fiscalPeriodId,
reversesId: currentClosingId,
voucherNumber: 6,
})
const replacementId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-12-31',
sourceType: 'year_end',
status: 'posted',
voucherNumber: 7,
})
await getPool().query(
`UPDATE public.fiscal_periods SET closing_entry_id = $1 WHERE id = $2`,
[replacementId, fiscalPeriodId],
)
const { rows } = await getPool().query(
`SELECT closing_entry_id FROM public.fiscal_periods WHERE id = $1`,
[fiscalPeriodId],
)
expect(rows[0].closing_entry_id).toBe(replacementId)
})
it('opening balance immutability is unchanged', async () => {
const ibEntryId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
entryDate: '2026-01-01',
sourceType: 'opening_balance',
status: 'posted',
voucherNumber: 8,
})
await getPool().query(
`UPDATE public.fiscal_periods
SET opening_balance_entry_id = $1, opening_balances_set = true
WHERE id = $2`,
[ibEntryId, fiscalPeriodId],
)
await expect(
getPool().query(
`UPDATE public.fiscal_periods SET opening_balance_entry_id = NULL WHERE id = $1`,
[fiscalPeriodId],
),
).rejects.toThrow(/opening balances are immutable/)
})
})