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
+81 -3
View File
@@ -7,6 +7,84 @@ import {
} from '@/tests/pg/fixtures'
describe('engine.pg: triggers & RPCs that mocks cannot catch', () => {
it('rejects a directly inserted posted journal entry with no lines', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
await expect(
getPool().query(
`INSERT INTO public.journal_entries
(user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, 1, 'A', '2026-06-01', 'Direct posted insert', 'manual', 'posted')`,
[userId, companyId, fiscalPeriodId],
),
).rejects.toThrow(/has zero total/i)
})
it('rejects an unbalanced directly inserted posted journal entry at constraint time', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const client = await getPool().connect()
try {
await client.query('BEGIN')
const inserted = await client.query<{ id: string }>(
`INSERT INTO public.journal_entries
(user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, 1, 'A', '2026-06-01', 'Direct posted insert', 'manual', 'posted')
RETURNING id`,
[userId, companyId, fiscalPeriodId],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 100, 0)`,
[inserted.rows[0]!.id],
)
await expect(
client.query('SET CONSTRAINTS check_balance_on_posted_insert IMMEDIATE'),
).rejects.toThrow(/not balanced/i)
} finally {
await client.query('ROLLBACK').catch(() => {})
client.release()
}
})
it('allows balanced lines to follow a posted header in the same transaction', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const client = await getPool().connect()
try {
await client.query('BEGIN')
const inserted = await client.query<{ id: string }>(
`INSERT INTO public.journal_entries
(user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, 1, 'A', '2026-06-01', 'Direct posted insert', 'manual', 'posted')
RETURNING id`,
[userId, companyId, fiscalPeriodId],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 100, 0),
($1, '3001', 0, 100)`,
[inserted.rows[0]!.id],
)
await client.query('SET CONSTRAINTS check_balance_on_posted_insert IMMEDIATE')
const persisted = await client.query<{ status: string }>(
`SELECT status FROM public.journal_entries WHERE id = $1`,
[inserted.rows[0]!.id],
)
expect(persisted.rows[0]!.status).toBe('posted')
} finally {
await client.query('ROLLBACK').catch(() => {})
client.release()
}
})
it('rejects INSERT into journal_entries when the fiscal period is closed', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany({ isClosed: true })
@@ -51,9 +129,9 @@ describe('engine.pg: triggers & RPCs that mocks cannot catch', () => {
it('rejects UPDATE to a posted journal entry (committed immutability)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
// Bypass commit_journal_entry by inserting directly as 'posted'. The
// immutability trigger fires on UPDATE, not INSERT, so this is legal
// setup on the superuser connection.
// Bypass commit_journal_entry with the direct-posted fixture. It inserts
// balanced lines in the same transaction so the deferred insert balance
// trigger accepts the setup before immutability is exercised below.
const entryId = await insertDraftJournalEntry({
userId,
companyId,
@@ -52,50 +52,60 @@ async function seedOpeningBalance(params: {
expect(accountIds.get('2010')).toBeTruthy()
const oldEntryId = randomUUID()
const voucher = await getPool().query<{ next_number: number }>(
`SELECT COALESCE(max(voucher_number), 0)::int + 1 AS next_number
FROM public.journal_entries
WHERE company_id = $1
AND fiscal_period_id = $2
AND voucher_series = 'A'`,
[params.companyId, params.fiscalPeriodId],
)
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-01-01',
'Old opening balance', 'opening_balance', 'posted')`,
[
oldEntryId,
params.userId,
params.companyId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, account_id, debit_amount,
credit_amount, currency, dimensions, sort_order)
VALUES
($1, '1930', $2, $4, 0, 'SEK', '{}'::jsonb, 0),
($1, '2010', $3, 0, $4, 'SEK', '{}'::jsonb, 1)`,
[oldEntryId, accountIds.get('1930'), accountIds.get('2010'), amount],
)
await getPool().query(
`INSERT INTO public.voucher_sequences
(company_id, user_id, fiscal_period_id, voucher_series, last_number)
VALUES ($1, $2, $3, 'A', $4)
ON CONFLICT (company_id, fiscal_period_id, voucher_series)
DO UPDATE SET last_number = GREATEST(public.voucher_sequences.last_number, $4)`,
[
params.companyId,
params.userId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
const client = await getClient()
try {
await client.query('BEGIN')
const voucher = await client.query<{ next_number: number }>(
`SELECT COALESCE(max(voucher_number), 0)::int + 1 AS next_number
FROM public.journal_entries
WHERE company_id = $1
AND fiscal_period_id = $2
AND voucher_series = 'A'`,
[params.companyId, params.fiscalPeriodId],
)
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)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-01-01',
'Old opening balance', 'opening_balance', 'posted')`,
[
oldEntryId,
params.userId,
params.companyId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, account_id, debit_amount,
credit_amount, currency, dimensions, sort_order)
VALUES
($1, '1930', $2, $4, 0, 'SEK', '{}'::jsonb, 0),
($1, '2010', $3, 0, $4, 'SEK', '{}'::jsonb, 1)`,
[oldEntryId, accountIds.get('1930'), accountIds.get('2010'), amount],
)
await client.query(
`INSERT INTO public.voucher_sequences
(company_id, user_id, fiscal_period_id, voucher_series, last_number)
VALUES ($1, $2, $3, 'A', $4)
ON CONFLICT (company_id, fiscal_period_id, voucher_series)
DO UPDATE SET last_number = GREATEST(public.voucher_sequences.last_number, $4)`,
[
params.companyId,
params.userId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
if (params.link !== false) {
await getPool().query(
`UPDATE public.fiscal_periods
@@ -36,63 +36,73 @@ async function insertPostedEntry(params: {
reversesId?: string | null
}): Promise<string> {
const id = randomUUID()
const voucher = await getPool().query<{ next_number: number }>(
`SELECT COALESCE(MAX(voucher_number), 0) + 1 AS next_number
FROM public.journal_entries
WHERE company_id = $1
AND fiscal_period_id = $2
AND voucher_series = 'A'`,
[params.companyId, params.fiscalPeriodId],
)
const client = await getClient()
try {
await client.query('BEGIN')
const voucher = await client.query<{ next_number: number }>(
`SELECT COALESCE(MAX(voucher_number), 0) + 1 AS next_number
FROM public.journal_entries
WHERE company_id = $1
AND fiscal_period_id = $2
AND voucher_series = 'A'`,
[params.companyId, params.fiscalPeriodId],
)
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, $7, $8, 'posted', $9)`,
[
id,
params.userId,
params.companyId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
params.entryDate,
params.description,
params.sourceType,
params.reversesId ?? null,
],
)
await getPool().query(
`INSERT INTO public.voucher_sequences
(company_id, user_id, fiscal_period_id, voucher_series, last_number)
VALUES ($1, $2, $3, 'A', $4)
ON CONFLICT (company_id, fiscal_period_id, voucher_series)
DO UPDATE SET last_number = GREATEST(
public.voucher_sequences.last_number,
EXCLUDED.last_number
)`,
[
params.companyId,
params.userId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
for (const line of params.lines) {
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, line_description)
VALUES ($1, $2, $3, $4, $5)`,
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, $7, $8, 'posted', $9)`,
[
id,
line.account_number,
line.debit_amount,
line.credit_amount,
line.line_description ?? null,
params.userId,
params.companyId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
params.entryDate,
params.description,
params.sourceType,
params.reversesId ?? null,
],
)
await client.query(
`INSERT INTO public.voucher_sequences
(company_id, user_id, fiscal_period_id, voucher_series, last_number)
VALUES ($1, $2, $3, 'A', $4)
ON CONFLICT (company_id, fiscal_period_id, voucher_series)
DO UPDATE SET last_number = GREATEST(
public.voucher_sequences.last_number,
EXCLUDED.last_number
)`,
[
params.companyId,
params.userId,
params.fiscalPeriodId,
voucher.rows[0]!.next_number,
],
)
for (const line of params.lines) {
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, line_description)
VALUES ($1, $2, $3, $4, $5)`,
[
id,
line.account_number,
line.debit_amount,
line.credit_amount,
line.line_description ?? null,
],
)
}
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
return id
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, runAsServiceRole, withUserContext } from '@/tests/pg/setup'
import { getClient, getPool, runAsServiceRole, withUserContext } from '@/tests/pg/setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from '@/tests/pg/fixtures'
// Covers the Fortnox re-sync flow:
@@ -72,29 +72,39 @@ async function insertPostedEntry(params: {
entryDate?: 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)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'Test entry', $8, 'posted')`,
[
id,
params.userId,
params.companyId,
params.fiscalPeriodId,
params.voucherNumber,
params.voucherSeries ?? 'A',
params.entryDate ?? '2026-06-01',
params.sourceType,
],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 100, 0),
($1, '3001', 0, 100)`,
[id],
)
const client = await getClient()
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)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'Test entry', $8, 'posted')`,
[
id,
params.userId,
params.companyId,
params.fiscalPeriodId,
params.voucherNumber,
params.voucherSeries ?? 'A',
params.entryDate ?? '2026-06-01',
params.sourceType,
],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, '1930', 100, 0),
($1, '3001', 0, 100)`,
[id],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
return id
}
@@ -21,7 +21,7 @@
*/
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from '@/tests/pg/setup'
import { getClient, getPool } from '@/tests/pg/setup'
import {
insertAuthUser,
insertCompany,
@@ -137,27 +137,37 @@ async function seedVoucher(params: {
amountInCurrency?: number | null
}): 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', '2026-05-05', 'Betalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, nextSeq() % 2_000_000_000],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, currency, amount_in_currency)
VALUES ($1, $2, $3, 0, $5, $6),
($1, $4, 0, $3, $5, $6)`,
[
id,
params.debitAccount,
params.sekAmount,
params.creditAccount,
params.lineCurrency ?? 'SEK',
params.amountInCurrency ?? null,
],
)
const client = await getClient()
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)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Betalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, nextSeq() % 2_000_000_000],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, currency, amount_in_currency)
VALUES ($1, $2, $3, 0, $5, $6),
($1, $4, 0, $3, $5, $6)`,
[
id,
params.debitAccount,
params.sekAmount,
params.creditAccount,
params.lineCurrency ?? 'SEK',
params.amountInCurrency ?? null,
],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
return id
}
@@ -562,21 +572,31 @@ describe('link_supplier_invoice_to_voucher: amount resolved in the invoice curre
total: 1000,
})
const voucherId = 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', '2026-05-05', 'Betalning', 'manual', 'posted')`,
[voucherId, userId, companyId, fiscalPeriodId, nextSeq() % 2_000_000_000],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, currency, amount_in_currency)
VALUES ($1, '2440', 6900, 0, 'EUR', 600),
($1, '2441', 4600, 0, 'EUR', 400),
($1, '1930', 0, 11500, 'EUR', 1000)`,
[voucherId],
)
const client = await getClient()
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)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Betalning', 'manual', 'posted')`,
[voucherId, userId, companyId, fiscalPeriodId, nextSeq() % 2_000_000_000],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, currency, amount_in_currency)
VALUES ($1, '2440', 6900, 0, 'EUR', 600),
($1, '2441', 4600, 0, 'EUR', 400),
($1, '1930', 0, 11500, 'EUR', 1000)`,
[voucherId],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
const result = await callLinkSupplierInvoice({
supplierInvoiceId,
@@ -14,7 +14,7 @@
*/
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from '@/tests/pg/setup'
import { getClient, getPool } from '@/tests/pg/setup'
import {
insertAuthUser,
insertCompany,
@@ -64,20 +64,30 @@ async function seedPostedVoucher(params: {
}): 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', 'Inbetalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
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],
)
const client = await getClient()
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)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Inbetalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
await client.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],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
return id
}
@@ -96,20 +106,30 @@ async function seedVoucherDebitCredit(params: {
}): 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', 'Inbetalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, $2, $3, 0),
($1, $4, 0, $3)`,
[id, params.debitAccount, amount, params.creditAccount],
)
const client = await getClient()
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)
VALUES ($1, $2, $3, $4, $5, 'A', '2026-05-05', 'Inbetalning', 'manual', 'posted')`,
[id, params.userId, params.companyId, params.fiscalPeriodId, Math.floor(Math.random() * 100000)],
)
await client.query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount)
VALUES ($1, $2, $3, 0),
($1, $4, 0, $3)`,
[id, params.debitAccount, amount, params.creditAccount],
)
await client.query('COMMIT')
} catch (error) {
await client.query('ROLLBACK').catch(() => {})
throw error
} finally {
client.release()
}
return id
}