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:
co-authored by
Claude Fable 5
parent
28b58aedc4
commit
cd344b6dbb
@@ -11,7 +11,12 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertCompany,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertJournalEntry(params: {
|
||||
userId: string
|
||||
@@ -21,6 +26,23 @@ async function insertJournalEntry(params: {
|
||||
status: 'draft' | 'posted'
|
||||
lines: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
if (params.status === 'posted') {
|
||||
return insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: '2026-03-15',
|
||||
description: 'Usage test',
|
||||
sourceType: 'manual',
|
||||
lines: params.lines.map((line) => ({
|
||||
accountNumber: line.account,
|
||||
debitAmount: line.debit,
|
||||
creditAmount: line.credit,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
const id = randomUUID()
|
||||
// Insert directly, bypassing commit_journal_entry's voucher sequencing —
|
||||
// fine for a read-side RPC that only aggregates line/account references.
|
||||
|
||||
+14
-15
@@ -21,6 +21,7 @@ import {
|
||||
insertCompany,
|
||||
insertCompanyMember,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertAsset(params: {
|
||||
@@ -86,21 +87,19 @@ async function insertPostedEntry(params: {
|
||||
fiscalPeriodId: string
|
||||
voucherNumber?: number
|
||||
}): 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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', '2025-12-31', 'Test', 'year_end', 'posted')`,
|
||||
[id, params.userId, params.companyId, params.fiscalPeriodId, params.voucherNumber ?? 1],
|
||||
)
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, '7832', 12000, 0), ($1, '1229', 0, 12000)`,
|
||||
[id],
|
||||
)
|
||||
return id
|
||||
return insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber ?? 1,
|
||||
entryDate: '2025-12-31',
|
||||
description: 'Test',
|
||||
sourceType: 'year_end',
|
||||
lines: [
|
||||
{ accountNumber: '7832', debitAmount: 12000, creditAmount: 0 },
|
||||
{ accountNumber: '1229', debitAmount: 0, creditAmount: 12000 },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
let companyA: { userId: string; companyId: string; fiscalPeriodId: string }
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
insertCompany,
|
||||
insertCompanyMember,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry,
|
||||
} from '@/tests/pg/fixtures'
|
||||
import { getPool, withUserContext } from '@/tests/pg/setup'
|
||||
|
||||
@@ -422,21 +423,20 @@ describe('bulk_book_transactions: document inheritance (PR #608)', () => {
|
||||
|
||||
// Manually pre-post a day-summary verifikat the user wants the txs
|
||||
// linked to. Bank net must equal sum(tx.amount) = 300.
|
||||
const jeId = 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)
|
||||
VALUES ($1, $2, $3, $4, 1, 'A', '2026-06-05', 'Manual day summary', 'manual', 'posted')`,
|
||||
[jeId, userId, companyId, fiscalPeriodId],
|
||||
)
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines (journal_entry_id, account_number, debit_amount, credit_amount, currency, sort_order)
|
||||
VALUES ($1, '1930', 300, 0, 'SEK', 0),
|
||||
($1, '3001', 0, 240, 'SEK', 1),
|
||||
($1, '2611', 0, 60, 'SEK', 2)`,
|
||||
[jeId],
|
||||
)
|
||||
const jeId = await insertPostedJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
voucherNumber: 1,
|
||||
entryDate: '2026-06-05',
|
||||
description: 'Manual day summary',
|
||||
sourceType: 'manual',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 300, creditAmount: 0, currency: 'SEK', sortOrder: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 240, currency: 'SEK', sortOrder: 1 },
|
||||
{ accountNumber: '2611', debitAmount: 0, creditAmount: 60, currency: 'SEK', sortOrder: 2 },
|
||||
],
|
||||
})
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
const r = await client.query<{ bulk_book_transactions: RpcResult & { docs_linked?: number } }>(
|
||||
|
||||
@@ -21,23 +21,49 @@ async function insertStornoOf(params: {
|
||||
sourceType?: string
|
||||
}): 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)
|
||||
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',
|
||||
params.status ?? 'posted',
|
||||
params.reversesId,
|
||||
],
|
||||
)
|
||||
return id
|
||||
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', () => {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getPool, withUserContext, runAsServiceRole } from './setup'
|
||||
import { seedCompany, insertDraftJournalEntry, insertBalancedLines } from './fixtures'
|
||||
|
||||
// set_committed_at() after migration 20260806160000: on draft-to-posted the
|
||||
// preset committed_at survives ONLY for backend writers, decided by the JWT
|
||||
// claims role (service_role, or no claims at all: direct SQL and pg tests).
|
||||
// Seeding flows backdate history that way. For end-user callers the stamp
|
||||
// stays tamper-proof: RLS lets a member insert a draft with any committed_at,
|
||||
// and the timeliness checks (BFL 5 kap) read committed_at as the genuine
|
||||
// transition time, so an authenticated caller must never control it: not via
|
||||
// a direct UPDATE, and not by laundering the post through the SECURITY
|
||||
// DEFINER commit_journal_entry RPC (which is why the guard reads JWT claims,
|
||||
// not current_user). Drafts with no committed_at are stamped now() for
|
||||
// everyone.
|
||||
|
||||
const BACKDATED = '2026-03-15T10:00:00Z'
|
||||
const BACKDATED_ISO = '2026-03-15T10:00:00.000Z'
|
||||
|
||||
async function seedBackdatedDraft(): Promise<{ entryId: string; userId: string }> {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
entryDate: '2026-03-15',
|
||||
committedAt: BACKDATED,
|
||||
})
|
||||
await insertBalancedLines(entryId)
|
||||
return { entryId, userId }
|
||||
}
|
||||
|
||||
describe('set_committed_at trusted-writer preservation', () => {
|
||||
it('preserves a backdated committed_at when posting as postgres', async () => {
|
||||
const { entryId } = await seedBackdatedDraft()
|
||||
const pool = getPool()
|
||||
await pool.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
||||
entryId,
|
||||
])
|
||||
const { rows } = await pool.query<{ committed_at: Date }>(
|
||||
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
expect(rows[0].committed_at.toISOString()).toBe(BACKDATED_ISO)
|
||||
})
|
||||
|
||||
it('preserves a backdated committed_at when posting as service_role', async () => {
|
||||
const { entryId } = await seedBackdatedDraft()
|
||||
const committedAt = await runAsServiceRole(async (client) => {
|
||||
await client.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
||||
entryId,
|
||||
])
|
||||
const { rows } = await client.query<{ committed_at: Date }>(
|
||||
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
return rows[0].committed_at
|
||||
})
|
||||
expect(committedAt.toISOString()).toBe(BACKDATED_ISO)
|
||||
})
|
||||
|
||||
it('overwrites a preset committed_at when an authenticated member posts', async () => {
|
||||
const { entryId, userId } = await seedBackdatedDraft()
|
||||
const before = Date.now()
|
||||
const committedAt = await withUserContext(userId, async (client) => {
|
||||
const updated = await client.query(
|
||||
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1 RETURNING id`,
|
||||
[entryId],
|
||||
)
|
||||
// RLS must actually let the member's UPDATE through; 0 rows would make
|
||||
// the assertion below pass vacuously against the seeded value.
|
||||
expect(updated.rowCount).toBe(1)
|
||||
const { rows } = await client.query<{ committed_at: Date }>(
|
||||
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
return rows[0].committed_at
|
||||
})
|
||||
const after = Date.now()
|
||||
expect(committedAt.toISOString()).not.toBe(BACKDATED_ISO)
|
||||
expect(committedAt.getTime()).toBeGreaterThanOrEqual(before - 60_000)
|
||||
expect(committedAt.getTime()).toBeLessThanOrEqual(after + 60_000)
|
||||
})
|
||||
|
||||
it('overwrites a preset committed_at when an authenticated member posts via commit_journal_entry', async () => {
|
||||
// The laundering path: the RPC is SECURITY DEFINER, so current_user
|
||||
// inside it is the function owner. The guard must still see the caller's
|
||||
// JWT claims and stamp now().
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
entryDate: '2026-03-15',
|
||||
committedAt: BACKDATED,
|
||||
})
|
||||
await insertBalancedLines(entryId)
|
||||
|
||||
const before = Date.now()
|
||||
const committedAt = await withUserContext(userId, async (client) => {
|
||||
const committed = await client.query<{ voucher_number: number }>(
|
||||
`SELECT * FROM public.commit_journal_entry($1, $2)`,
|
||||
[companyId, entryId],
|
||||
)
|
||||
expect(committed.rows[0].voucher_number).toBeGreaterThan(0)
|
||||
const { rows } = await client.query<{ committed_at: Date }>(
|
||||
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
return rows[0].committed_at
|
||||
})
|
||||
const after = Date.now()
|
||||
expect(committedAt.toISOString()).not.toBe(BACKDATED_ISO)
|
||||
expect(committedAt.getTime()).toBeGreaterThanOrEqual(before - 60_000)
|
||||
expect(committedAt.getTime()).toBeLessThanOrEqual(after + 60_000)
|
||||
})
|
||||
|
||||
it('stamps now() when the draft carries no committed_at', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
entryDate: '2026-03-15',
|
||||
})
|
||||
await insertBalancedLines(entryId)
|
||||
|
||||
const pool = getPool()
|
||||
const before = Date.now()
|
||||
await pool.query(`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`, [
|
||||
entryId,
|
||||
])
|
||||
const after = Date.now()
|
||||
const { rows } = await pool.query<{ committed_at: Date | null }>(
|
||||
`SELECT committed_at FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
expect(rows[0].committed_at).not.toBeNull()
|
||||
// Stamped at posting time, not the (older) entry_date.
|
||||
expect(rows[0].committed_at!.getTime()).toBeGreaterThanOrEqual(before - 60_000)
|
||||
expect(rows[0].committed_at!.getTime()).toBeLessThanOrEqual(after + 60_000)
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import { getPool } from './setup'
|
||||
import {
|
||||
seedCompany,
|
||||
insertDraftJournalEntry,
|
||||
insertPostedJournalEntry,
|
||||
insertBalancedLines,
|
||||
insertTransaction,
|
||||
} from './fixtures'
|
||||
@@ -169,18 +170,19 @@ describe('document surfaces unification', () => {
|
||||
fiscalPeriodId = s.fiscalPeriodId
|
||||
|
||||
const mkJe = async (n: number, sourceType: string) => {
|
||||
const id = await insertDraftJournalEntry({
|
||||
return insertPostedJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: n,
|
||||
entryDate: `2026-06-${String(n).padStart(2, '0')}`,
|
||||
description: `${sourceType} ${n}`,
|
||||
sourceType,
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: n * 100, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: n * 100 },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(id, n * 100)
|
||||
return id
|
||||
}
|
||||
|
||||
jeBankNoDoc = await mkJe(1, 'bank_transaction')
|
||||
@@ -331,17 +333,19 @@ describe('document surfaces unification', () => {
|
||||
let voucher = 1
|
||||
const expected: string[] = []
|
||||
for (const sourceType of NEEDS_DOC_SOURCE_TYPES) {
|
||||
const id = await insertDraftJournalEntry({
|
||||
const id = await insertPostedJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
fiscalPeriodId: s.fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: voucher,
|
||||
entryDate: '2026-06-15',
|
||||
description: sourceType,
|
||||
sourceType,
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 100 * voucher, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 100 * voucher },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(id, 100 * voucher)
|
||||
expected.push(id)
|
||||
voucher++
|
||||
}
|
||||
@@ -385,18 +389,19 @@ describe('transaction-pinned document backfill (migration 20260724090000 §4)',
|
||||
const s = await seedCompany()
|
||||
|
||||
const mkPostedJe = async (n: number, fiscalPeriodId: string) => {
|
||||
const id = await insertDraftJournalEntry({
|
||||
return insertPostedJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: n,
|
||||
entryDate: '2026-06-15',
|
||||
description: `backfill ${n}`,
|
||||
sourceType: 'supplier_invoice_paid',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 100 * n, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 100 * n },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(id, 100 * n)
|
||||
return id
|
||||
}
|
||||
|
||||
// Case A (Emil's flow): doc pinned to the tx, never propagated.
|
||||
@@ -534,6 +539,21 @@ describe('floating supplier-invoice document backfill (migration 20260727180000)
|
||||
// the verifikat view still displayed the PDF.
|
||||
const s = await seedCompany()
|
||||
const mkJe = async (n: number, status: 'posted' | 'reversed', sourceType: string) => {
|
||||
if (status === 'posted') {
|
||||
return insertPostedJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
fiscalPeriodId: s.fiscalPeriodId,
|
||||
voucherNumber: n,
|
||||
entryDate: '2026-06-15',
|
||||
description: `anchor ${n}`,
|
||||
sourceType,
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 100 * n, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 100 * n },
|
||||
],
|
||||
})
|
||||
}
|
||||
const id = await insertDraftJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
@@ -580,18 +600,19 @@ describe('floating supplier-invoice document backfill (migration 20260727180000)
|
||||
it('prefers the registration verifikat and never steals an anchored doc', async () => {
|
||||
const s = await seedCompany()
|
||||
const mkJe = async (n: number, sourceType: string) => {
|
||||
const id = await insertDraftJournalEntry({
|
||||
return insertPostedJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
fiscalPeriodId: s.fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: n,
|
||||
entryDate: '2026-06-15',
|
||||
description: `prefer ${n}`,
|
||||
sourceType,
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 100 * n, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 100 * n },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(id, 100 * n)
|
||||
return id
|
||||
}
|
||||
|
||||
const jeReg = await mkJe(1, 'supplier_invoice_registered')
|
||||
@@ -637,17 +658,19 @@ describe('floating supplier-invoice document backfill (migration 20260727180000)
|
||||
|
||||
it('skips closed periods: the period-lock trigger would reject the write anyway', async () => {
|
||||
const s = await seedCompany()
|
||||
const je = await insertDraftJournalEntry({
|
||||
const je = await insertPostedJournalEntry({
|
||||
userId: s.userId,
|
||||
companyId: s.companyId,
|
||||
fiscalPeriodId: s.fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: 1,
|
||||
entryDate: '2026-06-15',
|
||||
description: 'closed period',
|
||||
sourceType: 'supplier_invoice_paid',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 100, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 100 },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(je, 100)
|
||||
const supplierId = await insertSupplier({ userId: s.userId, companyId: s.companyId })
|
||||
const doc = await attachDocument({
|
||||
userId: s.userId,
|
||||
|
||||
@@ -179,6 +179,10 @@ export async function insertDraftJournalEntry(params: {
|
||||
// fires on draft->posted UPDATE), so committed_at stays null unless set here.
|
||||
committedAt?: string | null
|
||||
}): Promise<string> {
|
||||
if (params.status === 'posted') {
|
||||
return insertPostedJournalEntry(params)
|
||||
}
|
||||
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entries
|
||||
@@ -204,6 +208,95 @@ export async function insertDraftJournalEntry(params: {
|
||||
return id
|
||||
}
|
||||
|
||||
export interface PostedJournalEntryLine {
|
||||
accountNumber: string
|
||||
debitAmount: number
|
||||
creditAmount: number
|
||||
currency?: string
|
||||
lineDescription?: string | null
|
||||
sortOrder?: number
|
||||
dimensions?: Record<string, string>
|
||||
}
|
||||
|
||||
// Insert a posted entry and all of its lines in one transaction. This is the
|
||||
// only valid shape for pg fixtures that intentionally exercise a direct posted
|
||||
// INSERT: check_balance_on_posted_insert is deferred until the lines exist, but
|
||||
// still executes before COMMIT.
|
||||
export async function insertPostedJournalEntry(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
fiscalPeriodId: string
|
||||
entryDate?: string
|
||||
description?: string
|
||||
voucherSeries?: string
|
||||
voucherNumber?: number
|
||||
sourceType?: string
|
||||
sourceId?: string | null
|
||||
createdAt?: string
|
||||
committedAt?: string | null
|
||||
lines?: PostedJournalEntryLine[]
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const lines = params.lines ?? [
|
||||
{ accountNumber: '1930', debitAmount: 1000, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 1000 },
|
||||
]
|
||||
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, source_id, status, created_at, committed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'posted',
|
||||
COALESCE($11::timestamptz, now()), $12::timestamptz)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber ?? 0,
|
||||
params.voucherSeries ?? 'A',
|
||||
params.entryDate ?? '2026-06-01',
|
||||
params.description ?? 'Test entry',
|
||||
params.sourceType ?? 'manual',
|
||||
params.sourceId ?? null,
|
||||
params.createdAt ?? null,
|
||||
params.committedAt ?? null,
|
||||
],
|
||||
)
|
||||
|
||||
for (const [index, line] of lines.entries()) {
|
||||
await client.query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount,
|
||||
currency, line_description, sort_order, dimensions)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb)`,
|
||||
[
|
||||
id,
|
||||
line.accountNumber,
|
||||
line.debitAmount,
|
||||
line.creditAmount,
|
||||
line.currency ?? 'SEK',
|
||||
line.lineDescription ?? null,
|
||||
line.sortOrder ?? index,
|
||||
JSON.stringify(line.dimensions ?? {}),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
// Insert a balanced pair of journal entry lines (1 debit row + 1 credit row
|
||||
// at the given amount). Needed before commit_journal_entry() because the
|
||||
// balance constraint trigger fires on draft→posted.
|
||||
|
||||
@@ -17,13 +17,13 @@
|
||||
* is covered in mark-entry-as-opening-balance.pg.test.ts.)
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool } from './setup'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertCashAccount,
|
||||
insertCompany,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry as insertAtomicPostedJournalEntry,
|
||||
insertTransaction,
|
||||
} from './fixtures'
|
||||
|
||||
@@ -38,37 +38,25 @@ async function insertPostedJournalEntry(params: {
|
||||
/** Line rows to book; defaults to the classic 1930 debit / 2091 credit pair. */
|
||||
lines?: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const amount = params.amount ?? 1000
|
||||
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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', $6, $7, $8, 'posted')`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate,
|
||||
`Test ${params.sourceType}`,
|
||||
params.sourceType,
|
||||
],
|
||||
)
|
||||
const lines = params.lines ?? [
|
||||
{ account: '1930', debit: amount, credit: 0 },
|
||||
{ account: '2091', debit: 0, credit: amount },
|
||||
]
|
||||
for (const line of lines) {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[id, line.account, line.debit, line.credit],
|
||||
)
|
||||
}
|
||||
return id
|
||||
return insertAtomicPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: params.entryDate,
|
||||
description: `Test ${params.sourceType}`,
|
||||
sourceType: params.sourceType,
|
||||
lines: lines.map((line) => ({
|
||||
accountNumber: line.account,
|
||||
debitAmount: line.debit,
|
||||
creditAmount: line.credit,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
describe('get_account_gl_lines_for_matching RPC: N:1 candidates', () => {
|
||||
|
||||
@@ -8,9 +8,13 @@
|
||||
* default p_account_number of '1930' keeps these assertions valid.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertCompany,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry as insertAtomicPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertPostedJournalEntry(params: {
|
||||
userId: string
|
||||
@@ -21,38 +25,26 @@ async function insertPostedJournalEntry(params: {
|
||||
voucherNumber: number
|
||||
amount?: number
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const amount = params.amount ?? 1000
|
||||
// Insert as posted directly. This bypasses commit_journal_entry's voucher
|
||||
// sequencing; that's fine for testing the read-side RPC, which only cares
|
||||
// about (account_number, status, source_type, date_range, link presence).
|
||||
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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', $6, $7, $8, 'posted')`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate,
|
||||
`Test ${params.sourceType}`,
|
||||
params.sourceType,
|
||||
],
|
||||
)
|
||||
// Balanced pair on 1930 + 2091 (balanserad vinst/förlust, the realistic
|
||||
// carried-forward counterpart for an IB on a bank account; harmless for the
|
||||
// other source_types where the test only cares about the 1930 side).
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, '1930', $2, 0),
|
||||
($1, '2091', 0, $2)`,
|
||||
[id, amount],
|
||||
)
|
||||
return id
|
||||
return insertAtomicPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: params.entryDate,
|
||||
description: `Test ${params.sourceType}`,
|
||||
sourceType: params.sourceType,
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: amount, creditAmount: 0 },
|
||||
{ accountNumber: '2091', debitAmount: 0, creditAmount: amount },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
describe('get_unlinked_gl_lines RPC: opening_balance exclusion', () => {
|
||||
|
||||
@@ -10,9 +10,11 @@
|
||||
* the reconciliation cron) untouched.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { seedCompany } from './fixtures'
|
||||
import {
|
||||
insertPostedJournalEntry as insertAtomicPostedJournalEntry,
|
||||
seedCompany,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertPostedJournalEntry(params: {
|
||||
userId: string
|
||||
@@ -22,23 +24,20 @@ async function insertPostedJournalEntry(params: {
|
||||
voucherNumber: number
|
||||
amount?: number
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const amount = params.amount ?? 1500
|
||||
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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', $6, 'Bank tx', 'bank_transaction', 'posted')`,
|
||||
[id, params.userId, params.companyId, params.fiscalPeriodId, params.voucherNumber, params.entryDate],
|
||||
)
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, '1930', $2, 0),
|
||||
($1, '2091', 0, $2)`,
|
||||
[id, amount],
|
||||
)
|
||||
return id
|
||||
return insertAtomicPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: params.entryDate,
|
||||
description: 'Bank tx',
|
||||
sourceType: 'bank_transaction',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: amount, creditAmount: 0 },
|
||||
{ accountNumber: '2091', debitAmount: 0, creditAmount: amount },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
const UNLINKED = `SELECT journal_entry_id FROM public.get_unlinked_gl_lines($1)`
|
||||
|
||||
@@ -78,35 +78,49 @@ async function insertJournalEntry(params: {
|
||||
lines: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const status = params.status ?? 'posted'
|
||||
const client = await getPool().connect()
|
||||
// Insert directly, bypassing commit_journal_entry's voucher sequencing:
|
||||
// fine for a read-side RPC that only aggregates line/account references.
|
||||
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, 'A', $6, 'KPI RPC test', $7, $8, $9, $10)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate ?? '2026-03-15',
|
||||
params.sourceType ?? 'manual',
|
||||
params.status ?? 'posted',
|
||||
params.reversesId ?? null,
|
||||
params.correctionOfId ?? null,
|
||||
],
|
||||
)
|
||||
for (const line of params.lines) {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[id, line.account, line.debit, line.credit],
|
||||
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, 'A', $6, 'KPI RPC test', $7, $8, $9, $10)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate ?? '2026-03-15',
|
||||
params.sourceType ?? 'manual',
|
||||
status,
|
||||
params.reversesId ?? null,
|
||||
params.correctionOfId ?? null,
|
||||
],
|
||||
)
|
||||
for (const line of params.lines) {
|
||||
await client.query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[id, line.account, line.debit, line.credit],
|
||||
)
|
||||
}
|
||||
if (status === 'posted') {
|
||||
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()
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
async function seedCompany() {
|
||||
@@ -165,6 +179,8 @@ async function seedFullScenario() {
|
||||
lines: [
|
||||
{ account: '8310', debit: 0, credit: 200 },
|
||||
{ account: '8410', debit: 500, credit: 0 },
|
||||
// Balance outside classes 3-8 so the monthly assertions stay focused.
|
||||
{ account: '2999', debit: 0, credit: 300 },
|
||||
],
|
||||
})
|
||||
|
||||
@@ -265,7 +281,11 @@ describe('get_kpi_report_aggregates RPC', () => {
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 2, sourceType: 'storno', entryDate: '2026-04-02',
|
||||
reversesId: plainReversed,
|
||||
lines: [{ account: '5010', debit: 0, credit: 100 }],
|
||||
lines: [
|
||||
{ account: '5010', debit: 0, credit: 100 },
|
||||
// Keep the posted storno balanced without changing the asserted P&L account.
|
||||
{ account: '2999', debit: 100, credit: 0 },
|
||||
],
|
||||
})
|
||||
|
||||
const payload = await callRpc(ctx.companyId, ctx.fiscalPeriodId)
|
||||
|
||||
@@ -14,21 +14,7 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool } from './setup'
|
||||
import { seedCompany, insertDraftJournalEntry } from './fixtures'
|
||||
|
||||
async function insertLines(
|
||||
journalEntryId: string,
|
||||
lines: Array<{ account: string; debit: number; credit: number }>,
|
||||
): Promise<void> {
|
||||
for (const line of lines) {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[journalEntryId, line.account, line.debit, line.credit],
|
||||
)
|
||||
}
|
||||
}
|
||||
import { seedCompany, insertPostedJournalEntry } from './fixtures'
|
||||
|
||||
async function bookMerchant(params: {
|
||||
userId: string
|
||||
@@ -46,19 +32,18 @@ async function bookMerchant(params: {
|
||||
/** transactions.exchange_rate: the rate recorded on the row. Null = none. */
|
||||
exchangeRate?: number | null
|
||||
}): Promise<void> {
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
const entryId = await insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
entryDate: params.date,
|
||||
status: 'posted',
|
||||
voucherNumber: params.voucherNumber,
|
||||
sourceType: 'bank_transaction',
|
||||
lines: [
|
||||
{ accountNumber: params.expenseAccount, debitAmount: params.amount, creditAmount: 0 },
|
||||
{ accountNumber: '1930', debitAmount: 0, creditAmount: params.amount },
|
||||
],
|
||||
})
|
||||
await insertLines(entryId, [
|
||||
{ account: params.expenseAccount, debit: params.amount, credit: 0 },
|
||||
{ account: '1930', debit: 0, credit: params.amount },
|
||||
])
|
||||
await getPool().query(
|
||||
`INSERT INTO public.transactions
|
||||
(id, company_id, user_id, currency, amount, amount_sek, exchange_rate,
|
||||
|
||||
@@ -16,6 +16,7 @@ import { getPool } from './setup'
|
||||
import {
|
||||
seedCompany,
|
||||
insertDraftJournalEntry,
|
||||
insertPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertLines(
|
||||
@@ -79,22 +80,21 @@ async function bookMerchant(params: {
|
||||
voucherNumber: number
|
||||
sourceType?: string
|
||||
}): Promise<string> {
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
const entryId = await insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
entryDate: params.date,
|
||||
status: 'posted',
|
||||
voucherNumber: params.voucherNumber,
|
||||
sourceType: params.sourceType ?? 'bank_transaction',
|
||||
// Booked 3 days after the transaction: exercises the committed_at-based
|
||||
// lag (entry_date == transaction date would give 0).
|
||||
committedAt: plusDays(params.date, 3),
|
||||
lines: [
|
||||
{ accountNumber: params.expenseAccount, debitAmount: 500, creditAmount: 0 },
|
||||
{ accountNumber: '1930', debitAmount: 0, creditAmount: 500 },
|
||||
],
|
||||
})
|
||||
await insertLines(entryId, [
|
||||
{ account: params.expenseAccount, debit: 500, credit: 0 },
|
||||
{ account: '1930', debit: 0, credit: 500 },
|
||||
])
|
||||
await insertBookedTransaction({
|
||||
companyId: params.companyId,
|
||||
userId: params.userId,
|
||||
@@ -274,15 +274,15 @@ describe('get_ledger_usage_stats', () => {
|
||||
{ account: '4010', debit: 300, credit: 0 },
|
||||
{ account: '1930', debit: 0, credit: 300 },
|
||||
])
|
||||
const stornoId = await insertDraftJournalEntry({
|
||||
const stornoId = await insertPostedJournalEntry({
|
||||
userId, companyId, fiscalPeriodId,
|
||||
entryDate: '2026-06-15', status: 'posted', voucherNumber: 9,
|
||||
entryDate: '2026-06-15', voucherNumber: 9,
|
||||
sourceType: 'storno',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 300, creditAmount: 0 },
|
||||
{ accountNumber: '4010', debitAmount: 0, creditAmount: 300 },
|
||||
],
|
||||
})
|
||||
await insertLines(stornoId, [
|
||||
{ account: '1930', debit: 300, credit: 0 },
|
||||
{ account: '4010', debit: 0, credit: 300 },
|
||||
])
|
||||
// Legacy shape: a transaction still linked to the storno entry (predates
|
||||
// reverseEntry() unlinking). Must not create a counterparty pattern.
|
||||
await insertBookedTransaction({
|
||||
@@ -313,18 +313,18 @@ describe('get_ledger_usage_stats', () => {
|
||||
// (regression for 20260708110000; observed on prod as 2614).
|
||||
let rcVoucher = 20
|
||||
for (const d of ['2026-05-20', '2026-06-18']) {
|
||||
const rcEntry = await insertDraftJournalEntry({
|
||||
const rcEntry = await insertPostedJournalEntry({
|
||||
userId, companyId, fiscalPeriodId,
|
||||
entryDate: d, status: 'posted',
|
||||
entryDate: d,
|
||||
voucherNumber: rcVoucher++, sourceType: 'bank_transaction',
|
||||
committedAt: plusDays(d, 3),
|
||||
lines: [
|
||||
{ accountNumber: '5420', debitAmount: 500, creditAmount: 0 },
|
||||
{ accountNumber: '2645', debitAmount: 125, creditAmount: 0 },
|
||||
{ accountNumber: '2614', debitAmount: 0, creditAmount: 125 },
|
||||
{ accountNumber: '1930', debitAmount: 0, creditAmount: 500 },
|
||||
],
|
||||
})
|
||||
await insertLines(rcEntry, [
|
||||
{ account: '5420', debit: 500, credit: 0 },
|
||||
{ account: '2645', debit: 125, credit: 0 },
|
||||
{ account: '2614', debit: 0, credit: 125 },
|
||||
{ account: '1930', debit: 0, credit: 500 },
|
||||
])
|
||||
await insertBookedTransaction({
|
||||
companyId, userId, journalEntryId: rcEntry,
|
||||
merchantName: 'GOOGLE WO', category: 'expense_software', date: d,
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { seedCompany } from './fixtures'
|
||||
import { insertPostedJournalEntry, seedCompany } from './fixtures'
|
||||
|
||||
let arrivalSeq = 0
|
||||
|
||||
@@ -79,33 +79,27 @@ async function seedPostedVoucher(params: {
|
||||
side: 'ar' | 'ap'
|
||||
amount?: number
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const amount = params.amount ?? 1000
|
||||
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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Betalning', 'manual', 'posted')`,
|
||||
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
|
||||
)
|
||||
if (params.side === 'ar') {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, '1930', $2, 0),
|
||||
($1, '1510', 0, $2)`,
|
||||
[id, amount],
|
||||
)
|
||||
} else {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, '2440', $2, 0),
|
||||
($1, '1930', 0, $2)`,
|
||||
[id, amount],
|
||||
)
|
||||
}
|
||||
return id
|
||||
const lines = params.side === 'ar'
|
||||
? [
|
||||
{ accountNumber: '1930', debitAmount: amount, creditAmount: 0 },
|
||||
{ accountNumber: '1510', debitAmount: 0, creditAmount: amount },
|
||||
]
|
||||
: [
|
||||
{ accountNumber: '2440', debitAmount: amount, creditAmount: 0 },
|
||||
{ accountNumber: '1930', debitAmount: 0, creditAmount: amount },
|
||||
]
|
||||
|
||||
return insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: Math.floor(Math.random() * 100000),
|
||||
entryDate: '2026-05-05',
|
||||
description: 'Betalning',
|
||||
sourceType: 'manual',
|
||||
lines,
|
||||
})
|
||||
}
|
||||
|
||||
const LINK_INVOICE = `SELECT public.link_invoice_to_voucher($1, $2, $3, $4, $5) AS result`
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertCompany,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
async function insertEntry(params: {
|
||||
userId: string
|
||||
@@ -11,31 +15,20 @@ async function insertEntry(params: {
|
||||
entryDate: string
|
||||
lines: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
const entryId = 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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', $6, 'Production regression test', 'manual', 'posted')`,
|
||||
[
|
||||
entryId,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate,
|
||||
],
|
||||
)
|
||||
|
||||
for (const line of params.lines) {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[entryId, line.account, line.debit, line.credit],
|
||||
)
|
||||
}
|
||||
return entryId
|
||||
return insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: params.entryDate,
|
||||
description: 'Production regression test',
|
||||
sourceType: 'manual',
|
||||
lines: params.lines.map((line) => ({
|
||||
accountNumber: line.account,
|
||||
debitAmount: line.debit,
|
||||
creditAmount: line.credit,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
async function seedCompany() {
|
||||
|
||||
@@ -20,7 +20,12 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertCompany,
|
||||
insertFiscalPeriod,
|
||||
insertPostedJournalEntry,
|
||||
} from './fixtures'
|
||||
|
||||
// Mirrors the TS call site (lib/reports/vat-declaration.ts): a small
|
||||
// representative slice of ACCOUNT_RUTA is enough since the full list is a
|
||||
@@ -28,6 +33,9 @@ import { insertAuthUser, insertCompany, insertFiscalPeriod } from './fixtures'
|
||||
const RUTA_ACCOUNTS = ['2611', '2621', '2641', '2645', '3001']
|
||||
const NET_ACCOUNTS = ['2650', '1650']
|
||||
const ALL_ACCOUNTS = [...RUTA_ACCOUNTS, ...NET_ACCOUNTS]
|
||||
// This account keeps intentionally narrow VAT fixtures balanced without
|
||||
// entering the account set asserted by this read-side RPC suite.
|
||||
const VAT_FIXTURE_BALANCING_ACCOUNT = '2999'
|
||||
|
||||
interface RpcPayload {
|
||||
totals: Array<{ account_number: string; debit: number; credit: number }>
|
||||
@@ -68,6 +76,23 @@ async function insertJournalEntry(params: {
|
||||
entryDate?: string
|
||||
lines: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
if ((params.status ?? 'posted') === 'posted') {
|
||||
return insertPostedJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
entryDate: params.entryDate ?? '2026-03-15',
|
||||
description: 'VAT RPC test',
|
||||
sourceType: params.sourceType ?? 'manual',
|
||||
lines: params.lines.map((line) => ({
|
||||
accountNumber: line.account,
|
||||
debitAmount: line.debit,
|
||||
creditAmount: line.credit,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
const id = randomUUID()
|
||||
// Insert directly, bypassing commit_journal_entry's voucher sequencing —
|
||||
// fine for a read-side RPC that only aggregates line/account references.
|
||||
@@ -151,11 +176,17 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
})
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 2, entryDate: '2025-12-31',
|
||||
lines: [{ account: '2611', debit: 0, credit: 777 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 777 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 777, credit: 0 },
|
||||
],
|
||||
})
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 3, entryDate: '2026-06-30',
|
||||
lines: [{ account: '2611', debit: 0, credit: 100 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 100 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 100, credit: 0 },
|
||||
],
|
||||
})
|
||||
|
||||
const payload = await callRpc(ctx.companyId, '2026-01-01', '2026-12-31')
|
||||
@@ -168,7 +199,10 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 1, sourceType: 'invoice_created',
|
||||
lines: [{ account: '2611', debit: 0, credit: 2500 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 2500 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 2500, credit: 0 },
|
||||
],
|
||||
})
|
||||
// The app's own settlement flow: tagged, filtered by source_type alone.
|
||||
await insertJournalEntry({
|
||||
@@ -198,6 +232,7 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
{ account: '2611', debit: 0, credit: 2500 },
|
||||
{ account: '2641', debit: 1000, credit: 0 },
|
||||
{ account: '3001', debit: 0, credit: 10000 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 11500, credit: 0 },
|
||||
],
|
||||
})
|
||||
// Manual settlement clearing the period to 2650, booked without the
|
||||
@@ -236,7 +271,10 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 1, sourceType: 'invoice_created',
|
||||
lines: [{ account: '2611', debit: 0, credit: 100 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 100 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 100, credit: 0 },
|
||||
],
|
||||
})
|
||||
// The tagged settlement itself is filtered by source_type; its storno
|
||||
// reversal is untagged and would otherwise re-credit 2611.
|
||||
@@ -281,7 +319,10 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
|
||||
await insertJournalEntry({
|
||||
...ctx, voucherNumber: 1, sourceType: 'invoice_created',
|
||||
lines: [{ account: '2611', debit: 0, credit: 100 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 100 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 100, credit: 0 },
|
||||
],
|
||||
})
|
||||
// Paying last period's VAT debt: 2650 against the bank account.
|
||||
await insertJournalEntry({
|
||||
@@ -305,11 +346,17 @@ describe('get_vat_declaration_totals RPC', () => {
|
||||
|
||||
await insertJournalEntry({
|
||||
...a, voucherNumber: 1,
|
||||
lines: [{ account: '2611', debit: 0, credit: 100 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 100 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 100, credit: 0 },
|
||||
],
|
||||
})
|
||||
await insertJournalEntry({
|
||||
...b, voucherNumber: 1,
|
||||
lines: [{ account: '2611', debit: 0, credit: 999 }],
|
||||
lines: [
|
||||
{ account: '2611', debit: 0, credit: 999 },
|
||||
{ account: VAT_FIXTURE_BALANCING_ACCOUNT, debit: 999, credit: 0 },
|
||||
],
|
||||
})
|
||||
|
||||
const payload = await callRpc(a.companyId)
|
||||
|
||||
@@ -76,34 +76,48 @@ async function insertEntry(params: {
|
||||
lines: Array<{ account: string; debit: number; credit: number }>
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
const status = params.status ?? 'posted'
|
||||
const client = await getPool().connect()
|
||||
// Inserted directly, bypassing commit_journal_entry's voucher sequencing:
|
||||
// this is a read-side aggregate that only reads lines and account numbers.
|
||||
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)
|
||||
VALUES ($1, $2, $3, $4, $5, 'A', $6, 'VAT closing-entry test', $7, $8, $9)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate,
|
||||
params.sourceType ?? 'manual',
|
||||
params.status ?? 'posted',
|
||||
params.reversesId ?? null,
|
||||
],
|
||||
)
|
||||
for (const line of params.lines) {
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[id, line.account, line.debit, line.credit],
|
||||
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', $6, 'VAT closing-entry test', $7, $8, $9)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
params.fiscalPeriodId,
|
||||
params.voucherNumber,
|
||||
params.entryDate,
|
||||
params.sourceType ?? 'manual',
|
||||
status,
|
||||
params.reversesId ?? null,
|
||||
],
|
||||
)
|
||||
for (const line of params.lines) {
|
||||
await client.query(
|
||||
`INSERT INTO public.journal_entry_lines
|
||||
(journal_entry_id, account_number, debit_amount, credit_amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[id, line.account, line.debit, line.credit],
|
||||
)
|
||||
}
|
||||
if (status === 'posted') {
|
||||
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()
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
seedCompany,
|
||||
insertAuthUser,
|
||||
insertDraftJournalEntry,
|
||||
insertPostedJournalEntry,
|
||||
insertBalancedLines,
|
||||
} from './fixtures'
|
||||
|
||||
@@ -84,30 +85,34 @@ describe('verifikat_without_documents RPC', () => {
|
||||
|
||||
// 6 posted entries without documents: amounts 100..600, dates ascending
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
const id = await insertDraftJournalEntry({
|
||||
const id = await insertPostedJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
status: 'posted',
|
||||
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 },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(id, i * 100)
|
||||
seeded.set(i, { id, amount: i * 100 })
|
||||
}
|
||||
|
||||
// Posted entry WITH a document: must never appear
|
||||
const withDoc = await insertDraftJournalEntry({
|
||||
const withDoc = await insertPostedJournalEntry({
|
||||
userId,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
status: 'posted',
|
||||
voucherNumber: 7,
|
||||
entryDate: '2026-06-07',
|
||||
description: 'has doc',
|
||||
lines: [
|
||||
{ accountNumber: '1930', debitAmount: 700, creditAmount: 0 },
|
||||
{ accountNumber: '3001', debitAmount: 0, creditAmount: 700 },
|
||||
],
|
||||
})
|
||||
await insertBalancedLines(withDoc, 700)
|
||||
await attachDocument({ userId, companyId, journalEntryId: withDoc })
|
||||
|
||||
// Draft entry: must never appear
|
||||
|
||||
Reference in New Issue
Block a user