fix(invoices): guard cash-method partial payments across every payment path (#1413)

* fix(invoices): guard cash-method partial payments across every payment path

A never-booked kontantmetoden invoice can only be settled by the generated
cash entry (createInvoiceCashEntry / createSupplierInvoiceCashEntry), and
that entry always books the FULL invoice: it takes no payment amount. Three
payment surfaces still let partial payments through to it, corrupting books:

- settleInvoicePayment dropped the fully-paid term entirely, so a partial
  payment (Stripe sync, mark-paid) booked the entire invoice: over-recognized
  revenue, over-declared output VAT, and a bank debit that did not match the
  money received.
- The dashboard and agent match-transaction paths fell back to an
  accrual-style clearing entry against an EMPTY 1510: negative receivable,
  no revenue, no moms (ML 13 kap 8 § puts each installment's moms in its own
  receipt period). The comment claimed the credit "gets resolved on final
  payment", but the cash builder never touches 1510 and books the full
  total, so the final payment double-debited the bank instead.
- The supplier routes had no full-settlement term at all, so a partial
  payment booked the full expense + input VAT.

Fix: one shared predicate (cashPartialBlockReason in booking-mode.ts)
rejects generated cash entries unless the payment settles the invoice in
full from a fully unpaid state, wired into all six POST surfaces, the agent
commit paths, and the three preview routes (so dialogs cannot propose a
verifikat the POST refuses). New bilingual error codes
INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED / SI_CASH_PARTIAL_UNSUPPORTED.
Invoices booked at issue are unaffected: their partial payments keep the
normal 1510/2440 clearing path.

The v1 match-invoice route already had this guard (VALIDATION_ERROR); its
behavior is unchanged. Proper per-installment recognition (proportional
revenue + moms per receipt) is the follow-up feature that would lift this
restriction.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(review): drop stale ML 13 kap 8 § cites for kontantmetoden VAT timing

Compliance-review finding: the section is the old ML 1994:200 numbering; in
ML 2023:200, 13 kap covers input-VAT deduction, not redovisningstidpunkt.
The substantive rule (bokslutsmetoden reports moms at payment, per
installment, except at year-end) is unchanged and stated without a section
cite until the current-law section is verified. Comments and cookbook prose
only; no behavior change. Also fixes the two pre-existing occurrences.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-05 18:05:11 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 0449b1d0ea
commit 17d48ebb84
22 changed files with 599 additions and 58 deletions
+45 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { booksInvoicesOnIssue } from '../booking-mode'
import { booksInvoicesOnIssue, cashPartialBlockReason } from '../booking-mode'
describe('booksInvoicesOnIssue (#967)', () => {
it('books at issue for accrual companies by default', () => {
@@ -22,3 +22,47 @@ describe('booksInvoicesOnIssue (#967)', () => {
expect(booksInvoicesOnIssue({})).toBe(true)
})
})
describe('cashPartialBlockReason', () => {
const base = {
invoiceAlreadyBooked: false,
accountingMethod: 'cash',
priorPaidAmount: 0,
paysRemainingInFull: true,
}
it('allows a full settlement from a fully unpaid state', () => {
expect(cashPartialBlockReason(base)).toBeNull()
})
it('blocks a partial payment on a never-booked cash invoice', () => {
expect(cashPartialBlockReason({ ...base, paysRemainingInFull: false })).toBe('partial_payment')
})
it('blocks completing a previously part-paid never-booked invoice', () => {
expect(cashPartialBlockReason({ ...base, priorPaidAmount: 500 })).toBe(
'previously_partially_paid',
)
})
it('never blocks invoices that were booked at issue (clearing entry handles partials)', () => {
expect(
cashPartialBlockReason({ ...base, invoiceAlreadyBooked: true, paysRemainingInFull: false }),
).toBeNull()
})
it('never blocks under the accrual method, including the null-settings fallback', () => {
expect(
cashPartialBlockReason({ ...base, accountingMethod: 'accrual', paysRemainingInFull: false }),
).toBeNull()
expect(
cashPartialBlockReason({ ...base, accountingMethod: '', paysRemainingInFull: false }),
).toBeNull()
})
it('ignores sub-öre noise in the prior paid amount', () => {
expect(cashPartialBlockReason({ ...base, priorPaidAmount: 0.004 })).toBeNull()
expect(cashPartialBlockReason({ ...base, priorPaidAmount: null })).toBeNull()
expect(cashPartialBlockReason({ ...base, priorPaidAmount: undefined })).toBeNull()
})
})
+33
View File
@@ -22,3 +22,36 @@ export function booksInvoicesOnIssue(
if (!settings) return true
return (settings.accounting_method || 'accrual') === 'accrual' && !settings.defer_invoice_booking
}
/**
* Kontantmetoden guard for the GENERATED payment entries on never-booked
* invoices. createInvoiceCashEntry and createSupplierInvoiceCashEntry always
* book the FULL invoice (revenue or expense + VAT + a full-total settlement
* leg); neither takes a payment amount. A generated cash entry is therefore
* only valid when the payment settles the invoice in full from a fully
* unpaid state:
*
* - a partial payment would book the whole invoice against a smaller bank
* movement and declare the whole VAT at once, but bokslutsmetoden reports
* moms at payment, so each installment's moms belongs to its own receipt
* period;
* - completing a previously part-paid invoice would book the full total a
* second time on the settlement account.
*
* Callers reject with INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED (customer) or
* SI_CASH_PARTIAL_UNSUPPORTED (supplier) until per-installment recognition
* exists. Invoices already booked at issue are never affected: their payment
* is a plain clearing entry against 1510/2440, which handles partials fine.
*/
export function cashPartialBlockReason(opts: {
invoiceAlreadyBooked: boolean
accountingMethod: string
priorPaidAmount: number | null | undefined
paysRemainingInFull: boolean
}): 'partial_payment' | 'previously_partially_paid' | null {
if (opts.invoiceAlreadyBooked) return null
if ((opts.accountingMethod || 'accrual') !== 'cash') return null
if (!opts.paysRemainingInFull) return 'partial_payment'
if (Math.round((opts.priorPaidAmount ?? 0) * 100) !== 0) return 'previously_partially_paid'
return null
}
@@ -214,7 +214,7 @@ The ledger is SEK-denominated; foreign amounts are converted to SEK automaticall
- **Re-running the same file is safe; date-only overlap is also safe.** Dedup is primarily by a stable \`external_id\` (date + amount + counterparty); a secondary content match on \`(date, amount, description)\` against already-booked rows also skips, so partial overlap of two statements doesn't double-import.
- **Settlement account selection matters.** The wrong settlement account silently breaks bank reconciliation later. \`1930\` (företagskonto) is the SEK default; a foreign-currency bank account uses its own asset account (e.g. \`1932\` for USD). \`/imports/bank\` resolves the settlement account automatically — to set it explicitly, ingest via \`POST /transactions/ingest\` with \`settlement_account\`.
- **Cash-method companies and partial payments don't mix.** If \`company_settings.accounting_method = 'cash'\` and you try to match a partial payment, the response is \`VALIDATION_ERROR\` rather than booking accrual entries: cash-method cannot model the per-installment moms event correctly (ML 13 kap 8 §). Either book the partial payment as a separate categorisation or switch to accrual.
- **Cash-method companies and partial payments don't mix.** If \`company_settings.accounting_method = 'cash'\` and you try to match a partial payment, the response is \`VALIDATION_ERROR\` rather than booking accrual entries: cash-method cannot model the per-installment moms event correctly (bokslutsmetoden reports moms at payment, per installment). Either book the partial payment as a separate categorisation or switch to accrual.
- **Batch-categorize is partial-success by default.** If one item hits a locked period, the others still commit. The summary block tells you the totals; check per-item \`ok\` flags.
## Next steps
+14
View File
@@ -669,6 +669,20 @@ const MATCH_SI: Record<string, StructuredErrorEntry> = {
message_en:
'The cash method cannot handle a partial foreign-currency payment. Pay the invoice in full, switch to accrual, or book the payment manually.',
},
INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED: {
httpStatus: 400,
message_sv:
'Kontantmetoden kan inte bokföra delbetalningar av en obokförd faktura automatiskt: hela fakturan bokförs vid betalning. Ta emot hela beloppet i en betalning, byt till faktureringsmetoden eller bokför betalningen manuellt som verifikation.',
message_en:
'The cash method cannot auto-book partial payments of an unbooked invoice: the generated entry always books the full invoice. Receive the full amount in one payment, switch to the accrual method, or book the payment manually as a journal entry.',
},
SI_CASH_PARTIAL_UNSUPPORTED: {
httpStatus: 400,
message_sv:
'Kontantmetoden kan inte bokföra delbetalningar av en obokförd leverantörsfaktura automatiskt: hela fakturan bokförs vid betalning. Betala hela beloppet i en betalning eller bokför betalningen manuellt som verifikation.',
message_en:
'The cash method cannot auto-book partial payments of an unbooked supplier invoice: the generated entry always books the full invoice. Pay the full amount in one payment or book the payment manually as a journal entry.',
},
MATCH_SI_AMOUNT_EXCEEDS_REMAINING: {
httpStatus: 400,
message_sv:
@@ -103,6 +103,62 @@ describe('settleInvoicePayment', () => {
)
})
it('rejects a cash-method partial payment on a never-booked invoice before booking anything', async () => {
const { supabase } = createQueuedMockSupabase()
const invoice = payableInvoice({ journal_entry_id: null } as Partial<Invoice>)
const result = await settleInvoicePayment(
supabase as unknown as SupabaseClient,
'company-1',
'user-1',
{
...BASE_PARAMS,
invoice,
accountingMethod: 'cash',
paymentAmountInInvoiceCurrency: 500,
},
)
expect(result).toMatchObject({
ok: false,
code: 'INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED',
details: { reason: 'partial_payment' },
})
// The full-invoice cash entry must never book against a partial receipt,
// and no invoice state may change.
expect(vi.mocked(createInvoiceCashEntry)).not.toHaveBeenCalled()
expect(vi.mocked(createInvoicePaymentJournalEntry)).not.toHaveBeenCalled()
expect(vi.mocked(createJournalEntry)).not.toHaveBeenCalled()
})
it('rejects completing a previously part-paid never-booked cash invoice (would double-book the total)', async () => {
const { supabase } = createQueuedMockSupabase()
const invoice = payableInvoice({
status: 'partially_paid',
journal_entry_id: null,
remaining_amount: 750,
paid_amount: 500,
} as Partial<Invoice>)
const result = await settleInvoicePayment(
supabase as unknown as SupabaseClient,
'company-1',
'user-1',
{
...BASE_PARAMS,
invoice,
accountingMethod: 'cash',
paymentAmountInInvoiceCurrency: 750,
},
)
expect(result).toMatchObject({
ok: false,
code: 'INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED',
details: { reason: 'previously_partially_paid' },
})
expect(vi.mocked(createInvoiceCashEntry)).not.toHaveBeenCalled()
expect(vi.mocked(createInvoicePaymentJournalEntry)).not.toHaveBeenCalled()
})
it('uses the cash entry for unbooked kontantmetoden invoices', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: [{ id: 'inv-1' }] })
+30
View File
@@ -4,6 +4,7 @@ import {
createInvoiceCashEntry,
} from '@/lib/bookkeeping/invoice-entries'
import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
import { cashPartialBlockReason } from '@/lib/bookkeeping/booking-mode'
import { resolveInvoicePaymentSourceType } from '@/lib/bookkeeping/propose-payment-lines'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { cancelOrphanedPaymentEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
@@ -80,6 +81,7 @@ export type SettleInvoicePaymentResult =
paidAt: string | null
}
| { ok: false; code: 'MATCH_AMOUNT_EXCEEDS_REMAINING'; details: Record<string, unknown> }
| { ok: false; code: 'INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED'; details: Record<string, unknown> }
| { ok: false; code: 'INVOICE_PAID_LINES_UNBALANCED'; details: Record<string, unknown> }
| { ok: false; code: 'INVOICE_PAID_NO_FISCAL_PERIOD'; details: Record<string, unknown> }
| { ok: false; code: 'INVOICE_PAID_BOOK_FAILED'; details: Record<string, unknown> }
@@ -149,6 +151,34 @@ export async function settleInvoicePayment(
const paidAt = newStatus === 'paid' ? paidAtFromDate(paymentDate) : null
const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice'
// The generated cash entry (createInvoiceCashEntry) books the FULL invoice
// and takes no payment amount, so a never-booked kontantmetoden invoice can
// only be settled in full from a fully unpaid state. Partials used to book
// the entire revenue + moms against a smaller bank movement (bokslutsmetoden
// reports moms at payment, per installment), and completing a
// prior partial would book the full total a second time. Custom lines are
// NOT exempt: the dialog pre-fills the same full-invoice shape, so lines
// would book the identical error under a user-shaped label.
const cashBlock = cashPartialBlockReason({
invoiceAlreadyBooked,
accountingMethod,
priorPaidAmount: invoice.paid_amount,
paysRemainingInFull: newStatus === 'paid',
})
if (isRealInvoice && cashBlock) {
return {
ok: false,
code: 'INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED',
details: {
reason: cashBlock,
payment_amount: paymentAmountInInvoiceCurrency,
paid_amount: invoice.paid_amount ?? 0,
invoice_total: invoice.total,
},
}
}
let journalEntryId: string | null = null
if (isRealInvoice) {
+46 -4
View File
@@ -35,6 +35,7 @@ import {
createCreditNoteJournalEntry,
} from '@/lib/bookkeeping/invoice-entries'
import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
import { cashPartialBlockReason } from '@/lib/bookkeeping/booking-mode'
import { ensureManualCashAccount } from '@/lib/cash-accounts/service'
import { createJournalEntry, findFiscalPeriod, getSwedishLocalDate, reverseEntry, validateBalance } from '@/lib/bookkeeping/engine'
import {
@@ -1989,6 +1990,26 @@ async function commitMarkInvoicePaid(
}
const { newPaidAmount, newRemaining, newStatus } = payment.plan
// The generated cash entry books the FULL invoice: refuse to complete a
// previously part-paid, never-booked kontantmetoden invoice (it would book
// the full total a second time on the settlement account). A partial cannot
// arise here (this path always settles the full remaining), but the shared
// predicate covers it for safety.
const cashBlock = cashPartialBlockReason({
invoiceAlreadyBooked,
accountingMethod,
priorPaidAmount: inv.paid_amount,
paysRemainingInFull: newStatus === 'paid',
})
if (isRealInvoice && cashBlock) {
return {
error:
getErrorEntry('INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED')?.message_sv ??
'Kontantmetoden kan inte bokföra delbetalningar av en obokförd faktura automatiskt.',
status: 400,
}
}
if (isRealInvoice) {
if (useCashEntry) {
const je = await createInvoiceCashEntry(
@@ -2520,6 +2541,27 @@ async function commitMatchTransactionInvoice(
const invoiceAlreadyBooked = !!(invoice as { journal_entry_id?: string | null }).journal_entry_id
const useCashEntry = !invoiceAlreadyBooked && accountingMethod === 'cash' && isFullyPaid
// Reject cash-method partials and part-paid completions on never-booked
// invoices BEFORE the irreversible storno below. The old fallback booked an
// accrual-style clearing entry against an EMPTY 1510 (negative receivable,
// no revenue, no moms: bokslutsmetoden reports moms at payment, per
// installment), and the cash builder books the FULL invoice, so
// neither shape is bookable here. Mirrors the dashboard and v1 match routes.
const cashBlock = cashPartialBlockReason({
invoiceAlreadyBooked,
accountingMethod,
priorPaidAmount: (invoice as { paid_amount?: number | null }).paid_amount,
paysRemainingInFull: isFullyPaid,
})
if (cashBlock) {
return {
error:
getErrorEntry('INVOICE_PAID_CASH_PARTIAL_UNSUPPORTED')?.message_sv ??
'Kontantmetoden kan inte bokföra delbetalningar av en obokförd faktura automatiskt.',
status: 400,
}
}
// Debit the cash account THIS transaction actually belongs to, never a
// hardcoded 1930: cash_account_id -> cash_accounts.ledger_account is the
// only source of truth for which bank/cash account a real, matched
@@ -2601,9 +2643,9 @@ async function commitMatchTransactionInvoice(
}
}
const paymentNotes = (accountingMethod === 'cash' && !isFullyPaid)
? 'Kontantmetoden: intäkt bokförs vid slutbetalning' : null
// 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,
@@ -2614,7 +2656,7 @@ async function commitMatchTransactionInvoice(
exchange_rate: invoice.exchange_rate,
journal_entry_id: journalEntryId,
transaction_id: transactionId,
notes: paymentNotes,
notes: null,
})
// The invoice is now settled, so every OTHER transaction still carrying a