Files
accounted/tests/pg/verifikat-without-documents-rpc.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

218 lines
7.1 KiB
TypeScript

import { randomUUID } from 'crypto'
import { beforeAll, describe, expect, it } from 'vitest'
import { getPool, withUserContext } from './setup'
import {
seedCompany,
insertAuthUser,
insertDraftJournalEntry,
insertPostedJournalEntry,
insertBalancedLines,
} from './fixtures'
/**
* Invariants for the verifikat_without_documents RPC (mcp_optimization_plan
* P0-2). The predecessor applied min_amount in memory after the DB page:
* total_count ignored the filter and consecutive pages overlapped. These
* tests pin the SQL-side behavior: filter-respecting total, disjoint and
* complete pages, since filter, doc/draft exclusion, tenant guard.
*/
type RpcRow = {
journal_entry_id: string
voucher_number: number
gross_amount: number
}
type RpcResult = {
ok: boolean
code?: string
total_count?: number
verifikat?: RpcRow[]
}
async function callRpc(params: {
companyId: string
since?: string | null
minAmount?: number
limit?: number
offset?: number
}): Promise<RpcResult> {
const { rows } = await getPool().query<{ result: RpcResult }>(
`SELECT public.verifikat_without_documents($1, $2, $3, $4, $5) AS result`,
[
params.companyId,
params.since ?? null,
params.minAmount ?? 0,
params.limit ?? 20,
params.offset ?? 0,
],
)
return rows[0].result
}
async function attachDocument(params: {
userId: string
companyId: string
journalEntryId: string
}): Promise<void> {
await getPool().query(
`INSERT INTO public.document_attachments
(id, user_id, company_id, journal_entry_id, file_name, mime_type,
file_size_bytes, storage_path, sha256_hash, upload_source)
VALUES ($1, $2, $3, $4, 'underlag.pdf', 'application/pdf', 1024, $5, $6, 'file_upload')`,
[
randomUUID(),
params.userId,
params.companyId,
params.journalEntryId,
`documents/${params.companyId}/underlag.pdf`,
randomUUID().replace(/-/g, '').padEnd(64, '0'),
],
)
}
describe('verifikat_without_documents RPC', () => {
let userId: string
let companyId: string
let fiscalPeriodId: string
// voucher_number → { id, amount }; amounts chosen so min_amount splits the set
const seeded = new Map<number, { id: string; amount: number }>()
beforeAll(async () => {
const s = await seedCompany()
userId = s.userId
companyId = s.companyId
fiscalPeriodId = s.fiscalPeriodId
// 6 posted entries without documents: amounts 100..600, dates ascending
for (let i = 1; i <= 6; i++) {
const id = await insertPostedJournalEntry({
userId,
companyId,
fiscalPeriodId,
voucherNumber: i,
entryDate: `2026-06-0${i}`,
description: `no-doc ${i}`,
lines: [
{ accountNumber: '1930', debitAmount: i * 100, creditAmount: 0 },
{ accountNumber: '3001', debitAmount: 0, creditAmount: i * 100 },
],
})
seeded.set(i, { id, amount: i * 100 })
}
// Posted entry WITH a document: must never appear
const withDoc = await insertPostedJournalEntry({
userId,
companyId,
fiscalPeriodId,
voucherNumber: 7,
entryDate: '2026-06-07',
description: 'has doc',
lines: [
{ accountNumber: '1930', debitAmount: 700, creditAmount: 0 },
{ accountNumber: '3001', debitAmount: 0, creditAmount: 700 },
],
})
await attachDocument({ userId, companyId, journalEntryId: withDoc })
// Draft entry: must never appear
const draft = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'draft',
voucherNumber: 8,
entryDate: '2026-06-08',
description: 'draft',
})
await insertBalancedLines(draft, 800)
})
it('lists posted no-doc entries only, newest first, with gross amounts', async () => {
const res = await callRpc({ companyId })
expect(res.ok).toBe(true)
expect(res.total_count).toBe(6)
const rows = res.verifikat ?? []
expect(rows.map((r) => r.voucher_number)).toEqual([6, 5, 4, 3, 2, 1])
expect(rows[0].gross_amount).toBe(600)
})
it('total_count respects min_amount', async () => {
const res = await callRpc({ companyId, minAmount: 350 })
expect(res.ok).toBe(true)
// amounts 400, 500, 600 pass the filter
expect(res.total_count).toBe(3)
expect((res.verifikat ?? []).map((r) => r.voucher_number)).toEqual([6, 5, 4])
})
it('paginates a filtered set with disjoint, complete pages', async () => {
const collected: string[] = []
let offset = 0
for (;;) {
const res = await callRpc({ companyId, minAmount: 250, limit: 2, offset })
expect(res.ok).toBe(true)
expect(res.total_count).toBe(4) // amounts 300..600
const rows = res.verifikat ?? []
if (rows.length === 0) break
collected.push(...rows.map((r) => r.journal_entry_id))
offset += rows.length
if (offset >= (res.total_count ?? 0)) break
}
// No duplicates (the old in-memory filter overlapped pages) …
expect(new Set(collected).size).toBe(collected.length)
// … and no gaps: exactly the 4 entries ≥ 250.
const expected = [3, 4, 5, 6].map((n) => seeded.get(n)!.id).sort()
expect([...collected].sort()).toEqual(expected)
})
it('respects the since filter', async () => {
const res = await callRpc({ companyId, since: '2026-06-04' })
expect(res.ok).toBe(true)
expect(res.total_count).toBe(3)
expect((res.verifikat ?? []).map((r) => r.voucher_number)).toEqual([6, 5, 4])
})
it('offset past the end returns an empty page with a truthful total', async () => {
const res = await callRpc({ companyId, minAmount: 250, limit: 2, offset: 10 })
expect(res.ok).toBe(true)
expect(res.total_count).toBe(4)
expect(res.verifikat).toEqual([])
})
it('blocks an authenticated caller from another tenant', async () => {
const strangerId = await insertAuthUser()
const res = await withUserContext(strangerId, async (client) => {
const { rows } = await client.query<{ result: RpcResult }>(
`SELECT public.verifikat_without_documents($1, NULL, 0, 20, 0) AS result`,
[companyId],
)
return rows[0].result
})
expect(res.ok).toBe(false)
expect(res.code).toBe('VERIFIKAT_WITHOUT_DOCUMENTS_FORBIDDEN')
})
it('rejects a NULL company id for authenticated callers (NOT IN → UNKNOWN bypass)', async () => {
const res = await withUserContext(userId, async (client) => {
const { rows } = await client.query<{ result: RpcResult }>(
`SELECT public.verifikat_without_documents(NULL, NULL, 0, 20, 0) AS result`,
)
return rows[0].result
})
expect(res.ok).toBe(false)
expect(res.code).toBe('VERIFIKAT_WITHOUT_DOCUMENTS_FORBIDDEN')
})
it('allows an authenticated member of the company', async () => {
const res = await withUserContext(userId, async (client) => {
const { rows } = await client.query<{ result: RpcResult }>(
`SELECT public.verifikat_without_documents($1, NULL, 0, 20, 0) AS result`,
[companyId],
)
return rows[0].result
})
expect(res.ok).toBe(true)
expect(res.total_count).toBe(6)
})
})