* 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>
389 lines
12 KiB
TypeScript
389 lines
12 KiB
TypeScript
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
|
import {
|
|
findMatchingVouchersForInvoice,
|
|
validateVoucherForInvoiceLink,
|
|
linkInvoiceToVoucher,
|
|
} from '../voucher-matching'
|
|
import {
|
|
makeInvoice,
|
|
createQueuedMockSupabase,
|
|
} from '@/tests/helpers'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
|
|
// ============================================================
|
|
// validateVoucherForInvoiceLink — happy path + reject codes
|
|
// ============================================================
|
|
|
|
describe('validateVoucherForInvoiceLink', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
function setup(invoice = makeInvoice({ remaining_amount: 1000, total: 1000, currency: 'SEK' })) {
|
|
return invoice
|
|
}
|
|
|
|
it('rejects when the invoice has nothing remaining', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup(
|
|
makeInvoice({ remaining_amount: 0, paid_amount: 1000, total: 1000, currency: 'SEK' }),
|
|
)
|
|
enqueue({ data: null }) // unused — we short-circuit before querying
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_INVOICE_FULLY_PAID')
|
|
})
|
|
|
|
it('rejects when the voucher is missing', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({ data: null, error: null }) // journal_entries.maybeSingle → null
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-missing',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_VOUCHER_NOT_FOUND')
|
|
})
|
|
|
|
it('rejects when the voucher is not posted', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'draft',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_NOT_POSTED')
|
|
})
|
|
|
|
it('rejects when the voucher has no AR credit', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1930', debit_amount: 1000, credit_amount: 0, currency: 'SEK' },
|
|
{ account_number: '3001', debit_amount: 0, credit_amount: 1000, currency: 'SEK' },
|
|
],
|
|
})
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_NO_AR_CREDIT')
|
|
})
|
|
|
|
it('rejects when the voucher amount exceeds the remaining', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1930', debit_amount: 5000, credit_amount: 0, currency: 'SEK' },
|
|
{ account_number: '1510', debit_amount: 0, credit_amount: 5000, currency: 'SEK' },
|
|
],
|
|
})
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_AMOUNT_EXCEEDS_REMAINING')
|
|
})
|
|
|
|
it('rejects when the line currency does not match the invoice', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup(makeInvoice({ remaining_amount: 1000, total: 1000, currency: 'EUR' }))
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1510', debit_amount: 0, credit_amount: 1000, currency: 'SEK' },
|
|
],
|
|
})
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_CURRENCY_MISMATCH')
|
|
})
|
|
|
|
it('rejects when the voucher is already linked to this invoice', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1510', debit_amount: 0, credit_amount: 1000, currency: 'SEK' },
|
|
],
|
|
})
|
|
enqueue({ data: [{ id: 'pmt-1' }] })
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_ALREADY_LINKED')
|
|
})
|
|
|
|
it('returns ok=true with full-pay flag when amount equals remaining', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup()
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1930', debit_amount: 1000, credit_amount: 0, currency: 'SEK' },
|
|
{ account_number: '1510', debit_amount: 0, credit_amount: 1000, currency: 'SEK' },
|
|
],
|
|
})
|
|
enqueue({ data: [] })
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(true)
|
|
if (result.ok) {
|
|
expect(result.arCreditAmount).toBe(1000)
|
|
expect(result.paymentAmount).toBe(1000)
|
|
expect(result.isFullyPaid).toBe(true)
|
|
expect(result.remainingAfter).toBe(0)
|
|
}
|
|
})
|
|
|
|
it('returns ok=true with partial-pay flag when amount is less than remaining', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = setup(makeInvoice({ remaining_amount: 1000, total: 1000, currency: 'SEK' }))
|
|
enqueue({
|
|
data: {
|
|
id: 'je-1',
|
|
voucher_series: 'A',
|
|
voucher_number: 5,
|
|
entry_date: '2026-05-01',
|
|
description: '',
|
|
status: 'posted',
|
|
source_type: 'manual',
|
|
fiscal_period_id: 'fp-1',
|
|
company_id: 'company-1',
|
|
},
|
|
})
|
|
enqueue({
|
|
data: [
|
|
{ account_number: '1510', debit_amount: 0, credit_amount: 400, currency: 'SEK' },
|
|
],
|
|
})
|
|
enqueue({ data: [] })
|
|
const result = await validateVoucherForInvoiceLink(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
'je-1',
|
|
)
|
|
expect(result.ok).toBe(true)
|
|
if (result.ok) {
|
|
expect(result.paymentAmount).toBe(400)
|
|
expect(result.isFullyPaid).toBe(false)
|
|
expect(result.remainingAfter).toBe(600)
|
|
}
|
|
})
|
|
})
|
|
|
|
// ============================================================
|
|
// findMatchingVouchersForInvoice — empty + ranking smoke test
|
|
// ============================================================
|
|
|
|
describe('findMatchingVouchersForInvoice', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
it('returns empty when the invoice has nothing remaining', async () => {
|
|
const { supabase } = createQueuedMockSupabase()
|
|
const invoice = makeInvoice({ remaining_amount: 0, paid_amount: 1000, total: 1000 })
|
|
const result = await findMatchingVouchersForInvoice(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
)
|
|
expect(result).toEqual([])
|
|
})
|
|
|
|
it('returns empty when the journal lines query errors', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
const invoice = makeInvoice({
|
|
remaining_amount: 1000,
|
|
total: 1000,
|
|
due_date: '2026-05-01',
|
|
})
|
|
enqueue({ data: null, error: { message: 'db error' } })
|
|
const result = await findMatchingVouchersForInvoice(
|
|
supabase as never,
|
|
'company-1',
|
|
invoice as never,
|
|
)
|
|
expect(result).toEqual([])
|
|
})
|
|
})
|
|
|
|
// ============================================================
|
|
// linkInvoiceToVoucher — outcome shape & event emission
|
|
// ============================================================
|
|
|
|
describe('linkInvoiceToVoucher', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
eventBus.clear()
|
|
})
|
|
|
|
// linkInvoiceToVoucher now delegates validation + writes to the atomic
|
|
// link_invoice_to_voucher RPC (audit C2) — the wrapper's job is calling it
|
|
// with the right args and mapping the jsonb result/transport errors through.
|
|
// Guard behaviour itself is covered by voucher-matching.pg.test.ts against
|
|
// the real RPC.
|
|
|
|
it('passes a guard rejection from the RPC through unchanged', async () => {
|
|
const rpc = vi.fn().mockResolvedValue({
|
|
data: { ok: false, code: 'LINK_VOUCHER_INVOICE_FULLY_PAID', details: { status: 'paid' } },
|
|
error: null,
|
|
})
|
|
const result = await linkInvoiceToVoucher(
|
|
{ rpc } as never,
|
|
'user-1',
|
|
'company-1',
|
|
{ invoiceId: 'inv-1', journalEntryId: 'je-1' },
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) {
|
|
expect(result.code).toBe('LINK_VOUCHER_INVOICE_FULLY_PAID')
|
|
expect(result.details).toEqual({ status: 'paid' })
|
|
}
|
|
expect(rpc).toHaveBeenCalledWith('link_invoice_to_voucher', {
|
|
p_invoice_id: 'inv-1',
|
|
p_journal_entry_id: 'je-1',
|
|
p_user_id: 'user-1',
|
|
p_company_id: 'company-1',
|
|
p_notes: null,
|
|
})
|
|
})
|
|
|
|
it('maps an RPC transport error to LINK_VOUCHER_DB_ERROR', async () => {
|
|
const rpc = vi.fn().mockResolvedValue({ data: null, error: { message: 'connection reset' } })
|
|
const result = await linkInvoiceToVoucher(
|
|
{ rpc } as never,
|
|
'user-1',
|
|
'company-1',
|
|
{ invoiceId: 'inv-1', journalEntryId: 'je-1' },
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) {
|
|
expect(result.code).toBe('LINK_VOUCHER_DB_ERROR')
|
|
expect(result.details).toEqual({ reason: 'connection reset' })
|
|
}
|
|
})
|
|
|
|
it('maps an empty RPC response to LINK_VOUCHER_DB_ERROR', async () => {
|
|
const rpc = vi.fn().mockResolvedValue({ data: null, error: null })
|
|
const result = await linkInvoiceToVoucher(
|
|
{ rpc } as never,
|
|
'user-1',
|
|
'company-1',
|
|
{ invoiceId: 'inv-1', journalEntryId: 'je-1' },
|
|
)
|
|
expect(result.ok).toBe(false)
|
|
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_DB_ERROR')
|
|
})
|
|
})
|