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:
co-authored by
Claude Opus 5
parent
1a5d205bd6
commit
27ae59040e
@@ -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({
|
||||
|
||||
Reference in New Issue
Block a user