* fix(invoices): atomic link_invoice_to_voucher RPC — close the customer voucher-link race (audit C2) linkInvoiceToVoucher() did UPDATE-then-INSERT with a manual rollback restoring a STALE pre-link snapshot: under concurrent linking on the same invoice, A's failed insert could overwrite B's successful link while B's payment row remained — corrupting paid_amount/AR. Mirrors the supplier-side link_supplier_invoice_to_voucher fix (PR #602). - New SECURITY DEFINER RPC locks the invoice FOR UPDATE, re-validates (status, posted voucher, 151x AR credit, currency, overshoot, already-linked) and applies UPDATE + INSERT in one PG transaction. Inherits the supplier RPC's remaining-amount fix (trust stored remaining_amount even at 0 — the TS '> 0' guard let rounding drift slip past FULLY_PAID). Hardened per audit A5: REVOKE from PUBLIC/anon, GRANT to authenticated + service_role. - linkInvoiceToVoucher() now delegates to the RPC — same signature, same LINK_VOUCHER_* codes, so all callers (route, pending-op executor, MCP) are unchanged. Keeps the invoice.paid event (now emitted with the post-link row, mirroring the supplier wrapper) and the best-effort bank auto-reconcile. - pg-real tests: full/partial link, overshoot leaves the invoice untouched, ALREADY_LINKED, and the race regression (two concurrent full links -> exactly one wins, paid_amount never exceeds total, exactly one payment row). Verified locally against supabase/postgres:15.8.1.060 with all 334 migrations replayed: 10/10 pass. Two unrelated pg tests fail locally with AND without this change (pre-existing env sensitivity; green in CI). - Unit tests re-mocked to the RPC-wrapper contract. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(invoices): agent send path — block cancelled invoices + preflight PDF render (audit C17) commitSendInvoice (the agent/MCP path) was missing two guards the send route has: - No cancelled guard: a cancelled invoice passed the already-sent check, got re-rendered and EMAILED (a 'MAKULERAD' PDF delivered as if live), and the unguarded status flip silently re-activated it to 'sent'. Now rejected with the registry's INVOICE_SEND_CANCELLED message (400), mirroring the route. - No preflight render: the executor assigned the F-series number BEFORE rendering, so a render failure left a numbered-but-never-issued invoice (an F-series gap if the draft is abandoned). Now mirrors the route: on fresh allocation, render with an 'F-PREVIEW' placeholder first and reject with INVOICE_SEND_PDF_RENDER_FAILED before any number is consumed; retries with an existing number skip the preflight. Items/credit-note lookup moved above the preflight (it needs them); the real render and everything downstream are unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): payment reversal restores invoice state and releases bank line (F-2026080) Reversing a payment voucher left the customer invoice deadlocked: status stayed 'paid' while remaining_amount stayed stale (= total), and the bank transaction kept pointing at the reversed JE so the line could neither be re-matched nor deleted. - Customer branch now recomputes remaining_amount from total (the supplier branch already did) and clamps paid_amount at 0. - Both branches delete the payment row(s) tied to the reversed voucher so a re-match doesn't double-count or trip the unique indexes. - New releaseLinkedTransactions() detaches bank transactions from the reversed JE (by journal_entry_id and by captured payment transaction ids), clearing the link/categorization columns so the line returns to the inbox. Covers every standalone storno path (reverse route, MCP reverse tool, delete-last-voucher); the match-invoice route already handled its own case. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(transactions): match-invoice preview double-subtracted VAT on per-item path (F-2026080) InvoiceItem.line_total is the NET line amount (it sums to invoice.subtotal, each line's vat_amount = line_total * rate), but the preview's per-item rate aggregation computed sub = line_total - vat_amount, double-subtracting VAT and producing an unbalanced previewed verifikat (revenue credit too low against the 1930 debit). The commit path (generatePerRateLines) was already correct; only the preview disagreed. Regression test mirrors the F-2026080 invoice: multi-item 25% SEK cash entry must balance, with 3001 = subtotal and 2611 = vat_amount. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): address PR #666 review — supplier cash reversal, RPC tenant guard, CI fixes Review feedback fixes: - Supplier cash-payment reversal (Greptile): the supplier branch required a payment row before restoring status/amounts, so reversing a supplier_invoice_cash_payment (which books no payment row) left the invoice deadlocked at paid/remaining=0 — the same bug the customer branch fixed. Mirror the customer fallback (revert full paid_amount when no row exists). - Payment-row lookups now filter by invoice id + company_id: a batch voucher (match_batch_allocate) carries one payment row per invoice under the same journal_entry_id, so the unfiltered .single() errored out and silently yielded null. - Tenant guard on the voucher-link write RPCs (compliance V8.2.1, audit A5): link_invoice_to_voucher and link_supplier_invoice_to_voucher are SECURITY DEFINER + authenticated-executable, so any signed-in user could mutate another tenant's invoices via PostgREST. New migration applies the PR #625 claims-based membership guard to both, caps p_notes at the Zod layer's 2000 chars, and gives the supplier RPC the explicit REVOKE/GRANT it never had (was default PUBLIC execute). Covered by a new pg-real test. - releaseLinkedTransactions now logs Supabase errors (compliance V16.1) — a failed release leaves a bank line stuck on a reversed JE and must be observable. CI fixes: - naive-ore-round ratchet (core-only): payment-sync.ts converted to roundOre() from @/lib/money (-4 occurrences vs baseline). - match-batch-allocate.pg.test.ts flake (pg-real): Date.now()+random arrival numbers collided in CI; now time-component + monotonic counter. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): address PR #666 review round 2 — payment attribution, batch-scoped deletes, send guard - RPC payment attribution (GDPR Art.32): user-session callers can no longer attribute invoice_payments / supplier_invoice_payments rows to an arbitrary user via p_user_id — the JWT sub is authoritative when role is anon/authenticated. service_role / direct callers keep p_user_id verbatim (their scoping happens in TS). pg-real test asserts the spoofed id is ignored. - Payment-row deletes scoped to the source invoice (SOC 2 CC6.3): a batch voucher carries sibling payment rows for other invoices whose status this sync doesn't restore; deleting them desynced paid_amount from the rows. - releaseLinkedTransactions success audit log: transactions has no write_audit_log trigger, so clearing the link/categorization columns now logs the affected transaction ids for incident reconstruction. - commitSendInvoice guard extended with partially_paid/credited (ASVS V2.3): both imply the invoice was already issued; the status flip would have regressed them to 'sent'. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
417 lines
18 KiB
TypeScript
417 lines
18 KiB
TypeScript
/**
|
|
* pg-real test for the link-invoice-voucher feature's DB-side guards.
|
|
*
|
|
* Covers what the TypeScript service can't verify on its own:
|
|
* - The partial unique index idx_invoice_payments_je_inv_unique blocks
|
|
* linking the same voucher to the same invoice twice while still
|
|
* allowing the voucher to settle other invoices.
|
|
* - The link_invoice_voucher operation_type passes the pending_operations
|
|
* CHECK constraint.
|
|
* - Invoice + invoice_payments writes survive RLS for the owning user and
|
|
* are rejected for a different user.
|
|
*
|
|
* Asserts behaviour the migration 20260528120000 introduced.
|
|
*/
|
|
import { describe, it, expect } from 'vitest'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { getPool } from '@/tests/pg/setup'
|
|
import {
|
|
insertAuthUser,
|
|
insertCompany,
|
|
insertCompanyMember,
|
|
insertFiscalPeriod,
|
|
} from '@/tests/pg/fixtures'
|
|
|
|
async function seedCustomer(params: {
|
|
userId: string
|
|
companyId: string
|
|
}): Promise<string> {
|
|
const id = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
|
|
VALUES ($1, $2, $3, 'Test Kund AB', 'swedish_business')`,
|
|
[id, params.userId, params.companyId],
|
|
)
|
|
return id
|
|
}
|
|
|
|
async function seedInvoice(params: {
|
|
userId: string
|
|
companyId: string
|
|
customerId: string
|
|
total?: number
|
|
status?: 'sent' | 'overdue' | 'partially_paid'
|
|
}): Promise<string> {
|
|
const id = randomUUID()
|
|
const total = params.total ?? 1000
|
|
await getPool().query(
|
|
`INSERT INTO public.invoices
|
|
(id, user_id, company_id, customer_id, invoice_number, invoice_date, due_date,
|
|
currency, subtotal, vat_amount, total, vat_treatment, vat_rate, status,
|
|
paid_amount, remaining_amount)
|
|
VALUES ($1, $2, $3, $4, $5, '2026-04-01', '2026-05-01', 'SEK',
|
|
$6, 0, $6, 'standard_25', 25, $7, 0, $6)`,
|
|
[id, params.userId, params.companyId, params.customerId, `F-${id.slice(0, 8)}`, total, params.status ?? 'sent'],
|
|
)
|
|
return id
|
|
}
|
|
|
|
async function seedPostedVoucher(params: {
|
|
userId: string
|
|
companyId: string
|
|
fiscalPeriodId: string
|
|
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', '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],
|
|
)
|
|
return id
|
|
}
|
|
|
|
describe('link_invoice_voucher pg-real guards', () => {
|
|
it('partial unique index blocks linking the same voucher to the same invoice twice', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
|
|
|
|
// First link — should succeed.
|
|
await getPool().query(
|
|
`INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
|
|
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
|
|
[userId, companyId, invoiceId, voucherId],
|
|
)
|
|
|
|
// Second identical link — should be rejected by the partial unique index.
|
|
await expect(
|
|
getPool().query(
|
|
`INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
|
|
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
|
|
[userId, companyId, invoiceId, voucherId],
|
|
),
|
|
).rejects.toMatchObject({ code: '23505' })
|
|
})
|
|
|
|
it('one voucher can be linked to multiple distinct invoices', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceAId = await seedInvoice({ userId, companyId, customerId, total: 500 })
|
|
const invoiceBId = await seedInvoice({ userId, companyId, customerId, total: 500 })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
|
|
|
|
await getPool().query(
|
|
`INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
|
|
VALUES ($1, $2, $3, '2026-05-05', 500, 'SEK', $4),
|
|
($1, $2, $5, '2026-05-05', 500, 'SEK', $4)`,
|
|
[userId, companyId, invoiceAId, voucherId, invoiceBId],
|
|
)
|
|
|
|
const { rows } = await getPool().query<{ count: string }>(
|
|
`SELECT COUNT(*) FROM public.invoice_payments WHERE journal_entry_id = $1`,
|
|
[voucherId],
|
|
)
|
|
expect(Number(rows[0].count)).toBe(2)
|
|
})
|
|
|
|
it('partial unique index does NOT collide when journal_entry_id is NULL', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId })
|
|
|
|
// Two transaction-keyed payment rows for the same invoice with NULL JE
|
|
// must coexist (until 2026-05-28 partial index, this would have been a
|
|
// false positive if the index were unconditional).
|
|
const txId1 = randomUUID()
|
|
const txId2 = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.transactions (id, user_id, company_id, account_id, date, description, amount, currency)
|
|
VALUES ($1, $2, $3, $4, '2026-05-05', 'Payment 1', 500, 'SEK'),
|
|
($5, $2, $3, $4, '2026-05-06', 'Payment 2', 500, 'SEK')`,
|
|
[txId1, userId, companyId, randomUUID(), txId2],
|
|
).catch(async () => {
|
|
// transactions table also requires account_id pointing at bank_connections;
|
|
// skip seeding txs if FK doesn't allow NULL — and assert against the
|
|
// invoice_payments table directly.
|
|
})
|
|
|
|
// Insert two rows with no journal_entry_id and no transaction_id — the
|
|
// partial index excludes them and the (transaction_id, invoice_id) unique
|
|
// index allows NULL transaction_id duplicates.
|
|
await getPool().query(
|
|
`INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency)
|
|
VALUES ($1, $2, $3, '2026-05-05', 500, 'SEK'),
|
|
($1, $2, $3, '2026-05-06', 500, 'SEK')`,
|
|
[userId, companyId, invoiceId],
|
|
)
|
|
|
|
const { rows } = await getPool().query<{ count: string }>(
|
|
`SELECT COUNT(*) FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(Number(rows[0].count)).toBe(2)
|
|
})
|
|
|
|
it('link_invoice_voucher passes the operation_type CHECK constraint', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
|
|
|
|
const opId = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.pending_operations
|
|
(id, user_id, company_id, operation_type, title, params, preview_data, status, risk_level)
|
|
VALUES ($1, $2, $3, 'link_invoice_voucher', 'test', $4::jsonb, $5::jsonb, 'pending', 'medium')`,
|
|
[
|
|
opId,
|
|
userId,
|
|
companyId,
|
|
JSON.stringify({ invoice_id: invoiceId, journal_entry_id: voucherId }),
|
|
JSON.stringify({ voucher_label: 'A-1' }),
|
|
],
|
|
)
|
|
|
|
const { rows } = await getPool().query<{ status: string }>(
|
|
`SELECT status FROM public.pending_operations WHERE id = $1`,
|
|
[opId],
|
|
)
|
|
expect(rows[0]?.status).toBe('pending')
|
|
})
|
|
|
|
it('linking a voucher whose period is locked does NOT trigger enforce_period_lock', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
// Period must be open while we seed the voucher — enforce_period_lock
|
|
// fires on INSERT, so close it only after the JE rows exist.
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId })
|
|
|
|
await getPool().query(
|
|
`UPDATE public.fiscal_periods
|
|
SET is_closed = true, closed_at = now()
|
|
WHERE id = $1`,
|
|
[fiscalPeriodId],
|
|
)
|
|
|
|
// No journal_entries write happens in the link flow — only
|
|
// invoice_payments + invoices, neither of which is gated by
|
|
// enforce_period_lock. The insert below must succeed even though the
|
|
// voucher's fiscal period is closed.
|
|
await getPool().query(
|
|
`INSERT INTO public.invoice_payments
|
|
(user_id, company_id, invoice_id, payment_date, amount, currency, journal_entry_id)
|
|
VALUES ($1, $2, $3, '2026-05-05', 1000, 'SEK', $4)`,
|
|
[userId, companyId, invoiceId, voucherId],
|
|
)
|
|
|
|
const { rows } = await getPool().query<{ count: string }>(
|
|
`SELECT COUNT(*) FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(Number(rows[0].count)).toBe(1)
|
|
})
|
|
})
|
|
|
|
// ============================================================
|
|
// link_invoice_to_voucher RPC — atomic customer link (audit C2)
|
|
// Mirrors the supplier-side link_supplier_invoice_to_voucher tests: the RPC
|
|
// must lock the invoice FOR UPDATE, validate, and apply UPDATE + INSERT in a
|
|
// single transaction so concurrent linkers serialize instead of clobbering
|
|
// each other (the old TS path's stale-snapshot manual rollback).
|
|
// ============================================================
|
|
|
|
type RpcResult = {
|
|
ok: boolean
|
|
code?: string
|
|
invoice_status?: string
|
|
paid_amount?: number
|
|
remaining_amount?: number
|
|
payment_amount?: number
|
|
details?: Record<string, unknown>
|
|
}
|
|
|
|
async function callLinkRpc(args: {
|
|
invoiceId: string
|
|
voucherId: string
|
|
userId: string
|
|
companyId: string
|
|
}): Promise<RpcResult> {
|
|
const { rows } = await getPool().query<{ result: RpcResult }>(
|
|
`SELECT public.link_invoice_to_voucher($1, $2, $3, $4, NULL) AS result`,
|
|
[args.invoiceId, args.voucherId, args.userId, args.companyId],
|
|
)
|
|
return rows[0].result
|
|
}
|
|
|
|
describe('link_invoice_to_voucher RPC (atomic link — audit C2)', () => {
|
|
it('links a full payment: invoice advanced + payment row, one transaction', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId, total: 1000 })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
|
|
|
|
const result = await callLinkRpc({ invoiceId, voucherId, userId, companyId })
|
|
expect(result.ok).toBe(true)
|
|
expect(result.invoice_status).toBe('paid')
|
|
expect(Number(result.paid_amount)).toBe(1000)
|
|
expect(Number(result.remaining_amount)).toBe(0)
|
|
|
|
const { rows: inv } = await getPool().query(
|
|
`SELECT status, paid_amount, remaining_amount FROM public.invoices WHERE id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(inv[0].status).toBe('paid')
|
|
expect(Number(inv[0].paid_amount)).toBe(1000)
|
|
expect(Number(inv[0].remaining_amount)).toBe(0)
|
|
|
|
const { rows: pay } = await getPool().query(
|
|
`SELECT amount FROM public.invoice_payments WHERE invoice_id = $1 AND journal_entry_id = $2`,
|
|
[invoiceId, voucherId],
|
|
)
|
|
expect(pay).toHaveLength(1)
|
|
expect(Number(pay[0].amount)).toBe(1000)
|
|
})
|
|
|
|
it('links a partial payment as partially_paid with the right remaining', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId, total: 1000 })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 400 })
|
|
|
|
const result = await callLinkRpc({ invoiceId, voucherId, userId, companyId })
|
|
expect(result.ok).toBe(true)
|
|
expect(result.invoice_status).toBe('partially_paid')
|
|
expect(Number(result.paid_amount)).toBe(400)
|
|
expect(Number(result.remaining_amount)).toBe(600)
|
|
})
|
|
|
|
it('rejects overpayment and leaves the invoice completely untouched', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId, total: 1000 })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1500 })
|
|
|
|
const result = await callLinkRpc({ invoiceId, voucherId, userId, companyId })
|
|
expect(result.ok).toBe(false)
|
|
expect(result.code).toBe('LINK_VOUCHER_AMOUNT_EXCEEDS_REMAINING')
|
|
|
|
const { rows: inv } = await getPool().query(
|
|
`SELECT status, paid_amount, remaining_amount FROM public.invoices WHERE id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(inv[0].status).toBe('sent')
|
|
expect(Number(inv[0].paid_amount)).toBe(0)
|
|
expect(Number(inv[0].remaining_amount)).toBe(1000)
|
|
|
|
const { rows: pay } = await getPool().query(
|
|
`SELECT COUNT(*) AS count FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(Number(pay[0].count)).toBe(0)
|
|
})
|
|
|
|
it('rejects re-linking the same voucher to the same invoice (ALREADY_LINKED)', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId, total: 2000 })
|
|
const voucherId = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
|
|
|
|
const first = await callLinkRpc({ invoiceId, voucherId, userId, companyId })
|
|
expect(first.ok).toBe(true)
|
|
|
|
const second = await callLinkRpc({ invoiceId, voucherId, userId, companyId })
|
|
expect(second.ok).toBe(false)
|
|
expect(second.code).toBe('LINK_VOUCHER_ALREADY_LINKED')
|
|
|
|
const { rows: pay } = await getPool().query(
|
|
`SELECT COUNT(*) AS count FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(Number(pay[0].count)).toBe(1)
|
|
})
|
|
|
|
it('REGRESSION (the C2 race): two concurrent full-payment links — exactly one wins', async () => {
|
|
const userId = await insertAuthUser()
|
|
const companyId = await insertCompany({ createdBy: userId })
|
|
await insertCompanyMember({ companyId, userId })
|
|
const fiscalPeriodId = await insertFiscalPeriod({ userId, companyId })
|
|
const customerId = await seedCustomer({ userId, companyId })
|
|
const invoiceId = await seedInvoice({ userId, companyId, customerId, total: 1000 })
|
|
const voucherA = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
|
|
const voucherB = await seedPostedVoucher({ userId, companyId, fiscalPeriodId, amount: 1000 })
|
|
|
|
// Two different vouchers, each covering the full remaining, racing on the
|
|
// same invoice from separate pool connections. The FOR UPDATE lock must
|
|
// serialize them: the loser sees remaining = 0 and gets FULLY_PAID. Under
|
|
// the old TS path both could pass validation and the invoice ended up
|
|
// with paid_amount > total (the audit C2 corruption).
|
|
const [r1, r2] = await Promise.all([
|
|
callLinkRpc({ invoiceId, voucherId: voucherA, userId, companyId }),
|
|
callLinkRpc({ invoiceId, voucherId: voucherB, userId, companyId }),
|
|
])
|
|
|
|
const winners = [r1, r2].filter((r) => r.ok)
|
|
const losers = [r1, r2].filter((r) => !r.ok)
|
|
expect(winners).toHaveLength(1)
|
|
expect(losers).toHaveLength(1)
|
|
expect(losers[0].code).toBe('LINK_VOUCHER_INVOICE_FULLY_PAID')
|
|
|
|
const { rows: inv } = await getPool().query(
|
|
`SELECT status, paid_amount, remaining_amount FROM public.invoices WHERE id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(inv[0].status).toBe('paid')
|
|
expect(Number(inv[0].paid_amount)).toBe(1000) // never 2000
|
|
expect(Number(inv[0].remaining_amount)).toBe(0)
|
|
|
|
const { rows: pay } = await getPool().query(
|
|
`SELECT COUNT(*) AS count FROM public.invoice_payments WHERE invoice_id = $1`,
|
|
[invoiceId],
|
|
)
|
|
expect(Number(pay[0].count)).toBe(1)
|
|
})
|
|
})
|