fix(invoices): bank match stores the applied amount, not cash received, in invoice_payments (#2277)
* fix(invoices): bank match stores the applied amount, not cash received, in invoice_payments The dashboard match-invoice route, its v1 twin and the pending-operation match_transaction_invoice executor wrote invoice_payments.amount as the cash received in invoice currency. When a whole-krona bank line settles an öre-carrying remaining (the customer pays the rounded "Att betala"), planInvoicePayment advances paid_amount by the remaining only and books the öre on 3740, so the row exceeded the receivable by the absorbed öre: remaining 999.60, bank 1 000.00 gave a 1 000.00 row against a 999.60 paid_amount. The kontantmetod cut-off then pushed a -0.40 receivable with negative scaled moms, the historical AR ledger showed -0.40 outstanding on a paid invoice, and a storno of the payment voucher restored paid_amount 0.40 off (issue #2250). PR #2236 defined the amount for the manual, MCP and Stripe paths as the amount APPLIED to the invoice (new paid_amount minus the prior one). The three bank-match paths now share that definition through one helper, appliedPaymentAmount() in lib/invoices/invoice-payment-row.ts, which recordInvoicePaymentRow() uses as well. Every other field of the row (payment date, currency, exchange rate, journal entry, bank transaction, notes) is unchanged. Without a residual the applied amount equals the cash received, so ordinary matches post identical rows; cross-currency rows are now öre-rounded like paid_amount instead of the 4-decimal spot conversion, so row and paid_amount agree. Existing rows carrying the overshoot are not repaired here; that is a separate call. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015qgLgdt4mLmha1ZLFMwq1u * refactor(invoices): one writer for invoice_payments rows Rework of the #2250 fix from first principles. The bank-match paths did not just get the amount wrong; the class of bug is that invoice_payments rows were hand-built at five product sites (dashboard bank match, its v1 twin, the pending-operation match, the link-to-existing-voucher flow, and the #2236 paths through the helper), each computing its own fields with no single definition of what the row means. recordInvoicePaymentRow() (lib/invoices/invoice-payment-row.ts) is now the one writer. Its options grew by what the bank paths set, all optional with today's defaults so the #2236 callers are unchanged: transactionId (default null), exchangeRate (the rate actually used; omitted = invoice.exchange_rate, explicit null stored as null) and notes (default null). The failure result carries the Postgres SQLSTATE so the routes keep mapping a unique violation (23505) exactly as before. The applied-amount formula is an internal detail of that file again. Routed through the writer: app/api/transactions/[id]/match-invoice, the v1 match-invoice twin, commitMatchTransactionInvoice in lib/pending-operations/commit.ts, and lib/transactions/link-journal-entry.ts (strict plan, same currency only: its amount is unchanged, it now shares the row semantics). The pending-operation path used to drop the insert error on the floor; it stays non-fatal but is logged with ids. Guard: scripts/checks/no-new-antipatterns.mjs gains direct-invoice-payment-insert, a file-set rule with no baseline (0 today): .from('invoice_payments').insert( or .upsert( anywhere under app/, lib/ or extensions/ outside lib/invoices/invoice-payment-row.ts fails npm run check:guards. Operator scripts under scripts/ are out of its scope on purpose. Tests: the writer's unit tests cover the new options, the explicit-null rate, the SQLSTATE passthrough and the öre-rounded prior-paid subtraction; the per-path 3740 tests from the first commit stand; mock insert slots now return the row id the writer selects back. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015qgLgdt4mLmha1ZLFMwq1u --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
2d927349d3
commit
743e3ae7cc
@@ -231,7 +231,7 @@ describe('commitPendingOperation: link_transaction_journal_entry', () => {
|
||||
})
|
||||
enqueue({ data: [{ id: TX_UUID }], error: null }) // tx UPDATE
|
||||
enqueue({ data: [{ id: INV_UUID }], error: null }) // optimistic-lock invoice UPDATE
|
||||
enqueue({ data: null, error: null }) // invoice_payments INSERT
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments INSERT
|
||||
enqueue({ data: null, error: null }) // logMatchEvent insert
|
||||
enqueue({ data: null, error: null }) // dispatcher commit update
|
||||
|
||||
|
||||
+87
-5
@@ -171,7 +171,7 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings
|
||||
enqueue({ data: { ledger_account: '1940' }, error: null }) // cash_accounts lookup
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, error: null }) // invoice_payments insert
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
@@ -196,6 +196,15 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
expect(mockCreateCashEntry).not.toHaveBeenCalled()
|
||||
const invoiceUpdate = findCalls('invoices', 'update').at(-1)?.[0]
|
||||
expect(invoiceUpdate).toMatchObject({ paid_at: '2026-05-12T12:00:00Z' })
|
||||
// No residual: the applied amount IS the cash received (#2250).
|
||||
expect(findCalls('invoice_payments', 'insert').at(-1)?.[0]).toMatchObject({
|
||||
invoice_id: 'inv-1',
|
||||
transaction_id: 'tx-1',
|
||||
payment_date: '2026-05-12',
|
||||
amount: 12500,
|
||||
currency: 'SEK',
|
||||
journal_entry_id: 'je-1',
|
||||
})
|
||||
expect(matchedHandler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
invoice: expect.objectContaining({
|
||||
@@ -253,7 +262,7 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings
|
||||
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, error: null }) // invoice_payments insert
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
@@ -302,7 +311,7 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
// it keeps the 1930 fallback.
|
||||
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, error: null }) // invoice_payments insert
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
@@ -407,7 +416,7 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings
|
||||
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, error: null }) // invoice_payments insert
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
@@ -435,6 +444,79 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
})
|
||||
})
|
||||
|
||||
it('3740 residual: the invoice_payments row carries the applied amount, not the cash received (#2250)', async () => {
|
||||
// Remaining 999.60 settled by a whole-krona 1 000.00 bank line: 3740
|
||||
// absorbs the 0.40 and paid_amount advances by the remaining only, so the
|
||||
// AR sub-ledger row must be 999.60 as well (parity with the dashboard and
|
||||
// v1 routes; the #2236 definition every reader relies on).
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'tx-1',
|
||||
company_id: 'company-1',
|
||||
amount: 1000,
|
||||
currency: 'SEK',
|
||||
date: '2026-05-12',
|
||||
invoice_id: null,
|
||||
journal_entry_id: null,
|
||||
cash_account_id: null,
|
||||
},
|
||||
error: null,
|
||||
}) // transaction fetch
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'inv-1',
|
||||
invoice_number: 'F-2026002',
|
||||
status: 'sent',
|
||||
total: 999.6,
|
||||
remaining_amount: 999.6,
|
||||
paid_amount: 0,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
journal_entry_id: null,
|
||||
customer: { name: 'Test AB' },
|
||||
},
|
||||
error: null,
|
||||
}) // invoice fetch
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings
|
||||
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
const op = makePendingOp({ params: { transaction_id: 'tx-1', invoice_id: 'inv-1' } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(mockCreateJournalEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({
|
||||
lines: expect.arrayContaining([
|
||||
expect.objectContaining({ account_number: '1930', debit_amount: 1000 }),
|
||||
expect.objectContaining({ account_number: '1510', credit_amount: 999.6 }),
|
||||
expect.objectContaining({ account_number: '3740', credit_amount: 0.4 }),
|
||||
]),
|
||||
}),
|
||||
)
|
||||
expect(findCalls('invoices', 'update').at(-1)?.[0]).toMatchObject({
|
||||
status: 'paid',
|
||||
paid_amount: 999.6,
|
||||
remaining_amount: 0,
|
||||
})
|
||||
expect(findCalls('invoice_payments', 'insert').at(-1)?.[0]).toMatchObject({
|
||||
invoice_id: 'inv-1',
|
||||
transaction_id: 'tx-1',
|
||||
payment_date: '2026-05-12',
|
||||
amount: 999.6,
|
||||
currency: 'SEK',
|
||||
journal_entry_id: 'je-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('converts a cross-currency payment into the invoice currency before recording it', async () => {
|
||||
// Parity with the dashboard/v1 routes: feeding the raw SEK amount into a
|
||||
// USD invoice corrupts the units of paid_amount / remaining_amount and
|
||||
@@ -474,7 +556,7 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
enqueue({ data: { accounting_method: 'accrual', entity_type: 'aktiebolag' }, error: null }) // settings
|
||||
enqueue({ data: [], error: null }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, error: null }) // invoice_payments insert
|
||||
enqueue({ data: { id: 'ip-1' }, error: null }) // invoice_payments insert
|
||||
enqueue({ data: null, error: null }) // transactions update (link)
|
||||
enqueue({ data: null, error: null }) // dispatcher pending_operations update
|
||||
|
||||
|
||||
@@ -3504,18 +3504,35 @@ async function commitMatchTransactionInvoice(
|
||||
// No cash-method note here anymore: pure kontantmetoden partials are now
|
||||
// rejected above, and for an invoice booked at send the clearing entry
|
||||
// handles a partial correctly, so the note would be misleading.
|
||||
await supabase.from('invoice_payments').insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
invoice_id: invoiceId,
|
||||
payment_date: transaction.date,
|
||||
amount: paidAmount,
|
||||
currency: invoice.currency,
|
||||
exchange_rate: fx.required ? fx.rate : invoice.exchange_rate,
|
||||
journal_entry_id: journalEntryId,
|
||||
transaction_id: transactionId,
|
||||
notes: null,
|
||||
// The AR sub-ledger row goes through the single writer
|
||||
// (lib/invoices/invoice-payment-row.ts), which owns the amount definition:
|
||||
// applied to the invoice, never the cash received (#2250). Not fatal here,
|
||||
// exactly like the fire-and-forget insert it replaces: the voucher and the
|
||||
// invoice update are already committed. The failure is logged now, so the
|
||||
// row the kontantmetod cut-off would otherwise miss can be added.
|
||||
const recorded = await recordInvoicePaymentRow(supabase, {
|
||||
userId,
|
||||
companyId,
|
||||
invoice: {
|
||||
id: invoiceId,
|
||||
currency: invoice.currency,
|
||||
exchange_rate: invoice.exchange_rate,
|
||||
paid_amount: invoice.paid_amount,
|
||||
},
|
||||
paymentDate: transaction.date,
|
||||
newPaidAmount,
|
||||
journalEntryId,
|
||||
transactionId,
|
||||
exchangeRate: fx.required ? fx.rate : invoice.exchange_rate,
|
||||
})
|
||||
if (!recorded.ok) {
|
||||
log.error('match_transaction_invoice: invoice_payments insert failed', undefined, {
|
||||
invoiceId,
|
||||
transactionId,
|
||||
companyId,
|
||||
error: recorded.error,
|
||||
})
|
||||
}
|
||||
|
||||
// The invoice is now settled, so every OTHER transaction still carrying a
|
||||
// suggestion pointer at it is dead: retire them (issue #1259). This
|
||||
|
||||
Reference in New Issue
Block a user