Files
accounted/lib/invoices/apply-invoice-payment.ts
T
Jakob WennbergandClaude Opus 4.8 5777f51940 Reject overpayment on all invoice-match paths (audit C3) (#647)
* fix(invoices): reject overpayment on all invoice-match paths (audit C3)

The paid/remaining math was copy-pasted across three sites; the dashboard match-invoice route guarded against overpayment but the v1 public API route and the agent/MCP commitMatchTransactionInvoice had drifted WITHOUT it — silently accepting payment > remaining (recording paid_amount > total, over-crediting AR; cleanup needs storno, not edit).

- New lib/invoices/apply-invoice-payment.ts planInvoicePayment(): single source of the paid/remaining/status math + overpayment guard, via canonical roundOre (@/lib/money, guard rail #9). FX-agnostic — caller passes the invoice-currency amount.
- All three sites delegate; the guard runs BEFORE journal-entry creation so a rejected match never burns a voucher number. Dashboard behaviour unchanged (faithful extraction — its existing overpayment test still passes, the equivalence anchor). v1 returns MATCH_AMOUNT_EXCEEDS_REMAINING; commit returns the same registry message at 400.
- Removes 7 hand-rolled Math.round(x*100)/100 sites; antipattern guard ratchets 668 -> 661.
- Unit tests for the helper (overpayment rejection, half-öre tolerance, remaining_amount fallback).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* review: run overpayment guard before the storno (PR #647)

greptile: in commit.ts and the v1 route the conflicting-JE storno ran BEFORE the new guard, so a rejected overpayment would still reverse the transaction's prior JE and null its journal_entry_id — a side effect on a rejected match. Move planInvoicePayment above the storno so a rejection leaves the transaction fully untouched. (The dashboard route's pre-existing storno-before-guard ordering is FX-entangled and unchanged here; noted as a follow-up.)

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-03 17:00:22 +02:00

84 lines
3.0 KiB
TypeScript

/**
* Single source of truth for applying a payment amount to a customer invoice.
*
* Computes the new paid/remaining/status and — critically — REJECTS overpayment
* before the caller creates any journal entry, so a doomed match never burns a
* voucher number.
*
* Background: this math was copy-pasted across three sites — the dashboard
* match-invoice route (which had the overpayment guard), the v1 public API
* route, and `commitMatchTransactionInvoice` (the agent/MCP path). The latter
* two had drifted WITHOUT the guard, so they silently swallowed overpayment via
* `Math.max(0, …)` — recording e.g. 1500 paid on a 1000 invoice and
* over-crediting accounts receivable. Centralizing the math + guard here closes
* that drift; all three sites delegate to `planInvoicePayment`.
*
* FX: `paymentAmountInInvoiceCurrency` MUST already be in the invoice's
* currency. The caller owns any conversion (cross-currency settlement lives in
* the dashboard route), keeping this helper FX-agnostic.
*
* Extracted from the proven dashboard route with the same half-öre overshoot
* tolerance. Rounding goes through the canonical `roundOre` (@/lib/money) per
* guard rail #9 — identical to the route's previous `Math.round(x*100)/100`
* except on exact-half-öre amounts, where `roundOre` rounds correctly.
*/
import { roundOre, ORE_TOLERANCE } from '@/lib/money'
/** Half an öre — anything over the remaining by more than this is a real overpayment. */
export const PAYMENT_OVERSHOOT_TOLERANCE = ORE_TOLERANCE
export interface InvoicePaymentTotals {
total: number
paid_amount?: number | null
remaining_amount?: number | null
}
export interface InvoicePaymentPlan {
newPaidAmount: number
newRemaining: number
isFullyPaid: boolean
newStatus: 'paid' | 'partially_paid'
}
export type PlanInvoicePaymentResult =
| { ok: true; plan: InvoicePaymentPlan }
| {
ok: false
code: 'MATCH_AMOUNT_EXCEEDS_REMAINING'
details: { transaction_amount: number; remaining_amount: number; excess: number }
}
export function planInvoicePayment(
invoice: InvoicePaymentTotals,
paymentAmountInInvoiceCurrency: number,
): PlanInvoicePaymentResult {
const currentRemaining =
invoice.remaining_amount ?? invoice.total - (invoice.paid_amount || 0)
if (paymentAmountInInvoiceCurrency > currentRemaining + PAYMENT_OVERSHOOT_TOLERANCE) {
return {
ok: false,
code: 'MATCH_AMOUNT_EXCEEDS_REMAINING',
details: {
transaction_amount: paymentAmountInInvoiceCurrency,
remaining_amount: roundOre(currentRemaining),
excess: roundOre(paymentAmountInInvoiceCurrency - currentRemaining),
},
}
}
const newPaidAmount = roundOre((invoice.paid_amount || 0) + paymentAmountInInvoiceCurrency)
const newRemaining = Math.max(0, roundOre(currentRemaining - paymentAmountInInvoiceCurrency))
const isFullyPaid = newRemaining <= 0
return {
ok: true,
plan: {
newPaidAmount,
newRemaining,
isFullyPaid,
newStatus: isFullyPaid ? 'paid' : 'partially_paid',
},
}
}