fix(invoices): ROT/RUT kontantmetoden invoices could not be marked paid (#2040)

* fix(invoices): derive mark-paid amount as customer settlement, not gross debit sum

remaining_amount on a ROT/RUT invoice is stored net of the deduction
(total - deduction_total): the customer owes only their share, and
Skatteverket's share sits on 1513 until the payout flow clears it. The
kontantmetoden payment entry correctly books two debit legs (bank =
customer share, 1513 = deduction), but both mark-paid routes summed ALL
debit lines as the payment amount, so the gross total was compared
against the net remaining and every ROT/RUT cash invoice was rejected
with MATCH_AMOUNT_EXCEEDS_REMAINING by exactly deduction_total,
stalling the whole ROT chain (unpaid invoice never becomes a payout
candidate).

New deriveCustomerSettlementAmount in lib/invoices/apply-invoice-payment
excludes the net 1513 debit, capped at the invoice's own deduction (so
invoices without a deduction keep byte-identical behavior, including
rejecting a hand-added 1513 overshoot), and both the dashboard and v1
mark-paid routes use it. The verifikat still books the full entry
including the 1513 leg; only the settlement math changes.

Reported by a user unable to mark ROT invoice 1123 as paid.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uy5xt3nCKwL1vhRFPYjAjJ

* fix(invoices): harden ROT settlement derivation per skeptic refutations

Three fixes from adversarial review of the previous commit:

1. v1 mark-paid never fetched deduction_total (the pre-flight select
   projects explicit columns), so the exclusion cap was always 0 and the
   v1 API still failed with MATCH_AMOUNT_EXCEEDS_REMAINING. Fetch it ad
   hoc next to journal_entry_id (kept out of the response contract) and
   assert the projection in the route test, since the mock harness
   ignores select strings.

2. Gate the 1513 exclusion on the invoice NOT being booked yet, in both
   routes. An invoice booked at send already debited 1513 in its
   registration entry; ungated, a cash-shaped payment entry on such an
   invoice would post (orphaned 1510, doubled 1513, double revenue and
   VAT) where the gross guard used to reject it.

3. payment-sync's reversal recompute now stores remaining_amount net of
   deduction_total, matching build-invoice-write and the DB guard.
   Recomputing gross made a storno'd ROT cash invoice permanently
   un-payable under the net settlement derivation (net payment can never
   reach a gross remaining; the cash-partial block rejects the rest).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uy5xt3nCKwL1vhRFPYjAjJ

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-30 15:12:37 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 355723c566
commit e313bfa8ec
8 changed files with 497 additions and 23 deletions
@@ -239,6 +239,34 @@ describe('syncInvoiceStatusFromPaymentEntry', () => {
expect(wasDeleted('invoice_payments')).toBe(true)
})
// ROT/RUT: remaining_amount is the CUSTOMER share (total - deduction_total),
// as build-invoice-write stores it. Recomputing it gross on reversal used to
// inflate remaining to total, after which the net customer settlement could
// never reach it again and the invoice was permanently un-payable.
it('customer cash-payment reversal keeps remaining net of the ROT/RUT deduction', async () => {
const { supabase, updatePayload } = createRecordingSupabase([
{ data: null }, // invoice_payments select amount → none (cash entry)
{ data: { paid_amount: 86800, total: 124000, deduction_total: 37200, 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: 86800,
})
})
// 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 () => {
+17 -2
View File
@@ -152,7 +152,7 @@ export async function syncInvoiceStatusFromPaymentEntry(
const { data: customerInvoice } = await supabase
.from('invoices')
.select('paid_amount, total, due_date')
.select('paid_amount, total, due_date, deduction_total')
.eq('id', entry.source_id)
.eq('company_id', companyId)
.single()
@@ -172,7 +172,22 @@ export async function syncInvoiceStatusFromPaymentEntry(
// .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)
//
// remaining_amount is the CUSTOMER share: net of the ROT/RUT deduction,
// exactly as build-invoice-write stores it at creation (total -
// deduction_total) and as the invoices_remaining_amount_guard trigger
// derives it. Recomputing gross here inflated remaining on ROT/RUT
// invoices after a storno, which made them permanently un-settleable
// once mark-paid started comparing the net customer settlement against
// remaining (a net payment can never reach a gross remaining, and the
// cash-partial block rejects the "partial"). Mirrors rot-rut-file's
// derivation, which distrusted this very writer.
const deductionTotal =
(customerInvoice as { deduction_total?: number | null }).deduction_total ?? 0
const newRemaining = Math.max(
0,
roundOre(customerInvoice.total - deductionTotal - safePaidAmount),
)
const revertStatus = newPaidAmount > 0
? 'partially_paid'
: customerInvoice.due_date && new Date(customerInvoice.due_date) < new Date()