f538401988
* 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>
276 lines
11 KiB
TypeScript
276 lines
11 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { createLogger } from '@/lib/logger'
|
|
import { roundOre } from '@/lib/money'
|
|
import type { JournalEntry } from '@/types'
|
|
|
|
const log = createLogger('payment-sync')
|
|
|
|
export const PAYMENT_SOURCE_TYPES = [
|
|
'invoice_paid',
|
|
'invoice_cash_payment',
|
|
'supplier_invoice_paid',
|
|
'supplier_invoice_cash_payment',
|
|
] as const
|
|
|
|
export function isPaymentSourceType(sourceType: string | null | undefined): boolean {
|
|
if (!sourceType) return false
|
|
return (PAYMENT_SOURCE_TYPES as readonly string[]).includes(sourceType)
|
|
}
|
|
|
|
/**
|
|
* Revert the business-level paid status on the invoice or supplier invoice
|
|
* that a payment journal entry was attached to. Used by both reverseEntry()
|
|
* (storno) and the DELETE journal entry route — both paths leave the GL in a
|
|
* consistent state but the invoice's status/paid_amount/paid_at would otherwise
|
|
* stay stuck on "paid".
|
|
*
|
|
* Safe to call with any entry — returns early if source_type is not a payment.
|
|
*/
|
|
export async function syncInvoiceStatusFromPaymentEntry(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
entry: Pick<JournalEntry, 'id' | 'source_type' | 'source_id'>
|
|
): Promise<void> {
|
|
if (!isPaymentSourceType(entry.source_type) || !entry.source_id) return
|
|
|
|
const entryId = entry.id
|
|
|
|
if (entry.source_type.startsWith('supplier_invoice')) {
|
|
// Scope to THIS invoice's payment row: a batch voucher (match_batch_allocate)
|
|
// carries one payment row per invoice under the same journal_entry_id, so an
|
|
// unfiltered .single() errors out on multi-row and silently yields null.
|
|
const { data: payment } = await supabase
|
|
.from('supplier_invoice_payments')
|
|
.select('amount')
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('supplier_invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
const { data: supplierInvoice } = await supabase
|
|
.from('supplier_invoices')
|
|
.select('paid_amount, total_amount, due_date')
|
|
.eq('id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (supplierInvoice) {
|
|
// Same fallback semantics as the customer branch below: a cash payment
|
|
// (supplier_invoice_cash_payment) books no payment row and is only ever
|
|
// a FULL payment, so reverting the whole paid_amount is correct. The
|
|
// old `&& payment` guard skipped the restore entirely for cash
|
|
// reversals, leaving the supplier invoice deadlocked on 'paid'.
|
|
const paymentAmount = payment?.amount ?? supplierInvoice.paid_amount
|
|
const newPaidAmount = roundOre(supplierInvoice.paid_amount - paymentAmount)
|
|
const newRemaining = roundOre(supplierInvoice.total_amount - Math.max(0, newPaidAmount))
|
|
let newStatus: string
|
|
if (newPaidAmount > 0) {
|
|
newStatus = 'partially_paid'
|
|
} else if (supplierInvoice.due_date && new Date(supplierInvoice.due_date) < new Date()) {
|
|
newStatus = 'overdue'
|
|
} else {
|
|
newStatus = 'approved'
|
|
}
|
|
|
|
await supabase
|
|
.from('supplier_invoices')
|
|
.update({
|
|
status: newStatus,
|
|
paid_amount: Math.max(0, newPaidAmount),
|
|
remaining_amount: newRemaining,
|
|
paid_at: null,
|
|
payment_journal_entry_id: null,
|
|
})
|
|
.eq('id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
}
|
|
|
|
// Remove THIS invoice's payment row tied to the reversed voucher so a
|
|
// re-match of the same bank line doesn't double-count or trip the unique
|
|
// index on supplier_invoice_payments. Scoped to the source invoice — a
|
|
// batch voucher carries sibling rows for other invoices whose status this
|
|
// call does not restore, so deleting them here would desync paid_amount
|
|
// from the payment rows (PR #666 review, SOC 2 CC6.3). Capture the linked
|
|
// transaction id first so the bank line can be released back to the inbox.
|
|
const { data: spRows } = await supabase
|
|
.from('supplier_invoice_payments')
|
|
.select('transaction_id')
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('supplier_invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
|
|
await supabase
|
|
.from('supplier_invoice_payments')
|
|
.delete()
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('supplier_invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
|
|
await releaseLinkedTransactions(
|
|
supabase,
|
|
companyId,
|
|
entryId,
|
|
(spRows ?? []).map((r) => (r as { transaction_id: string | null }).transaction_id),
|
|
'supplier_invoice_id',
|
|
)
|
|
} else {
|
|
// Scoped like the supplier branch: filter by invoice_id + company_id so a
|
|
// batch voucher's sibling payment rows don't break the .single().
|
|
const { data: payment } = await supabase
|
|
.from('invoice_payments')
|
|
.select('amount')
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
const { data: customerInvoice } = await supabase
|
|
.from('invoices')
|
|
.select('paid_amount, total, due_date')
|
|
.eq('id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (customerInvoice) {
|
|
// For a partial reversal we take the exact amount from the payment row.
|
|
// The fallback (full paid_amount) only applies when no payment row exists
|
|
// — true for invoice_cash_payment, which is only ever booked on a FULL
|
|
// payment, so reverting the whole paid_amount is correct there. Guarding
|
|
// this keeps a future partial-cash path from over-reverting.
|
|
const paymentAmount = payment?.amount ?? customerInvoice.paid_amount
|
|
const newPaidAmount = roundOre(customerInvoice.paid_amount - paymentAmount)
|
|
const safePaidAmount = Math.max(0, newPaidAmount)
|
|
// The supplier branch already resets remaining_amount; the customer branch
|
|
// never did, leaving it stale (= total) after a reversal so the invoice
|
|
// showed fully unpaid yet stuck on 'paid'. Recompute from total. (The
|
|
// .in('status', …) guard below can leave status/remaining un-updated if
|
|
// the invoice isn't paid/partially_paid — only reachable on a non-storno
|
|
// path; the payment-row delete + tx release still run, freeing the line.)
|
|
const newRemaining = roundOre(customerInvoice.total - safePaidAmount)
|
|
const revertStatus = newPaidAmount > 0
|
|
? 'partially_paid'
|
|
: customerInvoice.due_date && new Date(customerInvoice.due_date) < new Date()
|
|
? 'overdue'
|
|
: 'sent'
|
|
|
|
await supabase
|
|
.from('invoices')
|
|
.update({
|
|
status: revertStatus,
|
|
paid_at: null,
|
|
paid_amount: safePaidAmount,
|
|
remaining_amount: newRemaining,
|
|
})
|
|
.eq('id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
.in('status', ['paid', 'partially_paid'])
|
|
}
|
|
|
|
// Remove THIS invoice's payment row tied to the reversed voucher so a
|
|
// re-match of the same bank line doesn't trip the (transaction_id,
|
|
// invoice_id) / (journal_entry_id, invoice_id) unique indexes on
|
|
// invoice_payments. Scoped to the source invoice — see the supplier
|
|
// branch comment for the batch-voucher rationale.
|
|
const { data: ipRows } = await supabase
|
|
.from('invoice_payments')
|
|
.select('transaction_id')
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
|
|
await supabase
|
|
.from('invoice_payments')
|
|
.delete()
|
|
.eq('journal_entry_id', entryId)
|
|
.eq('invoice_id', entry.source_id)
|
|
.eq('company_id', companyId)
|
|
|
|
await releaseLinkedTransactions(
|
|
supabase,
|
|
companyId,
|
|
entryId,
|
|
(ipRows ?? []).map((r) => (r as { transaction_id: string | null }).transaction_id),
|
|
'invoice_id',
|
|
)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Detach any bank transactions still pointing at a reversed payment voucher so
|
|
* the bank line returns to the inbox and becomes re-matchable. Without this, a
|
|
* standalone storno (the reverse route / MCP reverse tool / delete-last-voucher)
|
|
* leaves transactions.journal_entry_id pointing at a reversed JE — the match
|
|
* POST refuses (invoice no longer matchable once we also fix its status) and the
|
|
* line can't be re-booked or deleted. The match-invoice route already clears the
|
|
* tx when IT stornos a conflicting auto-categorization JE; this covers every
|
|
* other reversal path.
|
|
*
|
|
* Clears by journal_entry_id (covers the link even when the payment row was
|
|
* missing) and by the captured payment-row transaction ids (covers a partial
|
|
* match that cleared journal_entry_id but left invoice_id/category set). Only
|
|
* the link/categorization columns are reset; the transaction row is preserved.
|
|
*/
|
|
async function releaseLinkedTransactions(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
entryId: string,
|
|
paymentTransactionIds: Array<string | null>,
|
|
invoiceColumn: 'invoice_id' | 'supplier_invoice_id',
|
|
): Promise<void> {
|
|
const resetFields = {
|
|
journal_entry_id: null,
|
|
[invoiceColumn]: null,
|
|
is_business: null,
|
|
category: null,
|
|
}
|
|
|
|
const { data: releasedByEntry, error: byEntryError } = await supabase
|
|
.from('transactions')
|
|
.update(resetFields)
|
|
.eq('company_id', companyId)
|
|
.eq('journal_entry_id', entryId)
|
|
.select('id')
|
|
if (byEntryError) {
|
|
// Best-effort like the rest of the sync — the storno itself already
|
|
// committed — but a failed release leaves the bank line stuck on a
|
|
// reversed JE, so it must be observable.
|
|
log.error('Failed to release transactions by journal_entry_id', byEntryError, {
|
|
companyId,
|
|
journalEntryId: entryId,
|
|
})
|
|
} else if (releasedByEntry && releasedByEntry.length > 0) {
|
|
// transactions has no write_audit_log trigger, so the clearing of the
|
|
// link/categorization columns is logged here for incident reconstruction.
|
|
log.info('Released bank transactions from reversed payment voucher', {
|
|
companyId,
|
|
journalEntryId: entryId,
|
|
invoiceColumn,
|
|
transactionIds: releasedByEntry.map((r) => (r as { id: string }).id),
|
|
})
|
|
}
|
|
|
|
const txIds = paymentTransactionIds.filter((id): id is string => !!id)
|
|
if (txIds.length > 0) {
|
|
const { data: releasedById, error: byIdError } = await supabase
|
|
.from('transactions')
|
|
.update(resetFields)
|
|
.eq('company_id', companyId)
|
|
.in('id', txIds)
|
|
.select('id')
|
|
if (byIdError) {
|
|
log.error('Failed to release transactions by payment transaction ids', byIdError, {
|
|
companyId,
|
|
journalEntryId: entryId,
|
|
transactionIds: txIds,
|
|
})
|
|
} else if (releasedById && releasedById.length > 0) {
|
|
log.info('Released payment-linked bank transactions from reversed voucher', {
|
|
companyId,
|
|
journalEntryId: entryId,
|
|
invoiceColumn,
|
|
transactionIds: releasedById.map((r) => (r as { id: string }).id),
|
|
})
|
|
}
|
|
}
|
|
}
|