fix(transactions): retire stale invoice match pointers when an invoice settles (#1313)

* fix(transactions): retire stale invoice match pointers when an invoice settles

potential_invoice_id / potential_supplier_invoice_id are write-once import
suggestions: nothing revisited them once written. With recurring same-amount
invoices, an earlier suggestion pointed transaction A at invoice X, X was then
paid off by transaction B, and A kept pointing at a fully paid invoice. The
match dialog computed its amount diff against that invoice's 0 kr
remaining_amount and reported a bogus partial payment, and the dead pointer
also blocked a fresh suggestion: both re-suggestion scans require the column
to be NULL.

Add one shared helper, clearSettledInvoiceSuggestions(), that nulls a settled
invoice's own suggestion column on every other transaction of the same
company, scoped by company_id and by that invoice id only, never widening to
the confirmed invoice_id / supplier_invoice_id links. It is best effort by
construction: every caller has already booked a payment verifikat, so a failed
cleanup logs and returns instead of failing the settle.

Wired into every path where an invoice reaches paid through a payment:
the dashboard and v1 match-invoice / match-supplier-invoice routes, the
dashboard and v1 mark-paid routes, settleInvoicePayment, the batch allocation
route (per fully settled allocation), linkInvoiceToVoucher and
linkSupplierInvoiceToVoucher, linkTransactionToJournalEntry, and the MCP
staged-operation executors for mark_invoice_paid and
match_transaction_invoice. Partial payments are deliberately left alone: a
partially paid invoice is still matchable. The v1 supplier match route also
clears its own row's hint, which it was missing next to its dashboard twin.

Read-time revalidation stays as the backstop for the paths not wired up here.
countSuggestedMatches now delegates to listSuggestedMatches, which already
revalidates candidates, so the worklist badge can no longer claim a number the
list refuses to render.

A data-only backfill migration retires the pointers already stranded in the
database. It touches no journal entry, verifikat or period-locked data, is
idempotent, and its status lists mirror lib/invoices/matchable-statuses.ts.

Fixes #1259

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

* fix(transactions): wire the MCP batch allocation into the settled-pointer cleanup

Review follow-up on the #1259 fix.

commitMatchBatchAllocate calls the same match_batch_allocate RPC as the
dashboard route, and gnubok_match_batch_allocate is a live staged MCP tool, so
an agent settling a samlingsbetalning reproduced the issue exactly: the RPC
nulls potential_invoice_id / potential_supplier_invoice_id only on the source
transaction, leaving every other transaction of the company pointing at an
invoice the batch just closed. The per-allocation loop moves into
clearSettledBatchAllocationSuggestions() so the HTTP route and the MCP executor
run the same code and cannot drift again, with a commit-path test pinning that
only the fully settled allocation is retired.

The enlarged badge scan is made safe. countSuggestedMatches now feeds up to 200
ids into listSuggestedMatches, past the 150 per .in() that countInboxDocuments
already chunks for, so the candidate lookups are chunked at IN_CLAUSE_CHUNK too
and their ids deduped. Both lookups now check .error: previously a 414, a 500 or
an RLS change produced empty maps, an empty list and a zero badge with nothing
logged. Every failure branch here logs companyId, matching the logAndZero
convention.

Also: restore the anchorSupplierInvoiceDocument doc comment above its own call
in the dashboard supplier-invoice mark-paid route (the #1259 block had been
inserted between them), and assert the transaction update payload in the v1
match-supplier-invoice test, which now covers the potential_supplier_invoice_id
null that the route was missing next to its dashboard twin.

Fixes #1259

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-30 18:52:24 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 1a5d205bd6
commit 27ae59040e
35 changed files with 1627 additions and 86 deletions
@@ -107,6 +107,14 @@ vi.mock('@/lib/core/documents/document-service', async () => {
return { ...actual, linkToJournalEntry: vi.fn() }
})
// Mocked away so the settled-suggestion cleanup (issue #1259) does not add a
// `transactions` query to the recorded set: the txQueries() assertions below
// are about the duplicate-guard sweeps only. The helper's own query shape is
// pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: vi.fn().mockResolvedValue(undefined),
}))
import { eventBus } from '@/lib/events'
import { POST } from '../route'
@@ -39,8 +39,15 @@ vi.mock('@/lib/core/documents/supplier-invoice-underlag', () => ({
anchorSupplierInvoiceDocument: vi.fn().mockResolvedValue(null),
}))
// Mocked so it consumes no slot in the queued Supabase mock: the helper's own
// query shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: vi.fn().mockResolvedValue(undefined),
}))
import { eventBus } from '@/lib/events'
import { anchorSupplierInvoiceDocument } from '@/lib/core/documents/supplier-invoice-underlag'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { POST } from '../route'
@@ -148,6 +155,16 @@ describe('POST /api/supplier-invoices/[id]/mark-paid', () => {
expect(body.remaining_amount).toBe(0)
expect(body.journal_entry_id).toBe('je-1')
expect(mockCreateSupplierInvoicePaymentEntry).toHaveBeenCalled()
// Issue #1259: full settlement retires every transaction's suggestion
// pointer at this invoice. No exceptTransactionId: mark-paid is not driven
// by a bank transaction.
expect(vi.mocked(clearSettledInvoiceSuggestions)).toHaveBeenCalledTimes(1)
expect(vi.mocked(clearSettledInvoiceSuggestions)).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'supplier_invoice',
'si-1',
)
})
it('marks as partially paid', async () => {
@@ -188,6 +205,9 @@ describe('POST /api/supplier-invoices/[id]/mark-paid', () => {
expect(body.status).toBe('partially_paid')
expect(body.paid_amount).toBe(5000)
expect(body.remaining_amount).toBe(5000)
// Issue #1259: a partially paid invoice is still matchable, so its sibling
// suggestions must survive.
expect(vi.mocked(clearSettledInvoiceSuggestions)).not.toHaveBeenCalled()
})
it('uses cash method journal entry when configured', async () => {
@@ -9,6 +9,7 @@ import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
import { cancelOrphanedPaymentEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { anchorSupplierInvoiceDocument } from '@/lib/core/documents/supplier-invoice-underlag'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { validateBody } from '@/lib/api/validate'
import { MarkSupplierInvoicePaidSchema } from '@/lib/api/schemas'
import { withRouteContext } from '@/lib/api/with-route-context'
@@ -396,6 +397,13 @@ export const POST = withRouteContext(
})
}
// Fully settled: retire every transaction's suggestion pointer at this
// invoice (issue #1259). No exceptTransactionId: this flow is not driven by
// a bank transaction, so any pointer at it is now dead.
if (isFullyPaid) {
await clearSettledInvoiceSuggestions(supabase, companyId!, 'supplier_invoice', id)
}
// Under kontantmetoden the cash payment entry is the ONLY booking of the
// affärshändelse, so its underlag (the document from the inbox) must hang on
// THIS verifikat per BFL 5 kap 6 §. Under faktureringsmetoden the document
@@ -17,6 +17,14 @@ vi.mock('@/lib/invoices/match-log', () => ({
logMatchEvent: vi.fn(),
}))
// Issue #1259: settling the invoice retires the suggestion pointers at it.
// Mocked so it consumes no slot in the queued Supabase mock; the helper's own
// query shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: mockClearSuggestions,
}))
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: vi.fn() },
}))
@@ -250,6 +258,58 @@ describe('POST /api/transactions/[id]/link-journal-entry', () => {
expect(body.invoice_status).toBe('paid')
expect(body.paid_amount).toBe(1000)
expect(body.remaining_amount).toBe(0)
// Issue #1259: the invoice is settled, so no other transaction may keep
// pointing at it as a match suggestion.
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'invoice',
INV_UUID,
)
})
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
enqueue({
data: makeTransaction({ id: TX_UUID, journal_entry_id: null, amount: 400, date: '2026-05-15' }),
error: null,
})
enqueue({
data: {
id: JE_UUID,
status: 'posted',
voucher_series: 'A',
voucher_number: 1,
entry_date: '2026-05-15',
},
error: null,
})
enqueue({
data: makeInvoice({
id: INV_UUID,
status: 'sent',
total: 1000,
remaining_amount: 1000,
paid_amount: 0,
currency: 'SEK',
}),
error: null,
})
enqueue({ data: [{ id: TX_UUID }], error: null }) // update transaction
enqueue({ data: [{ id: INV_UUID }], error: null }) // update invoice
enqueue({ data: null, error: null }) // insert invoice_payments
enqueue({ data: null, error: null }) // logMatchEvent
const request = createMockRequest(`/api/transactions/${TX_UUID}/link-journal-entry`, {
method: 'POST',
body: { journal_entry_id: JE_UUID, invoice_id: INV_UUID },
})
const response = await POST(request, createMockRouteParams({ id: TX_UUID }))
const { status, body } = await parseJsonResponse<{ invoice_status: string | null }>(response)
expect(status).toBe(200)
expect(body.invoice_status).toBe('partially_paid')
expect(mockClearSuggestions).not.toHaveBeenCalled()
})
it('returns 404 when invoice_id supplied but invoice not found', async () => {
@@ -19,6 +19,15 @@ vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
// Issue #1259: each fully settled allocation retires the suggestion pointers
// at its invoice. Mocked so it consumes no slot in the queued Supabase mock;
// the helper's own query shape is pinned by
// lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: mockClearSuggestions,
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
@@ -33,6 +42,7 @@ import { POST } from '../route'
const TX_UUID = '11111111-1111-4111-8111-111111111111'
const INV_UUID = '22222222-2222-4222-8222-222222222222'
const SI_UUID = '33333333-3333-4333-8333-333333333333'
const SI_PARTIAL_UUID = '44444444-4444-4444-8444-444444444444'
describe('POST /api/transactions/[id]/match-batch', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
@@ -116,6 +126,76 @@ describe('POST /api/transactions/[id]/match-batch', () => {
expect(body.data.voucher_number).toBe(12)
expect(body.data.allocations).toHaveLength(1)
expect(body.data.total_allocated).toBe(1000)
// Issue #1259: the allocation settled the invoice in full, so every OTHER
// transaction still pointing at it as a suggestion is retired.
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'invoice',
INV_UUID,
{ exceptTransactionId: TX_UUID },
)
})
it('retires suggestions only for the allocations that settled in full', async () => {
enqueue({
data: {
ok: true,
journal_entry_id: 'je-batch-2',
voucher_series: 'A',
voucher_number: 13,
tx_id: TX_UUID,
allocations: [
{
kind: 'supplier_invoice',
supplier_invoice_id: SI_UUID,
payment_id: 'sip-1',
status: 'paid',
paid_amount: 1000,
remaining_amount: 0,
amount: 1000,
},
{
kind: 'supplier_invoice',
supplier_invoice_id: SI_PARTIAL_UUID,
payment_id: 'sip-2',
status: 'partially_paid',
paid_amount: 400,
remaining_amount: 600,
amount: 400,
},
],
total_allocated: 1400,
leftover: 0,
},
error: null,
})
enqueue({ data: { id: TX_UUID, amount: -1400, currency: 'SEK' }, error: null }) // tx fetch
enqueue({ data: { id: SI_UUID, currency: 'SEK', status: 'paid' }, error: null })
enqueue({ data: { id: SI_PARTIAL_UUID, currency: 'SEK', status: 'partially_paid' }, error: null })
const request = createMockRequest(`/api/transactions/${TX_UUID}/match-batch`, {
method: 'POST',
body: {
allocations: [
{ kind: 'supplier_invoice', supplier_invoice_id: SI_UUID, amount: 1000 },
{ kind: 'supplier_invoice', supplier_invoice_id: SI_PARTIAL_UUID, amount: 400 },
],
},
})
const response = await POST(request, createMockRouteParams({ id: TX_UUID }))
expect(response.status).toBe(200)
// Only the fully settled one: a partially paid invoice is still matchable.
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'supplier_invoice',
SI_UUID,
{ exceptTransactionId: TX_UUID },
)
})
it('maps an RPC structured failure to errorResponseFromCode', async () => {
@@ -4,6 +4,7 @@ import { validateBody } from '@/lib/api/validate'
import { MatchBatchSchema } from '@/lib/api/schemas'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { eventBus } from '@/lib/events/bus'
import { clearSettledBatchAllocationSuggestions } from '@/lib/invoices/clear-settled-batch-allocations'
import { ensureInitialized } from '@/lib/init'
import type { Invoice, SupplierInvoice, Transaction } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
@@ -149,6 +150,17 @@ export const POST = withRouteContext(
}
}
// Every allocation the RPC settled in full retires its suggestion pointer
// from the company's OTHER transactions (issue #1259). This request's own
// row is linked by the RPC, so it is excluded there. Shared with the MCP
// executor for the same RPC (commitMatchBatchAllocate).
await clearSettledBatchAllocationSuggestions(
supabase,
companyId!,
result.allocations,
transactionId,
)
return NextResponse.json({
data: {
journal_entry_id: result.journal_entry_id,
@@ -44,6 +44,13 @@ vi.mock('@/lib/invoices/duplicate-payment-detection', () => ({
detectDuplicatePaymentVoucher: (...args: unknown[]) => mockDetectDuplicate(...args),
}))
// Mocked so it consumes no slot in the queued Supabase mock: the helper's own
// query shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const mockClearSuggestions = vi.fn()
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: (...args: unknown[]) => mockClearSuggestions(...args),
}))
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: vi.fn() },
}))
@@ -628,6 +635,49 @@ describe('POST /api/transactions/[id]/match-invoice', () => {
expect(body.invoice_status).toBe('partially_paid')
expect(body.paid_amount).toBe(5000)
expect(body.remaining_amount).toBe(7500)
// Issue #1259: a partially paid invoice is still matchable, so the sibling
// suggestions must survive.
expect(mockClearSuggestions).not.toHaveBeenCalled()
})
// Issue #1259: full settlement retires the pointer at this invoice from every
// OTHER transaction still carrying it as an import-time suggestion.
it('retires the settled invoice suggestion on the other transactions', async () => {
const tx = makeTransaction({ id: 'tx-1', amount: 12500, invoice_id: null, date: '2024-06-15' })
const invoice = makeInvoice({
id: VALID_UUID,
status: 'sent',
total: 12500,
remaining_amount: 12500,
paid_amount: 0,
})
enqueue({ data: tx, error: null })
enqueue({ data: invoice, error: null })
enqueue({ data: [], error: null }) // hard-duplicate check
enqueue({ data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null })
mockCreateJournalEntry.mockResolvedValue({ id: 'je-1' })
enqueue({ data: [{ id: VALID_UUID }], error: null }) // update invoice
enqueue({ data: null, error: null }) // insert invoice_payments
enqueue({ data: null, error: null }) // update transaction
enqueue({ data: null, error: null }) // logMatchEvent
const request = createMockRequest('/api/transactions/tx-1/match-invoice', {
method: 'POST',
body: { invoice_id: VALID_UUID },
})
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'invoice',
VALID_UUID,
{ exceptTransactionId: 'tx-1' },
)
})
it('cash method ignores cash entry when invoice was already booked (accrual→cash migration)', async () => {
@@ -15,6 +15,7 @@ import { MatchInvoiceSchema } from '@/lib/api/schemas'
import { logMatchEvent } from '@/lib/invoices/match-log'
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
import { detectDuplicatePaymentVoucher } from '@/lib/invoices/duplicate-payment-detection'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { eventBus } from '@/lib/events/bus'
import { ensureInitialized } from '@/lib/init'
import type { Currency, EntityType, Invoice, Transaction } from '@/types'
@@ -688,6 +689,15 @@ export const POST = withRouteContext(
return errorResponseFromCode('MATCH_INVOICE_RECORD_PAYMENT_FAILED', txLog, { requestId })
}
// The invoice is now settled, so every OTHER transaction still carrying a
// suggestion pointer at it is dead: retire them (issue #1259). This
// request's own row is cleared by the update just below.
if (isFullyPaid) {
await clearSettledInvoiceSuggestions(supabase, companyId!, 'invoice', invoice_id, {
exceptTransactionId: transactionId,
})
}
const { error: updateTxError } = await supabase
.from('transactions')
.update({
@@ -38,6 +38,13 @@ vi.mock('@/lib/invoices/match-log', () => ({
logMatchEvent: vi.fn(),
}))
// Mocked so it consumes no slot in the queued Supabase mock: the helper's own
// query shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const mockClearSuggestions = vi.fn()
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: (...args: unknown[]) => mockClearSuggestions(...args),
}))
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: vi.fn() },
}))
@@ -473,6 +480,36 @@ describe('POST /api/transactions/[id]/match-supplier-invoice: non-FX paths', ()
})
})
// Issue #1259: the settled invoice's pointer must also be retired from every
// OTHER transaction that still carries it as an import-time suggestion.
it('retires the settled invoice suggestion on the other transactions', async () => {
enqueueHappyPath({
transaction: { amount: -1000, currency: 'SEK' },
invoice: { currency: 'SEK', remaining_amount: 1000 },
})
await POST(makeReq(), createMockRouteParams({ id: TX_UUID }))
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
mockSupabase,
'company-1',
'supplier_invoice',
SI_UUID,
{ exceptTransactionId: TX_UUID },
)
})
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
enqueueHappyPath({
transaction: { amount: -400, currency: 'SEK' },
invoice: { currency: 'SEK', remaining_amount: 1000 },
})
const res = await POST(makeReq(), createMockRouteParams({ id: TX_UUID }))
const { body } = await parseJsonResponse<{ invoice_status: string }>(res)
expect(body.invoice_status).toBe('partially_paid')
expect(mockClearSuggestions).not.toHaveBeenCalled()
})
it('öresavrundning: a whole-krona Bankgiro payment settles an öre-bearing invoice in full via 3740', async () => {
// The reported bug: invoice 11 231,25, bank paid 11 231 → previously left
// 0,25 stranded as partially_paid. Now → paid, with 0,25 booked to 3740.
@@ -15,6 +15,7 @@ import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structure
import { validateBody } from '@/lib/api/validate'
import { MatchSupplierInvoiceSchema } from '@/lib/api/schemas'
import { logMatchEvent } from '@/lib/invoices/match-log'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { eventBus } from '@/lib/events/bus'
import { ensureInitialized } from '@/lib/init'
import type { SupplierInvoice, SupplierInvoiceItem, Transaction } from '@/types'
@@ -412,6 +413,19 @@ export const POST = withRouteContext(
return errorResponseFromCode('MATCH_SI_RECORD_PAYMENT_FAILED', txLog, { requestId })
}
// The invoice is now settled, so every OTHER transaction still carrying a
// suggestion pointer at it is dead: retire them (issue #1259). This
// request's own row is cleared by the update just below.
if (isFullyPaid) {
await clearSettledInvoiceSuggestions(
supabase,
companyId!,
'supplier_invoice',
supplier_invoice_id,
{ exceptTransactionId: transactionId },
)
}
const { error: updateTxError } = await supabase
.from('transactions')
.update({
@@ -42,6 +42,14 @@ vi.mock('@/lib/bookkeeping/engine', () => ({
findFiscalPeriod: vi.fn().mockResolvedValue('fp-1'),
}))
// Issue #1259: settling the invoice retires the suggestion pointers at it.
// Mocked so the assertion is on the orchestration; the helper's own query
// shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: mockClearSuggestions,
}))
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
import {
createInvoicePaymentJournalEntry as mockedPayment,
@@ -185,6 +193,15 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
expect(paidHandler).toHaveBeenCalledWith(
expect.objectContaining({ companyId: COMPANY_ID, userId: USER_ID, paymentAmount: 12500 }),
)
// Issue #1259: the invoice is settled, so no transaction may keep pointing
// at it as a match suggestion.
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
expect.anything(),
COMPANY_ID,
'invoice',
INVOICE_ID,
)
})
it('uses the cash-basis booking when accounting_method=cash', async () => {
@@ -737,6 +754,9 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
// the transactions scan never runs: the matching bank row above would
// otherwise have 409'd a perfectly valid partial payment.
expect(calls.some((c) => c.table === 'transactions')).toBe(false)
// Issue #1259: a partially paid invoice is still matchable, so the
// suggestions pointing at it must survive.
expect(mockClearSuggestions).not.toHaveBeenCalled()
})
it('still runs the duplicate guard when the converted SEK lines settle a EUR invoice in full', async () => {
@@ -43,6 +43,7 @@ import { getErrorMessage } from '@/lib/errors/get-error-message'
import { eventBus } from '@/lib/events'
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
import { planInvoicePaymentForLines } from '@/lib/invoices/apply-invoice-payment'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { roundOre } from '@/lib/money'
import type { CreateJournalEntryInput, EntityType, Invoice } from '@/types'
@@ -543,6 +544,13 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
})
}
// Fully settled: retire every transaction's suggestion pointer at this
// invoice (issue #1259). No exceptTransactionId: this flow is not driven by
// a bank transaction, so any pointer at it is now dead.
if (newStatus === 'paid') {
await clearSettledInvoiceSuggestions(ctx.supabase, ctx.companyId!, 'invoice', invoiceId)
}
// Step 3: emit invoice.paid (best-effort, surfaces in warnings on fail).
try {
await eventBus.emit({
@@ -0,0 +1,209 @@
/**
* Coverage for POST /api/v1/companies/:companyId/supplier-invoices/:id/mark-paid.
*
* Scoped to the settled-suggestion cleanup (issue #1259): a supplier invoice
* paid through the API must not leave bank transactions pointing at it as an
* import-time match suggestion, and a PARTIAL payment must leave those
* suggestions alone because the invoice is still matchable.
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
beforeAll(() => {
if (process.env.NODE_ENV !== 'test') {
throw new Error(
`mark-paid route tests require NODE_ENV=test (got ${process.env.NODE_ENV ?? 'undefined'})`,
)
}
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
})
vi.mock('@/lib/auth/api-keys', async () => {
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
return {
...actual,
validateApiKey: vi.fn(),
createServiceClientNoCookies: vi.fn(),
}
})
vi.mock('@supabase/supabase-js', async () => {
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
})
// Journal-entry helpers are stubbed: the route flow is what we test here.
vi.mock('@/lib/bookkeeping/supplier-invoice-entries', () => ({
createSupplierInvoicePaymentEntry: vi.fn().mockResolvedValue({ id: 'je-si-payment' }),
createSupplierInvoiceCashEntry: vi.fn().mockResolvedValue({ id: 'je-si-cash' }),
}))
vi.mock('@/lib/bookkeeping/engine', () => ({
createJournalEntry: vi.fn().mockResolvedValue({ id: 'je-custom' }),
findFiscalPeriod: vi.fn().mockResolvedValue('fp-1'),
reverseEntry: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/core/documents/supplier-invoice-underlag', () => ({
anchorSupplierInvoiceDocument: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/api/v1/check-period-lock', () => ({
checkPeriodLock: vi.fn().mockResolvedValue({ locked: false, fiscal_period_id: 'fp-1' }),
}))
// Issue #1259: settling the invoice retires the suggestion pointers at it.
// Mocked so the assertion is on the orchestration; the helper's own query
// shape is pinned by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: mockClearSuggestions,
}))
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { POST as markPaid } from '../route'
import { eventBus } from '@/lib/events'
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
type MockResult = { data?: unknown; error?: unknown }
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
const queues = new Map<string, MockResult[]>()
for (const [t, val] of Object.entries(byTable)) {
queues.set(t, Array.isArray(val) ? [...val] : [val])
}
const buildChain = (table: string): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => {
const q = queues.get(table)
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
resolve(next)
}
}
return () => buildChain(table)
},
}
return new Proxy({}, handler)
}
return { from: vi.fn((table: string) => buildChain(table)) }
}
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const SI_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const USER_ID = 'user-1'
function makeRequest(body?: unknown): Request {
return new Request(
`https://x.test/api/v1/companies/${COMPANY_ID}/supplier-invoices/${SI_ID}/mark-paid`,
{
method: 'POST',
headers: {
Authorization: 'Bearer test-fixture-not-a-real-key',
'Content-Type': 'application/json',
'Idempotency-Key': 'idem1234-1010-4abc-8def-1234567890ab',
},
body: body !== undefined ? JSON.stringify(body) : undefined,
},
)
}
function detailParams() {
return { params: Promise.resolve({ companyId: COMPANY_ID, id: SI_ID }) }
}
const APPROVED_SI = {
id: SI_ID,
supplier_id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
status: 'approved',
currency: 'SEK',
exchange_rate: null,
total: 1000,
paid_amount: 0,
remaining_amount: 1000,
supplier_invoice_number: 'LF-1',
arrival_number: 1,
invoice_date: '2026-05-01',
due_date: '2026-05-31',
received_date: '2026-05-01',
is_credit_note: false,
credited_invoice_id: null,
payment_journal_entry_id: null,
registration_journal_entry_id: 'je-registration',
vat_treatment: 'standard_25',
reverse_charge: false,
subtotal: 800,
vat_amount: 200,
default_dimensions: null,
supplier: { id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', name: 'Leverantör AB', supplier_type: 'swedish_business' },
items: [],
}
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
mockValidate.mockResolvedValue({
userId: USER_ID,
companyId: COMPANY_ID,
apiKeyId: 'ak_1',
apiKeyName: 'CI key',
scopes: ['suppliers:write'],
mode: 'live',
})
})
describe('POST /api/v1/companies/:companyId/supplier-invoices/:id/mark-paid', () => {
it('retires the settled invoice suggestions on a full payment (issue #1259)', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
supplier_invoices: [
{ data: APPROVED_SI, error: null },
{
data: { ...APPROVED_SI, status: 'paid', paid_amount: 1000, remaining_amount: 0 },
error: null,
},
],
company_settings: { data: { accounting_method: 'accrual' }, error: null },
supplier_invoice_payments: { data: null, error: null },
}),
)
const res = await markPaid(makeRequest({ payment_date: '2026-05-12' }), detailParams())
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.status).toBe('paid')
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
expect(mockClearSuggestions).toHaveBeenCalledWith(
expect.anything(),
COMPANY_ID,
'supplier_invoice',
SI_ID,
)
})
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
supplier_invoices: [
{ data: APPROVED_SI, error: null },
{
data: { ...APPROVED_SI, status: 'partially_paid', paid_amount: 400, remaining_amount: 600 },
error: null,
},
],
company_settings: { data: { accounting_method: 'accrual' }, error: null },
supplier_invoice_payments: { data: null, error: null },
}),
)
const res = await markPaid(
makeRequest({ payment_date: '2026-05-12', amount: 400 }),
detailParams(),
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.status).toBe('partially_paid')
expect(mockClearSuggestions).not.toHaveBeenCalled()
})
})
@@ -29,6 +29,7 @@ import {
import { reverseEntry, createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { anchorSupplierInvoiceDocument } from '@/lib/core/documents/supplier-invoice-underlag'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { eventBus } from '@/lib/events'
import type { SupplierInvoice, SupplierInvoiceItem } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
@@ -506,6 +507,18 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
})
}
// Fully settled: retire every transaction's suggestion pointer at this
// invoice (issue #1259). No exceptTransactionId: this flow is not driven by
// a bank transaction, so any pointer at it is now dead.
if (newStatus === 'paid') {
await clearSettledInvoiceSuggestions(
ctx.supabase,
ctx.companyId!,
'supplier_invoice',
invoiceId,
)
}
// Anchor the invoice's retained source document to a posted verifikat if
// it is still floating. Under kontantmetoden the cash entry we just booked
// is the only booking of the affärshändelse, so its underlag belongs here
@@ -69,6 +69,15 @@ vi.mock('@/lib/bookkeeping/supplier-invoice-entries', () => ({
vi.mock('@/lib/invoices/match-log', () => ({
logMatchEvent: vi.fn(),
}))
// Issue #1259: the settle paths retire sibling suggestion pointers. Mocked so
// the assertion is on the orchestration; the helper's own query shape is pinned
// by lib/invoices/__tests__/clear-settled-invoice-suggestions.test.ts.
const { clearSuggestionsMock } = vi.hoisted(() => ({
clearSuggestionsMock: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
clearSettledInvoiceSuggestions: clearSuggestionsMock,
}))
vi.mock('@/lib/bookkeeping/mapping-engine', async () => {
// Keep the real applySettlementAccount: it's a pure rewrite (1930 -> the
// resolved bank leg) and the v1 categorize route's settlement-account fix
@@ -111,6 +120,10 @@ function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>
for (const [t, val] of Object.entries(byTable)) {
queues.set(t, Array.isArray(val) ? [...val] : [val])
}
// Every chained builder call, in order. The proxy otherwise swallows its
// arguments, which makes update payloads invisible to assertions. Recording
// is passive: it changes nothing about what a chain resolves to.
const calls: { table: string; method: string; args: unknown[] }[] = []
const buildChain = (table: string): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
@@ -121,12 +134,25 @@ function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>
resolve(next)
}
}
return (..._args: unknown[]) => buildChain(table)
return (...args: unknown[]) => {
calls.push({ table, method: String(prop), args })
return buildChain(table)
}
},
}
return new Proxy({}, handler)
}
return { from: vi.fn((table: string) => buildChain(table)) }
return { from: vi.fn((table: string) => buildChain(table)), calls }
}
/** Payloads of every `.update()` call made against `table`. */
function updatePayloads(
supa: { calls: { table: string; method: string; args: unknown[] }[] },
table: string,
): Record<string, unknown>[] {
return supa.calls
.filter((c) => c.table === table && c.method === 'update')
.map((c) => c.args[0] as Record<string, unknown>)
}
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
@@ -558,6 +584,16 @@ describe('POST :id/match-invoice', () => {
expect.objectContaining({ account_number: '1930', debit_amount: 12500, credit_amount: 0 }),
expect.objectContaining({ account_number: '1510', debit_amount: 0, credit_amount: 12500 }),
])
// Issue #1259: settling the invoice retires its suggestion pointer on every
// OTHER transaction of the company.
expect(clearSuggestionsMock).toHaveBeenCalledTimes(1)
expect(clearSuggestionsMock).toHaveBeenCalledWith(
expect.anything(),
COMPANY_ID,
'invoice',
INV_ID,
{ exceptTransactionId: TX_ID },
)
})
it('rejects negative transaction with MATCH_INVOICE_NOT_INCOME', async () => {
@@ -814,41 +850,40 @@ describe('POST :id/match-invoice', () => {
describe('POST :id/match-supplier-invoice', () => {
it('matches a negative transaction to an open supplier invoice', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
transactions: {
const supa = makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
transactions: {
data: {
id: TX_ID,
amount: -5000,
date: '2026-05-12',
currency: 'SEK',
supplier_invoice_id: null,
journal_entry_id: null,
},
error: null,
},
supplier_invoices: [
{
data: {
id: TX_ID,
amount: -5000,
date: '2026-05-12',
id: SI_ID,
status: 'approved',
total: 5000,
paid_amount: 0,
remaining_amount: 5000,
currency: 'SEK',
supplier_invoice_id: null,
journal_entry_id: null,
exchange_rate: null,
supplier: { name: 'Acme', supplier_type: 'swedish_business' },
items: [],
},
error: null,
},
supplier_invoices: [
{
data: {
id: SI_ID,
status: 'approved',
total: 5000,
paid_amount: 0,
remaining_amount: 5000,
currency: 'SEK',
exchange_rate: null,
supplier: { name: 'Acme', supplier_type: 'swedish_business' },
items: [],
},
error: null,
},
{ data: [{ id: SI_ID }], error: null },
],
company_settings: { data: { accounting_method: 'accrual' }, error: null },
supplier_invoice_payments: { data: null, error: null },
}),
)
{ data: [{ id: SI_ID }], error: null },
],
company_settings: { data: { accounting_method: 'accrual' }, error: null },
supplier_invoice_payments: { data: null, error: null },
})
mockServiceClient.mockReturnValue(supa)
const res = await matchSIPOST(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/transactions/${TX_ID}/match-supplier-invoice`,
@@ -859,6 +894,25 @@ describe('POST :id/match-supplier-invoice', () => {
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.invoice_status).toBe('paid')
// Issue #1259: the confirmed link supersedes the suggestion, so this row's
// own hint must not survive it. Parity with the dashboard twin, which this
// route was missing.
expect(updatePayloads(supa, 'transactions')).toContainEqual(
expect.objectContaining({
supplier_invoice_id: SI_ID,
potential_supplier_invoice_id: null,
is_business: true,
}),
)
// And every OTHER transaction of the company gets its pointer retired.
expect(clearSuggestionsMock).toHaveBeenCalledTimes(1)
expect(clearSuggestionsMock).toHaveBeenCalledWith(
expect.anything(),
COMPANY_ID,
'supplier_invoice',
SI_ID,
{ exceptTransactionId: TX_ID },
)
})
it('rejects positive transaction with MATCH_SI_NOT_EXPENSE', async () => {
@@ -41,6 +41,7 @@ import { getErrorMessage } from '@/lib/errors/get-error-message'
import { logMatchEvent } from '@/lib/invoices/match-log'
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
import { detectDuplicatePaymentVoucher } from '@/lib/invoices/duplicate-payment-detection'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { eventBus } from '@/lib/events/bus'
import type { Currency, EntityType, Invoice, Transaction } from '@/types'
@@ -741,6 +742,15 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
})
}
// The invoice is now settled, so every OTHER transaction still carrying a
// suggestion pointer at it is dead: retire them (issue #1259). This
// request's own row is cleared by the update just below.
if (isFullyPaid) {
await clearSettledInvoiceSuggestions(ctx.supabase, ctx.companyId!, 'invoice', invoice_id, {
exceptTransactionId: txId,
})
}
// When the tx already has a category (set by a prior :categorize call,
// could be income_products / rental / etc.), preserve it. When there is
// none, leave the column UNTOUCHED: the existing default ('uncategorized')
@@ -23,6 +23,7 @@ import { findUnresolvableAccounts } from '@/lib/bookkeeping/account-validation'
import { anchorSupplierInvoiceDocument } from '@/lib/core/documents/supplier-invoice-underlag'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { logMatchEvent } from '@/lib/invoices/match-log'
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
import { eventBus } from '@/lib/events/bus'
import type { SupplierInvoice, SupplierInvoiceItem, Transaction } from '@/types'
@@ -464,10 +465,26 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
})
}
// The invoice is now settled, so every OTHER transaction still carrying a
// suggestion pointer at it is dead: retire them (issue #1259). This
// request's own row is cleared by the update just below.
if (isFullyPaid) {
await clearSettledInvoiceSuggestions(
ctx.supabase,
ctx.companyId!,
'supplier_invoice',
supplier_invoice_id,
{ exceptTransactionId: txId },
)
}
const { error: updateTxErr } = await ctx.supabase
.from('transactions')
.update({
supplier_invoice_id,
// Parity with the dashboard route: the confirmed link supersedes the
// suggestion, so the hint must not survive it (issue #1259).
potential_supplier_invoice_id: null,
journal_entry_id: journalEntryId,
is_business: true,
})