Files
accounted/lib/bookkeeping/__tests__/payment-sync.test.ts
T
Jakob Wennberg f538401988 Invoice correctness bundle: voucher-link race, agent send guards, payment-reversal restore (audit C2/C17, F-2026080) (#666)
* 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>
2026-06-04 15:32:39 +02:00

368 lines
14 KiB
TypeScript

import { describe, expect, it, beforeEach, vi } from 'vitest'
import { isPaymentSourceType, syncInvoiceStatusFromPaymentEntry } from '@/lib/bookkeeping/payment-sync'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { JournalEntry } from '@/types'
/**
* A Supabase mock that records the table + method + args of every chained call
* (the shared createQueuedMockSupabase only records `from()` table names). Lets
* us assert on the actual UPDATE/DELETE payloads, which is what the reversal
* restore (remaining_amount reset, payment-row delete, tx release) hinges on.
*/
type RecordedCall = {
table: string
ops: Array<{ method: string; args: unknown[] }>
}
function createRecordingSupabase(queue: Array<{ data?: unknown; error?: unknown }>) {
const calls: RecordedCall[] = []
let i = 0
const from = vi.fn((table: string) => {
const result = queue[i++] ?? { data: null, error: null }
const rec: RecordedCall = { table, ops: [] }
calls.push(rec)
const chain: unknown = new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
return (...args: unknown[]) => {
rec.ops.push({ method: String(prop), args })
return chain
}
},
},
)
return chain
})
const updatePayload = (table: string): Record<string, unknown> | undefined => {
const rec = calls.find((c) => c.table === table && c.ops.some((o) => o.method === 'update'))
return rec?.ops.find((o) => o.method === 'update')?.args[0] as Record<string, unknown> | undefined
}
const tablesUpdated = (table: string) => calls.filter((c) => c.table === table && c.ops.some((o) => o.method === 'update'))
const wasDeleted = (table: string) => calls.some((c) => c.table === table && c.ops.some((o) => o.method === 'delete'))
return { supabase: { from } as never, calls, updatePayload, tablesUpdated, wasDeleted }
}
describe('isPaymentSourceType', () => {
it.each([
'invoice_paid',
'invoice_cash_payment',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
])('recognises %s as payment', (sourceType) => {
expect(isPaymentSourceType(sourceType)).toBe(true)
})
it.each(['manual', 'invoice_created', 'supplier_invoice_registered', '', null, undefined])(
'rejects %s',
(sourceType) => {
expect(isPaymentSourceType(sourceType)).toBe(false)
}
)
})
describe('syncInvoiceStatusFromPaymentEntry', () => {
beforeEach(() => {
vi.clearAllMocks()
})
function entry(overrides: Partial<JournalEntry> = {}): Pick<JournalEntry, 'id' | 'source_type' | 'source_id'> {
return {
id: 'entry-1',
source_type: 'supplier_invoice_paid',
source_id: 'supplier-invoice-1',
...overrides,
} as Pick<JournalEntry, 'id' | 'source_type' | 'source_id'>
}
it('is a no-op when source_type is not a payment', async () => {
const { supabase } = createQueuedMockSupabase()
await syncInvoiceStatusFromPaymentEntry(
supabase as never,
'co-1',
entry({ source_type: 'manual' as JournalEntry['source_type'] })
)
expect(supabase.from).not.toHaveBeenCalled()
})
it('is a no-op when source_id is missing', async () => {
const { supabase } = createQueuedMockSupabase()
await syncInvoiceStatusFromPaymentEntry(
supabase as never,
'co-1',
entry({ source_id: null })
)
expect(supabase.from).not.toHaveBeenCalled()
})
it('reverts a fully-paid supplier invoice back to approved', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: { amount: 1000 } },
// Fully paid before deletion: paid_amount === total_amount
{ data: { paid_amount: 1000, total_amount: 1000, due_date: '2099-12-31' } },
{ data: null }, // UPDATE result
])
await syncInvoiceStatusFromPaymentEntry(supabase as never, 'co-1', entry())
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
// After the status update the helper now also deletes the stale payment row
// and releases any linked bank transaction back to the inbox.
expect(fromCalls).toEqual([
'supplier_invoice_payments', // select amount
'supplier_invoices', // select
'supplier_invoices', // update status/paid/remaining
'supplier_invoice_payments', // select transaction_id
'supplier_invoice_payments', // delete payment row
'transactions', // release linked bank line
])
})
it('reverts a partially-paid supplier invoice to partially_paid when paid_amount remains', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: { amount: 500 } }, // payment being reversed
// Started with 1000 paid (multiple payments), reversing 500
{ data: { paid_amount: 1000, total_amount: 1500, due_date: '2099-12-31' } },
{ data: null },
])
await syncInvoiceStatusFromPaymentEntry(supabase as never, 'co-1', entry())
// select payment, select invoice, update invoice, select payment tx,
// delete payment row, release linked transaction.
expect((supabase.from as ReturnType<typeof vi.fn>).mock.calls.length).toBe(6)
})
it('routes customer invoice entries through the invoices table', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: { amount: 1000 } },
{ data: { paid_amount: 1000, due_date: '2099-12-31' } },
{ data: null },
])
await syncInvoiceStatusFromPaymentEntry(
supabase as never,
'co-1',
entry({ source_type: 'invoice_paid', source_id: 'invoice-1' })
)
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(fromCalls).toEqual([
'invoice_payments', // select amount
'invoices', // select
'invoices', // update status/paid/remaining
'invoice_payments', // select transaction_id
'invoice_payments', // delete payment row
'transactions', // release linked bank line
])
})
it('handles invoice_cash_payment the same way as invoice_paid', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: { amount: 500 } },
{ data: { paid_amount: 500, due_date: '2099-12-31' } },
{ data: null },
])
await syncInvoiceStatusFromPaymentEntry(
supabase as never,
'co-1',
entry({ source_type: 'invoice_cash_payment', source_id: 'invoice-1' })
)
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(fromCalls[0]).toBe('invoice_payments')
expect(fromCalls[1]).toBe('invoices')
})
it('handles supplier_invoice_cash_payment the same way as supplier_invoice_paid', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: { amount: 1000 } },
{ data: { paid_amount: 1000, total_amount: 1000, due_date: '2099-12-31' } },
{ data: null },
])
await syncInvoiceStatusFromPaymentEntry(
supabase as never,
'co-1',
entry({ source_type: 'supplier_invoice_cash_payment' })
)
const fromCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(fromCalls[0]).toBe('supplier_invoice_payments')
expect(fromCalls[1]).toBe('supplier_invoices')
})
it('does not error when no payment row exists for the supplier entry', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany([
{ data: null }, // no payment row
{ data: { paid_amount: 1000, total_amount: 1000, due_date: '2099-12-31' } },
])
await expect(
syncInvoiceStatusFromPaymentEntry(supabase as never, 'co-1', entry())
).resolves.toBeUndefined()
})
// Regression for the stuck-invoice deadlock (F-2026080): reversing a cash
// payment left the invoice at status='paid' / remaining_amount=total because
// the customer branch never reset remaining_amount. The cash path has no
// invoice_payments row, so the full paid_amount is reverted.
it('customer cash-payment reversal resets paid_amount, remaining_amount and status', async () => {
const { supabase, updatePayload, wasDeleted } = createRecordingSupabase([
{ data: null }, // invoice_payments select amount → none (cash entry)
{ data: { paid_amount: 5212.5, total: 5212.5, due_date: '2099-12-31' } }, // invoices select
{ data: null }, // invoices update
{ data: [] }, // invoice_payments select transaction_id
{ data: null }, // invoice_payments delete
{ data: null }, // transactions update
])
await syncInvoiceStatusFromPaymentEntry(
supabase,
'co-1',
entry({ source_type: 'invoice_cash_payment', source_id: 'invoice-1' }),
)
expect(updatePayload('invoices')).toEqual({
status: 'sent',
paid_at: null,
paid_amount: 0,
remaining_amount: 5212.5,
})
expect(wasDeleted('invoice_payments')).toBe(true)
})
// Partial reversal (clearing entry with a payment row): only the reversed
// amount comes off, remaining = total - newPaid, status stays partially_paid.
it('customer partial reversal keeps remaining_amount = total - newPaid', async () => {
const { supabase, updatePayload } = createRecordingSupabase([
{ data: { amount: 500 } }, // invoice_payments select amount
{ data: { paid_amount: 1500, total: 2000, due_date: '2099-12-31' } }, // invoices select
{ data: null }, // invoices update
{ data: [] }, // invoice_payments select transaction_id
{ data: null }, // invoice_payments delete
{ data: null }, // transactions update
])
await syncInvoiceStatusFromPaymentEntry(
supabase,
'co-1',
entry({ source_type: 'invoice_paid', source_id: 'invoice-1' }),
)
expect(updatePayload('invoices')).toEqual({
status: 'partially_paid',
paid_at: null,
paid_amount: 1000,
remaining_amount: 1000,
})
})
// The bank line that paid the (now reversed) voucher must be detached so it
// returns to the inbox and is re-matchable — cleared both by journal_entry_id
// and by the transaction id captured from the payment row.
it('releases the linked bank transaction (clears journal_entry_id, invoice_id, category)', async () => {
const { supabase, tablesUpdated } = createRecordingSupabase([
{ data: null }, // invoice_payments select amount
{ data: { paid_amount: 5212.5, total: 5212.5, due_date: '2099-12-31' } }, // invoices select
{ data: null }, // invoices update
{ data: [{ transaction_id: 'tx-9' }] }, // invoice_payments select transaction_id
{ data: null }, // invoice_payments delete
{ data: null }, // transactions update by journal_entry_id
{ data: null }, // transactions update by id
])
await syncInvoiceStatusFromPaymentEntry(
supabase,
'co-1',
entry({ source_type: 'invoice_cash_payment', source_id: 'invoice-1' }),
)
const txUpdates = tablesUpdated('transactions')
// Once by journal_entry_id, once by the captured payment transaction_id.
expect(txUpdates.length).toBe(2)
const resetPayload = txUpdates[0].ops.find((o) => o.method === 'update')?.args[0]
expect(resetPayload).toEqual({
journal_entry_id: null,
invoice_id: null,
is_business: null,
category: null,
})
// Second update targets the captured tx id.
const byId = txUpdates[1].ops.find((o) => o.method === 'in')
expect(byId?.args).toEqual(['id', ['tx-9']])
})
// Supplier-side parity: remaining_amount was already reset; now the payment
// row is deleted and the bank line released too.
it('supplier reversal deletes the payment row and releases the bank line', async () => {
const { supabase, updatePayload, wasDeleted, tablesUpdated } = createRecordingSupabase([
{ data: { amount: 1000 } }, // supplier_invoice_payments select amount
{ data: { paid_amount: 1000, total_amount: 1000, due_date: '2099-12-31' } }, // supplier_invoices select
{ data: null }, // supplier_invoices update
{ data: [{ transaction_id: 'tx-7' }] }, // supplier_invoice_payments select transaction_id
{ data: null }, // supplier_invoice_payments delete
{ data: null }, // transactions update by journal_entry_id
{ data: null }, // transactions update by id
])
await syncInvoiceStatusFromPaymentEntry(
supabase,
'co-1',
entry({ source_type: 'supplier_invoice_paid', source_id: 'supplier-invoice-1' }),
)
expect(updatePayload('supplier_invoices')).toMatchObject({
status: 'approved',
paid_amount: 0,
remaining_amount: 1000, // total_amount - 0 paid = full amount owed again
})
expect(wasDeleted('supplier_invoice_payments')).toBe(true)
const resetPayload = tablesUpdated('transactions')[0].ops.find((o) => o.method === 'update')?.args[0]
expect(resetPayload).toEqual({
journal_entry_id: null,
supplier_invoice_id: null,
is_business: null,
category: null,
})
})
// Regression for the Greptile finding on PR #666: the supplier branch
// required a payment row before restoring status/amounts, so reversing a
// supplier_invoice_cash_payment (which books NO payment row — cash entries
// are only ever full payments) deleted nothing visible but left the invoice
// permanently at status='paid' / remaining_amount=0 — the same deadlock the
// customer branch fix closed.
it('supplier cash-payment reversal restores status without a payment row', async () => {
const { supabase, updatePayload } = createRecordingSupabase([
{ data: null }, // supplier_invoice_payments select amount → none (cash entry)
{ data: { paid_amount: 1000, total_amount: 1000, due_date: '2099-12-31' } }, // supplier_invoices select
{ data: null }, // supplier_invoices update
{ data: [] }, // supplier_invoice_payments select transaction_id
{ data: null }, // supplier_invoice_payments delete
{ data: null }, // transactions update by journal_entry_id
])
await syncInvoiceStatusFromPaymentEntry(
supabase,
'co-1',
entry({ source_type: 'supplier_invoice_cash_payment', source_id: 'supplier-invoice-1' }),
)
expect(updatePayload('supplier_invoices')).toMatchObject({
status: 'approved',
paid_amount: 0,
remaining_amount: 1000,
paid_at: null,
payment_journal_entry_id: null,
})
})
})