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>
This commit is contained in:
Mattsson
2026-08-06 23:00:05 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 28b58aedc4
commit cd344b6dbb
31 changed files with 1181 additions and 517 deletions
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { seedCompany, insertBalancedLines } from '@/tests/pg/fixtures'
import { seedCompany } from '@/tests/pg/fixtures'
// Covers the p_exclude_draft / p_collapse_corrections / p_series params on
// list_fiscal_period_entries_with_related (migrations 20260621130500 +
@@ -15,8 +15,10 @@ import { seedCompany, insertBalancedLines } from '@/tests/pg/fixtures'
// total_count must stay in lockstep with the filtered set so pagination holds.
describe('list_fiscal_period_entries_with_related: draft + correction filters', () => {
// Insert a journal_entry directly so we can set the storno/correction link
// columns the fixtures don't expose. Posted/reversed rows get balanced lines
// so any deferred balance check is satisfied.
// columns the fixtures don't expose. Header and balanced lines go in ONE
// transaction: check_balance_on_posted_insert is deferred to commit, so a
// posted header committed alone (autocommit per query) is rejected with
// "has zero total" before the lines could ever land.
async function insertEntry(p: {
userId: string
companyId: string
@@ -32,27 +34,45 @@ describe('list_fiscal_period_entries_with_related: draft + correction filters',
withLines?: boolean
}): Promise<string> {
const id = randomUUID()
await getPool().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, correction_of_id)
VALUES ($1,$2,$3,$4,$5,$11,$12,$6,$7,$8,$9,$10)`,
[
id,
p.userId,
p.companyId,
p.fiscalPeriodId,
p.voucherNumber,
p.description,
p.sourceType,
p.status,
p.reversesId ?? null,
p.correctionOfId ?? null,
p.voucherSeries ?? 'A',
p.entryDate ?? '2026-06-01',
],
)
if (p.withLines) await insertBalancedLines(id)
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, correction_of_id)
VALUES ($1,$2,$3,$4,$5,$11,$12,$6,$7,$8,$9,$10)`,
[
id,
p.userId,
p.companyId,
p.fiscalPeriodId,
p.voucherNumber,
p.description,
p.sourceType,
p.status,
p.reversesId ?? null,
p.correctionOfId ?? null,
p.voucherSeries ?? 'A',
p.entryDate ?? '2026-06-01',
],
)
if (p.withLines) {
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 1000, 0),
($1, '3001', 0, 1000)`,
[id],
)
}
await client.query('COMMIT')
} catch (err) {
await client.query('ROLLBACK').catch(() => {})
throw err
} finally {
client.release()
}
return id
}
+40 -3
View File
@@ -507,12 +507,25 @@ export async function POST(request: Request) {
historyVoucherNumbers.push(historyVoucherNumber as number)
}
// Inserted as draft and posted after the lines land: PostgREST autocommits
// each request, and check_balance_on_posted_insert (migration
// 20260806130000) rejects a posted header whose transaction carries no
// lines. The draft-to-posted UPDATE below fires check_balance_on_post
// against the finished verifikat instead.
//
// committed_at note: this route runs under the requester's authenticated
// client, and set_committed_at() (migration 20260806160000) preserves a
// preset committed_at only for trusted roles, so any backdated
// committed_at supplied here is overwritten with now() at posting. That
// is deliberate: an end-user role must never control the audit timestamp,
// and sandbox companies are disposable.
const { data: insertedHistoryEntries, error: historyEntryError } = await supabase
.from('journal_entries')
.insert(
ledgerHistory.entries.map((historyEntry, index) => ({
...historyEntry,
voucher_number: historyVoucherNumbers[index],
status: 'draft',
})),
)
.select('id, voucher_number')
@@ -542,6 +555,13 @@ export async function POST(request: Request) {
)
if (historyLinesError) throw historyLinesError
const { error: historyPostError } = await supabase
.from('journal_entries')
.update({ status: 'posted' })
.in('id', historyEntryIds)
.eq('company_id', companyId)
if (historyPostError) throw historyPostError
// The history is the company's books from before it arrived in Accounted:
// its kvitton live in the previous system's binder, not here. Left
// unflagged, every one of these vouchers would land on Hem as "Verifikat
@@ -577,7 +597,8 @@ export async function POST(request: Request) {
description: 'Faktura F-2026001, Björk & Partner AB',
source_type: 'invoice_created',
source_id: invoiceMap['F-2026001'],
status: 'posted',
// Draft until the lines exist; see the ledger-history comment above.
status: 'draft',
committed_at: toDateStr(thirtyDaysAgo),
})
.select('id')
@@ -603,7 +624,8 @@ export async function POST(request: Request) {
description: 'Betalning faktura F-2026001, Björk & Partner AB',
source_type: 'invoice_paid',
source_id: invoiceMap['F-2026001'],
status: 'posted',
// Draft until the lines exist; see the ledger-history comment above.
status: 'draft',
committed_at: toDateStr(fifteenDaysAgo),
})
.select('id')
@@ -675,6 +697,13 @@ export async function POST(request: Request) {
if (jelError) throw jelError
const { error: invoicePostError } = await supabase
.from('journal_entries')
.update({ status: 'posted' })
.in('id', [je1.id, je2.id])
.eq('company_id', companyId)
if (invoicePostError) throw invoicePostError
// 11. Create transactions
const { data: txRows, error: txError } = await supabase
.from('transactions')
@@ -1166,7 +1195,8 @@ export async function POST(request: Request) {
const { data: insertedSalaryEntry, error: salaryEntryError } = await supabase
.from('journal_entries')
.insert({ ...voucher.entry, voucher_number: salaryVoucherNumber })
// Draft until the lines exist; see the ledger-history comment above.
.insert({ ...voucher.entry, voucher_number: salaryVoucherNumber, status: 'draft' })
.select('id')
.single()
if (salaryEntryError) throw salaryEntryError
@@ -1185,6 +1215,13 @@ export async function POST(request: Request) {
runEntryLinks[voucher.runColumn] = insertedSalaryEntry.id
}
const { error: salaryPostError } = await supabase
.from('journal_entries')
.update({ status: 'posted' })
.in('id', Object.values(runEntryLinks))
.eq('company_id', companyId)
if (salaryPostError) throw salaryPostError
const { error: linkRunError } = await supabase
.from('salary_runs')
.update(runEntryLinks)