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
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { mockLoggerWarn } = vi.hoisted(() => ({ mockLoggerWarn: vi.fn() }))
|
||||
vi.mock('@/lib/logger', () => ({
|
||||
createLogger: () => ({
|
||||
info: vi.fn(),
|
||||
warn: mockLoggerWarn,
|
||||
error: vi.fn(),
|
||||
child: vi.fn().mockReturnThis(),
|
||||
}),
|
||||
}))
|
||||
|
||||
import { clearSettledInvoiceSuggestions } from '../clear-settled-invoice-suggestions'
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const SI_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const INV_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const TX_ID = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
const { supabase, enqueue, reset, findCall, findCalls, calls } = createQueuedMockSupabase()
|
||||
|
||||
describe('clearSettledInvoiceSuggestions', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('nulls potential_supplier_invoice_id on every OTHER transaction of the company', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'supplier_invoice',
|
||||
SI_ID,
|
||||
{ exceptTransactionId: TX_ID },
|
||||
)
|
||||
|
||||
expect(supabase.from).toHaveBeenCalledWith('transactions')
|
||||
expect(findCall('transactions', 'update')).toEqual([
|
||||
{ potential_supplier_invoice_id: null },
|
||||
])
|
||||
const eqCalls = findCalls('transactions', 'eq')
|
||||
expect(eqCalls).toEqual([
|
||||
['company_id', COMPANY],
|
||||
['potential_supplier_invoice_id', SI_ID],
|
||||
])
|
||||
expect(findCall('transactions', 'neq')).toEqual(['id', TX_ID])
|
||||
})
|
||||
|
||||
it('nulls only potential_invoice_id for kind invoice', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'invoice',
|
||||
INV_ID,
|
||||
)
|
||||
|
||||
const payload = findCall('transactions', 'update')?.[0] as Record<string, unknown>
|
||||
expect(Object.keys(payload)).toEqual(['potential_invoice_id'])
|
||||
expect(payload.potential_invoice_id).toBeNull()
|
||||
expect(findCalls('transactions', 'eq')).toEqual([
|
||||
['company_id', COMPANY],
|
||||
['potential_invoice_id', INV_ID],
|
||||
])
|
||||
})
|
||||
|
||||
it('omits the neq filter when no exceptTransactionId is given', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'invoice',
|
||||
INV_ID,
|
||||
)
|
||||
expect(findCalls('transactions', 'neq')).toEqual([])
|
||||
|
||||
reset()
|
||||
enqueue({ data: null, error: null })
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'invoice',
|
||||
INV_ID,
|
||||
{ exceptTransactionId: null },
|
||||
)
|
||||
expect(findCalls('transactions', 'neq')).toEqual([])
|
||||
})
|
||||
|
||||
it('never widens the write beyond the settled invoice own pointer', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'supplier_invoice',
|
||||
SI_ID,
|
||||
{ exceptTransactionId: TX_ID },
|
||||
)
|
||||
const methods = calls.map((c) => c.method)
|
||||
expect(methods).not.toContain('or')
|
||||
expect(methods).not.toContain('is')
|
||||
expect(methods).not.toContain('in')
|
||||
// Only one table is ever touched.
|
||||
expect([...new Set(calls.map((c) => c.table))]).toEqual(['transactions'])
|
||||
})
|
||||
|
||||
it('logs and resolves when the update fails: a settle must never fail on cleanup', async () => {
|
||||
enqueue({ data: null, error: { message: 'permission denied' } })
|
||||
await expect(
|
||||
clearSettledInvoiceSuggestions(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
'supplier_invoice',
|
||||
SI_ID,
|
||||
),
|
||||
).resolves.toBeUndefined()
|
||||
expect(mockLoggerWarn).toHaveBeenCalledTimes(1)
|
||||
expect(mockLoggerWarn).toHaveBeenCalledWith(
|
||||
'failed to clear settled invoice suggestions',
|
||||
expect.objectContaining({ companyId: COMPANY, invoiceId: SI_ID, reason: 'permission denied' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,11 @@ vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
cancelOrphanedPaymentEntry: vi.fn(),
|
||||
}))
|
||||
// Mocked so it consumes no slot in the queued Supabase mock: the helper's own
|
||||
// query shape is pinned by ./clear-settled-invoice-suggestions.test.ts.
|
||||
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
|
||||
clearSettledInvoiceSuggestions: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
createInvoicePaymentJournalEntry,
|
||||
@@ -21,6 +26,7 @@ import {
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
||||
import { cancelOrphanedPaymentEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
|
||||
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
|
||||
import { settleInvoicePayment } from '@/lib/invoices/settle-invoice-payment'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
@@ -314,6 +320,48 @@ describe('settleInvoicePayment', () => {
|
||||
)
|
||||
})
|
||||
|
||||
// Issue #1259: a fully settled invoice must not keep sibling transactions
|
||||
// pointing at it as a match suggestion.
|
||||
it('retires the settled invoice suggestions when the invoice reaches paid', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: 'inv-1' }] })
|
||||
|
||||
const result = await settleInvoicePayment(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
{ ...BASE_PARAMS, invoice: payableInvoice() },
|
||||
)
|
||||
|
||||
expect(result).toMatchObject({ ok: true, newStatus: 'paid' })
|
||||
expect(vi.mocked(clearSettledInvoiceSuggestions)).toHaveBeenCalledTimes(1)
|
||||
expect(vi.mocked(clearSettledInvoiceSuggestions)).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'invoice',
|
||||
'inv-1',
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: 'inv-1' }] })
|
||||
|
||||
const result = await settleInvoicePayment(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'user-1',
|
||||
{
|
||||
...BASE_PARAMS,
|
||||
paymentAmountInInvoiceCurrency: 500,
|
||||
invoice: payableInvoice(),
|
||||
},
|
||||
)
|
||||
|
||||
expect(result).toMatchObject({ ok: true, newStatus: 'partially_paid' })
|
||||
expect(vi.mocked(clearSettledInvoiceSuggestions)).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('emits invoice.paid with the settled state', async () => {
|
||||
const handler = vi.fn()
|
||||
eventBus.on('invoice.paid', handler)
|
||||
|
||||
@@ -10,6 +10,14 @@ import {
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
// 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 ./clear-settled-invoice-suggestions.test.ts.
|
||||
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
|
||||
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
|
||||
clearSettledInvoiceSuggestions: mockClearSuggestions,
|
||||
}))
|
||||
|
||||
// ============================================================
|
||||
// validateVoucherForSupplierInvoiceLink: happy path + rejects
|
||||
// ============================================================
|
||||
@@ -408,6 +416,16 @@ describe('linkSupplierInvoiceToVoucher', () => {
|
||||
payload: expect.objectContaining({ paymentAmount: 1000, userId: 'user-1' }),
|
||||
}),
|
||||
)
|
||||
|
||||
// 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(
|
||||
supabase,
|
||||
'company-1',
|
||||
'supplier_invoice',
|
||||
invoice.id,
|
||||
)
|
||||
})
|
||||
|
||||
it('still returns success even if the post-link invoice re-fetch is empty (event is best-effort)', async () => {
|
||||
@@ -441,6 +459,9 @@ describe('linkSupplierInvoiceToVoucher', () => {
|
||||
}
|
||||
// Event NOT emitted when re-fetch found nothing
|
||||
expect(emitSpy).not.toHaveBeenCalled()
|
||||
// Issue #1259: a partially paid invoice is still matchable, so the
|
||||
// suggestions pointing at it must survive.
|
||||
expect(mockClearSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -10,6 +10,14 @@ import {
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
// 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 ./clear-settled-invoice-suggestions.test.ts.
|
||||
const { mockClearSuggestions } = vi.hoisted(() => ({ mockClearSuggestions: vi.fn() }))
|
||||
vi.mock('@/lib/invoices/clear-settled-invoice-suggestions', () => ({
|
||||
clearSettledInvoiceSuggestions: mockClearSuggestions,
|
||||
}))
|
||||
|
||||
// ============================================================
|
||||
// validateVoucherForInvoiceLink: happy path + reject codes
|
||||
// ============================================================
|
||||
@@ -651,4 +659,55 @@ describe('linkInvoiceToVoucher', () => {
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.code).toBe('LINK_VOUCHER_DB_ERROR')
|
||||
})
|
||||
|
||||
// Issue #1259: an invoice settled through this path must not leave other
|
||||
// transactions pointing at it as a match suggestion.
|
||||
function enqueueRpcOk(
|
||||
enqueue: (r: { data?: unknown; error?: unknown }) => void,
|
||||
invoiceStatus: 'paid' | 'partially_paid',
|
||||
) {
|
||||
enqueue({
|
||||
data: {
|
||||
ok: true,
|
||||
payment_id: 'pay-1',
|
||||
invoice_status: invoiceStatus,
|
||||
paid_amount: invoiceStatus === 'paid' ? 1000 : 400,
|
||||
remaining_amount: invoiceStatus === 'paid' ? 0 : 600,
|
||||
payment_amount: invoiceStatus === 'paid' ? 1000 : 400,
|
||||
journal_entry_id: 'je-1',
|
||||
currency: 'SEK',
|
||||
payment_date: '2026-06-01',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
// Post-link invoice re-fetch for the event payload.
|
||||
enqueue({ data: null, error: null })
|
||||
}
|
||||
|
||||
it('retires the settled invoice suggestions on a full payment', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueRpcOk(enqueue, 'paid')
|
||||
|
||||
const result = await linkInvoiceToVoucher(supabase as never, 'user-1', 'company-1', {
|
||||
invoiceId: 'inv-1',
|
||||
journalEntryId: 'je-1',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledWith(supabase, 'company-1', 'invoice', 'inv-1')
|
||||
})
|
||||
|
||||
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueRpcOk(enqueue, 'partially_paid')
|
||||
|
||||
const result = await linkInvoiceToVoucher(supabase as never, 'user-1', 'company-1', {
|
||||
invoiceId: 'inv-1',
|
||||
journalEntryId: 'je-1',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(mockClearSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { clearSettledInvoiceSuggestions } from './clear-settled-invoice-suggestions'
|
||||
|
||||
/**
|
||||
* One allocation result as returned by the `match_batch_allocate` RPC
|
||||
* (supabase/migrations/20260601122000_match_batch_allocate_round3_fixes.sql).
|
||||
* Only the fields this cleanup needs are declared; both callers pass richer
|
||||
* rows.
|
||||
*/
|
||||
export interface BatchAllocationResult {
|
||||
kind: 'customer_invoice' | 'supplier_invoice' | string
|
||||
invoice_id?: string | null
|
||||
supplier_invoice_id?: string | null
|
||||
status: 'paid' | 'partially_paid' | string
|
||||
}
|
||||
|
||||
/**
|
||||
* Retire the suggestion pointers at every invoice a samlingsbetalning settled
|
||||
* in full (issue #1259).
|
||||
*
|
||||
* The RPC nulls potential_invoice_id / potential_supplier_invoice_id only on
|
||||
* the source transaction (WHERE id = p_tx_id), so every OTHER transaction of
|
||||
* the company keeps a pointer at an invoice the batch just closed. That row is
|
||||
* excluded here via exceptTransactionId: the RPC already linked it.
|
||||
*
|
||||
* Shared by the two callers of `match_batch_allocate`, the HTTP route
|
||||
* (app/api/transactions/[id]/match-batch/route.ts) and the MCP staged-operation
|
||||
* executor (commitMatchBatchAllocate in lib/pending-operations/commit.ts), so
|
||||
* they cannot drift.
|
||||
*
|
||||
* Partially paid allocations are deliberately left alone: such an invoice is
|
||||
* still matchable, so its suggestions must survive.
|
||||
*
|
||||
* Best effort like the helper it wraps: the batch verifikat is already
|
||||
* committed, so a failed cleanup must never fail the settle.
|
||||
*/
|
||||
export async function clearSettledBatchAllocationSuggestions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
allocations: readonly BatchAllocationResult[],
|
||||
transactionId: string,
|
||||
): Promise<void> {
|
||||
for (const alloc of allocations) {
|
||||
if (alloc.status !== 'paid') continue
|
||||
if (alloc.kind === 'customer_invoice' && alloc.invoice_id) {
|
||||
await clearSettledInvoiceSuggestions(supabase, companyId, 'invoice', alloc.invoice_id, {
|
||||
exceptTransactionId: transactionId,
|
||||
})
|
||||
} else if (alloc.kind === 'supplier_invoice' && alloc.supplier_invoice_id) {
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase,
|
||||
companyId,
|
||||
'supplier_invoice',
|
||||
alloc.supplier_invoice_id,
|
||||
{ exceptTransactionId: transactionId },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('invoices/clear-settled-invoice-suggestions')
|
||||
|
||||
export type SettledInvoiceKind = 'invoice' | 'supplier_invoice'
|
||||
|
||||
/**
|
||||
* Retire the match SUGGESTIONS that point at an invoice which has just been
|
||||
* fully settled.
|
||||
*
|
||||
* potential_invoice_id / potential_supplier_invoice_id are written once, at
|
||||
* bank import (lib/transactions/ingest.ts) or by the retro-match handler, and
|
||||
* nothing revisited them. When one of several identical recurring invoices was
|
||||
* paid off by a DIFFERENT transaction, every other transaction kept a pointer
|
||||
* at a now fully paid invoice. Read paths already refuse to offer such a
|
||||
* candidate (lib/invoices/matchable-statuses.ts, lib/worklist/categories.ts,
|
||||
* the transactions page), but the row still blocks a fresh suggestion: both
|
||||
* re-suggestion scans require the column to be NULL
|
||||
* (lib/bookkeeping/handlers/supplier-invoice-handler.ts and
|
||||
* app/api/transactions/batch-match-invoices/route.ts).
|
||||
*
|
||||
* This complements the read-time revalidation rather than replacing it: the
|
||||
* guards stay the backstop for the settle paths not wired up here.
|
||||
*
|
||||
* Call ONLY when the invoice is fully settled: a partially paid invoice is
|
||||
* still matchable, so its suggestions must survive.
|
||||
*
|
||||
* Best-effort and non-fatal by construction: every caller has already booked a
|
||||
* payment verifikat, so a failed cleanup must never fail the settle.
|
||||
*/
|
||||
export async function clearSettledInvoiceSuggestions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
kind: SettledInvoiceKind,
|
||||
invoiceId: string,
|
||||
options?: { exceptTransactionId?: string | null },
|
||||
): Promise<void> {
|
||||
const column = kind === 'invoice' ? 'potential_invoice_id' : 'potential_supplier_invoice_id'
|
||||
let query = supabase
|
||||
.from('transactions')
|
||||
.update({ [column]: null })
|
||||
// company_id is defense in depth: service-role callers have no RLS.
|
||||
.eq('company_id', companyId)
|
||||
// Never widen: only this invoice's own pointer, never any other hint and
|
||||
// never the confirmed link columns (invoice_id / supplier_invoice_id).
|
||||
.eq(column, invoiceId)
|
||||
if (options?.exceptTransactionId) {
|
||||
query = query.neq('id', options.exceptTransactionId)
|
||||
}
|
||||
const { error } = await query
|
||||
if (error) {
|
||||
log.warn('failed to clear settled invoice suggestions', {
|
||||
companyId,
|
||||
kind,
|
||||
invoiceId,
|
||||
reason: error.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { resolveInvoicePaymentSourceType } from '@/lib/bookkeeping/propose-payme
|
||||
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
|
||||
import { cancelOrphanedPaymentEntry } from '@/lib/bookkeeping/cancel-orphaned-entry'
|
||||
import { planInvoicePaymentForLines } from '@/lib/invoices/apply-invoice-payment'
|
||||
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { CreateJournalEntryInput, Customer, EntityType, Invoice } from '@/types'
|
||||
|
||||
@@ -285,6 +286,13 @@ export async function settleInvoicePayment(
|
||||
return { ok: false, code: 'INVOICE_PAID_RACE' }
|
||||
}
|
||||
|
||||
// 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(supabase, companyId, 'invoice', invoice.id)
|
||||
}
|
||||
|
||||
// Notify subscribers: invoice.paid fans out to registered webhooks and the
|
||||
// Stripe extension's link-deactivation handler. Best-effort: the payment is
|
||||
// already committed, so an emit failure must not fail the operation.
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
customerNameMatches,
|
||||
} from './invoice-matching'
|
||||
import { autoReconcileTransactionForLinkedVoucher } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { clearSettledInvoiceSuggestions } from './clear-settled-invoice-suggestions'
|
||||
import { documentCurrency, ledgerLineSideAmountIn } from '@/lib/bookkeeping/ledger-line-amount'
|
||||
import type { SupplierInvoice, Supplier } from '@/types'
|
||||
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
|
||||
@@ -701,6 +702,19 @@ export async function linkSupplierInvoiceToVoucher(
|
||||
})
|
||||
}
|
||||
|
||||
// The invoice is settled, so every transaction still carrying a suggestion
|
||||
// pointer at it is dead: retire them (issue #1259). No exceptTransactionId:
|
||||
// the reconciled row (if any) has already had its own hint cleared by the
|
||||
// auto-reconcile tag update, so nothing here needs preserving.
|
||||
if (result.invoice_status === 'paid') {
|
||||
await clearSettledInvoiceSuggestions(
|
||||
supabase,
|
||||
companyId,
|
||||
'supplier_invoice',
|
||||
params.supplierInvoiceId,
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
customerNameMatches,
|
||||
} from './invoice-matching'
|
||||
import { autoReconcileTransactionForLinkedVoucher } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { clearSettledInvoiceSuggestions } from './clear-settled-invoice-suggestions'
|
||||
import { documentCurrency, ledgerLineSideAmountIn } from '@/lib/bookkeeping/ledger-line-amount'
|
||||
import type { Invoice, Customer } from '@/types'
|
||||
|
||||
@@ -804,6 +805,14 @@ export async function linkInvoiceToVoucher(
|
||||
})
|
||||
}
|
||||
|
||||
// The invoice is settled, so every transaction still carrying a suggestion
|
||||
// pointer at it is dead: retire them (issue #1259). No exceptTransactionId:
|
||||
// the reconciled row (if any) has already had its own hint cleared by the
|
||||
// auto-reconcile tag update, so nothing here needs preserving.
|
||||
if (rpc.invoice_status === 'paid') {
|
||||
await clearSettledInvoiceSuggestions(supabase, companyId, 'invoice', params.invoiceId)
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
|
||||
@@ -34,6 +34,14 @@ vi.mock('@/lib/invoices/duplicate-payment-candidates', () => ({
|
||||
findDuplicatePaymentCandidatesForInvoice: (...args: unknown[]) => mockFindDupPayments(...args),
|
||||
}))
|
||||
|
||||
// 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,
|
||||
}))
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
@@ -135,5 +143,16 @@ describe('commitPendingOperation: mark_invoice_paid state + invoice.paid', () =>
|
||||
invoice: expect.objectContaining({ id: 'inv-1', status: 'paid', remaining_amount: 0, paid_amount: 525 }),
|
||||
}),
|
||||
)
|
||||
|
||||
// Issue #1259: the invoice is settled, so no transaction may keep pointing
|
||||
// at it as a match suggestion. This flow is not driven by a bank
|
||||
// transaction, so nothing is excluded.
|
||||
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledWith(supabase, 'company-1', 'invoice', 'inv-1')
|
||||
})
|
||||
|
||||
// No partial-payment counterpart here: this executor always settles the full
|
||||
// remaining balance (no custom amount param), so newStatus is always 'paid'.
|
||||
// The partial case is pinned on the surfaces that can produce it, e.g.
|
||||
// lib/invoices/__tests__/settle-invoice-payment.test.ts.
|
||||
})
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Suggestion-pointer cleanup for the agent/MCP batch-allocation commit path
|
||||
* (`commitMatchBatchAllocate` in lib/pending-operations/commit.ts), the second
|
||||
* caller of the `match_batch_allocate` RPC next to
|
||||
* POST /api/transactions/[id]/match-batch.
|
||||
*
|
||||
* Issue #1259: the RPC nulls potential_invoice_id /
|
||||
* potential_supplier_invoice_id only on the source transaction
|
||||
* (WHERE id = p_tx_id), so every OTHER transaction of the company keeps a
|
||||
* pointer at an invoice the samlingsbetalning just closed. Both callers run the
|
||||
* same shared cleanup (lib/invoices/clear-settled-batch-allocations.ts); the
|
||||
* HTTP twin has the same test shape in
|
||||
* app/api/transactions/[id]/match-batch/__tests__/route.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
// 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,
|
||||
}))
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
const TX_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const INV_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const SI_ID = '33333333-3333-4333-8333-333333333333'
|
||||
const SI_PARTIAL_ID = '44444444-4444-4444-8444-444444444444'
|
||||
|
||||
function makePendingOp(params: Record<string, unknown>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'match_batch_allocate',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params,
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'medium',
|
||||
created_at: '2026-05-03T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-05-03T00:00:00Z',
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
const REQUEST_ALLOCATIONS = [
|
||||
{ kind: 'supplier_invoice', supplier_invoice_id: SI_ID, amount: 1000 },
|
||||
{ kind: 'supplier_invoice', supplier_invoice_id: SI_PARTIAL_ID, amount: 400 },
|
||||
]
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: match_batch_allocate suggestion cleanup', () => {
|
||||
it('retires suggestions only for the allocations that settled in full', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({
|
||||
data: {
|
||||
ok: true,
|
||||
journal_entry_id: 'je-batch-1',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 42,
|
||||
tx_id: TX_ID,
|
||||
allocations: [
|
||||
{
|
||||
kind: 'supplier_invoice',
|
||||
supplier_invoice_id: SI_ID,
|
||||
payment_id: 'sip-1',
|
||||
status: 'paid',
|
||||
paid_amount: 1000,
|
||||
remaining_amount: 0,
|
||||
amount: 1000,
|
||||
},
|
||||
{
|
||||
kind: 'supplier_invoice',
|
||||
supplier_invoice_id: SI_PARTIAL_ID,
|
||||
payment_id: 'sip-2',
|
||||
status: 'partially_paid',
|
||||
paid_amount: 400,
|
||||
remaining_amount: 600,
|
||||
amount: 400,
|
||||
},
|
||||
],
|
||||
total_allocated: 1400,
|
||||
leftover: 0,
|
||||
},
|
||||
error: null,
|
||||
}) // match_batch_allocate RPC
|
||||
enqueue({ data: null, error: null }) // dispatcher finalize update
|
||||
|
||||
const op = makePendingOp({ transaction_id: TX_ID, allocations: REQUEST_ALLOCATIONS })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
// A partially paid invoice is still matchable, so its suggestions survive.
|
||||
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'supplier_invoice',
|
||||
SI_ID,
|
||||
{ exceptTransactionId: TX_ID },
|
||||
)
|
||||
})
|
||||
|
||||
it('retires a fully settled customer invoice allocation', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({
|
||||
data: {
|
||||
ok: true,
|
||||
journal_entry_id: 'je-batch-2',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 43,
|
||||
tx_id: TX_ID,
|
||||
allocations: [
|
||||
{
|
||||
kind: 'customer_invoice',
|
||||
invoice_id: INV_ID,
|
||||
payment_id: 'ip-1',
|
||||
status: 'paid',
|
||||
paid_amount: 1000,
|
||||
remaining_amount: 0,
|
||||
amount: 1000,
|
||||
},
|
||||
],
|
||||
total_allocated: 1000,
|
||||
leftover: 0,
|
||||
},
|
||||
error: null,
|
||||
}) // match_batch_allocate RPC
|
||||
enqueue({ data: null, error: null }) // dispatcher finalize update
|
||||
|
||||
const op = makePendingOp({
|
||||
transaction_id: TX_ID,
|
||||
allocations: [{ kind: 'customer_invoice', invoice_id: INV_ID, amount: 1000 }],
|
||||
})
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledWith(supabase, 'company-1', 'invoice', INV_ID, {
|
||||
exceptTransactionId: TX_ID,
|
||||
})
|
||||
})
|
||||
|
||||
it('retires nothing when the RPC reports a structured failure', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { ok: false, code: 'BATCH_OVER_ALLOCATED' }, error: null }) // RPC
|
||||
enqueue({ data: null, error: null }) // dispatcher rejection update
|
||||
|
||||
const op = makePendingOp({ transaction_id: TX_ID, allocations: REQUEST_ALLOCATIONS })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(mockClearSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -27,6 +27,14 @@ vi.mock('@/lib/bookkeeping/invoice-entries', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
// 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,
|
||||
}))
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
@@ -149,6 +157,58 @@ describe('commitPendingOperation: match_transaction_invoice settlement account r
|
||||
'1940',
|
||||
)
|
||||
expect(mockCreateCashEntry).not.toHaveBeenCalled()
|
||||
// Issue #1259: the invoice is settled, so every OTHER transaction still
|
||||
// carrying a suggestion pointer at it is retired; this op's own row is
|
||||
// cleared by the link update.
|
||||
expect(mockClearSuggestions).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearSuggestions).toHaveBeenCalledWith(supabase, 'company-1', 'invoice', 'inv-1', {
|
||||
exceptTransactionId: 'tx-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves the suggestions alone on a partial payment: the invoice is still matchable', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'tx-1',
|
||||
company_id: 'company-1',
|
||||
amount: 5000,
|
||||
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-2026001',
|
||||
status: 'sent',
|
||||
total: 12500,
|
||||
remaining_amount: 12500,
|
||||
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: [{ id: 'inv-1' }], error: null }) // invoice CAS update
|
||||
enqueue({ data: null, 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(result.data).toMatchObject({ invoice_status: 'partially_paid' })
|
||||
expect(mockClearSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('defaults to 1930 when the transaction has no linked cash account', async () => {
|
||||
|
||||
@@ -57,6 +57,11 @@ import { linkInvoiceToVoucher } from '@/lib/invoices/voucher-matching'
|
||||
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
|
||||
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
|
||||
import { linkSupplierInvoiceToVoucher } from '@/lib/invoices/supplier-voucher-matching'
|
||||
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
|
||||
import {
|
||||
clearSettledBatchAllocationSuggestions,
|
||||
type BatchAllocationResult,
|
||||
} from '@/lib/invoices/clear-settled-batch-allocations'
|
||||
import { linkTransactionToJournalEntry } from '@/lib/transactions/link-journal-entry'
|
||||
import { getErrorEntry } from '@/lib/errors/structured-errors'
|
||||
import { parseSIEFile } from '@/lib/import/sie-parser'
|
||||
@@ -2051,6 +2056,13 @@ async function commitMarkInvoicePaid(
|
||||
}
|
||||
}
|
||||
|
||||
// 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(supabase, companyId, 'invoice', invoiceId)
|
||||
}
|
||||
|
||||
// Notify subscribers: invoice.paid fans out to registered webhooks
|
||||
// (lib/webhooks/handler.ts). Best-effort: the payment is already committed,
|
||||
// so an emit failure must not fail the operation. Parity with the v1 and
|
||||
@@ -2600,6 +2612,15 @@ async function commitMatchTransactionInvoice(
|
||||
notes: paymentNotes,
|
||||
})
|
||||
|
||||
// The invoice is now settled, so every OTHER transaction still carrying a
|
||||
// suggestion pointer at it is dead: retire them (issue #1259). This
|
||||
// operation's own row is cleared by the update just below.
|
||||
if (isFullyPaid) {
|
||||
await clearSettledInvoiceSuggestions(supabase, companyId, 'invoice', invoiceId, {
|
||||
exceptTransactionId: transactionId,
|
||||
})
|
||||
}
|
||||
|
||||
await supabase
|
||||
.from('transactions')
|
||||
.update({
|
||||
@@ -5052,7 +5073,13 @@ async function commitMatchBatchAllocate(
|
||||
})
|
||||
return { error: error.message || 'Database error', status: 500 }
|
||||
}
|
||||
const result = data as { ok: boolean; code?: string; details?: unknown; journal_entry_id?: string }
|
||||
const result = data as {
|
||||
ok: boolean
|
||||
code?: string
|
||||
details?: unknown
|
||||
journal_entry_id?: string
|
||||
allocations?: BatchAllocationResult[]
|
||||
}
|
||||
if (!result || !result.ok) {
|
||||
return {
|
||||
error: result?.code || 'match_batch_allocate failed',
|
||||
@@ -5060,6 +5087,12 @@ async function commitMatchBatchAllocate(
|
||||
data: result?.details as Record<string, unknown> | undefined,
|
||||
}
|
||||
}
|
||||
// Every allocation the RPC settled in full retires its suggestion pointer
|
||||
// from the company's OTHER transactions (issue #1259): the RPC only nulls
|
||||
// them on the source tx. Same helper as the HTTP twin
|
||||
// (app/api/transactions/[id]/match-batch/route.ts) so the two cannot drift.
|
||||
await clearSettledBatchAllocationSuggestions(supabase, companyId, result.allocations ?? [], txId)
|
||||
|
||||
// Structured audit-trail entry on success (compliance-swarm V16). Tx
|
||||
// count + JE id + the source tx id only: no amounts, no
|
||||
// counterparty identifiers, no descriptions. txId is included
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { clearSettledInvoiceSuggestions } from '@/lib/invoices/clear-settled-invoice-suggestions'
|
||||
import { logMatchEvent } from '@/lib/invoices/match-log'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Invoice, Transaction } from '@/types'
|
||||
@@ -403,6 +404,14 @@ export async function linkTransactionToJournalEntry(
|
||||
await rollbackTxLink('invoice_payments insert failed')
|
||||
return { ok: false, code: 'MATCH_INVOICE_RECORD_PAYMENT_FAILED' }
|
||||
}
|
||||
|
||||
// The invoice is settled, so every transaction still carrying a suggestion
|
||||
// pointer at it is dead: retire them (issue #1259). No exceptTransactionId
|
||||
// needed: this row's own hints were already nulled by the tx update above,
|
||||
// so the invoice-id filter no longer selects it.
|
||||
if (isFullyPaid) {
|
||||
await clearSettledInvoiceSuggestions(supabase, companyId, 'invoice', invoiceId)
|
||||
}
|
||||
}
|
||||
|
||||
logMatchEvent(supabase, userId, transactionId, 'linked_to_existing_voucher', {
|
||||
|
||||
@@ -109,7 +109,6 @@ describe('countVerifikatMissingDocument', () => {
|
||||
|
||||
describe('simple head counts', () => {
|
||||
it.each([
|
||||
['countSuggestedMatches', countSuggestedMatches, 'transactions'],
|
||||
['countSupplierInvoicesAwaitingApproval', countSupplierInvoicesAwaitingApproval, 'supplier_invoices'],
|
||||
['countOverdueInvoices', countOverdueInvoices, 'invoices'],
|
||||
['countDeadlinesNeedingAction', countDeadlinesNeedingAction, 'deadlines'],
|
||||
@@ -121,6 +120,76 @@ describe('simple head counts', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// Issue #1259: the badge delegates to listSuggestedMatches so it can never
|
||||
// claim a number the list refuses to render. A raw head count over the hint
|
||||
// columns counted pointers at invoices settled by a different transaction.
|
||||
describe('countSuggestedMatches', () => {
|
||||
it('counts only hints whose candidate is still matchable', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: 'tx-1',
|
||||
date: '2026-06-01',
|
||||
description: 'ICA',
|
||||
amount: 423,
|
||||
currency: 'SEK',
|
||||
potential_invoice_id: 'inv-1',
|
||||
potential_supplier_invoice_id: null,
|
||||
},
|
||||
{
|
||||
id: 'tx-2',
|
||||
date: '2026-05-30',
|
||||
description: 'TELIA',
|
||||
amount: -549,
|
||||
currency: 'SEK',
|
||||
potential_invoice_id: null,
|
||||
potential_supplier_invoice_id: 'sinv-paid',
|
||||
},
|
||||
],
|
||||
})
|
||||
// inv-1 is still open; sinv-paid was settled by another transaction, so the
|
||||
// status/remaining filters exclude it server-side.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'inv-1', invoice_number: 'F-1', total: 423, customer: { name: 'Kund AB' } },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
await expect(countSuggestedMatches(supabase, COMPANY)).resolves.toBe(1)
|
||||
expect(mockSupabase.from).toHaveBeenCalledWith('transactions')
|
||||
})
|
||||
|
||||
it('returns 0 when the only hint points at an invoice settled elsewhere', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: 'tx-1',
|
||||
date: '2026-06-01',
|
||||
description: 'MONTHLY FEE',
|
||||
amount: -549,
|
||||
currency: 'SEK',
|
||||
potential_invoice_id: null,
|
||||
potential_supplier_invoice_id: 'sinv-paid',
|
||||
},
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
await expect(countSuggestedMatches(supabase, COMPANY)).resolves.toBe(0)
|
||||
})
|
||||
|
||||
it('soft-fails to 0 on query error', async () => {
|
||||
enqueue({ error: { message: 'boom' } })
|
||||
await expect(countSuggestedMatches(supabase, COMPANY)).resolves.toBe(0)
|
||||
})
|
||||
|
||||
it('clamps the scan so the badge cannot walk an unbounded hint set', async () => {
|
||||
enqueue({ data: [] })
|
||||
await countSuggestedMatches(supabase, COMPANY)
|
||||
expect(findCall('transactions', 'limit')).toEqual([200])
|
||||
})
|
||||
})
|
||||
|
||||
describe('listSuggestedMatches', () => {
|
||||
it('maps invoice and supplier-invoice hints to confirmable rows', async () => {
|
||||
enqueue({
|
||||
@@ -282,4 +351,65 @@ describe('listSuggestedMatches', () => {
|
||||
|
||||
await expect(listSuggestedMatches(supabase, COMPANY)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
// The badge scans up to 200 hints (SUGGESTED_MATCH_SCAN_CAP), past the 150
|
||||
// ids per .in() that countInboxDocuments already chunks for: PostgREST puts
|
||||
// them in the GET query string, and a 414 would come back as a silent 0.
|
||||
it('chunks the candidate id list at 150 ids per lookup', async () => {
|
||||
const txRows = Array.from({ length: 151 }, (_, i) => ({
|
||||
id: `tx-${i}`,
|
||||
date: '2026-06-01',
|
||||
description: 'X',
|
||||
amount: 100,
|
||||
currency: 'SEK',
|
||||
potential_invoice_id: `inv-${i}`,
|
||||
potential_supplier_invoice_id: null,
|
||||
}))
|
||||
enqueue({ data: txRows })
|
||||
enqueue({ data: [] }) // chunk 1
|
||||
enqueue({ data: [] }) // chunk 2
|
||||
|
||||
await listSuggestedMatches(supabase, COMPANY, 200)
|
||||
|
||||
const idFilters = findCalls('invoices', 'in').filter(([col]) => col === 'id')
|
||||
expect(idFilters).toHaveLength(2)
|
||||
expect((idFilters[0][1] as string[]).length).toBe(150)
|
||||
expect((idFilters[1][1] as string[]).length).toBe(1)
|
||||
})
|
||||
|
||||
// Previously the candidate results were consumed without checking .error, so
|
||||
// a 414 / 500 / RLS change yielded empty maps, an empty list and a zero badge
|
||||
// with nothing logged.
|
||||
it('returns [] and logs with companyId when a candidate lookup fails', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: 'tx-1',
|
||||
date: '2026-06-01',
|
||||
description: 'X',
|
||||
amount: 100,
|
||||
currency: 'SEK',
|
||||
potential_invoice_id: 'inv-1',
|
||||
potential_supplier_invoice_id: null,
|
||||
},
|
||||
],
|
||||
})
|
||||
enqueue({ error: { message: 'boom' } })
|
||||
|
||||
await expect(listSuggestedMatches(supabase, COMPANY)).resolves.toEqual([])
|
||||
expect(consoleError).toHaveBeenCalled()
|
||||
const logged = consoleError.mock.calls.map((c) => String(c[0])).join('\n')
|
||||
expect(logged).toContain('candidate lookup failed')
|
||||
expect(logged).toContain(COMPANY)
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('logs the tenant with the transaction query failure too', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
enqueue({ error: { message: 'boom' } })
|
||||
await expect(listSuggestedMatches(supabase, COMPANY)).resolves.toEqual([])
|
||||
expect(String(consoleError.mock.calls[0]?.[0])).toContain(COMPANY)
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,9 +12,10 @@ import {
|
||||
} from './categories'
|
||||
|
||||
/**
|
||||
* All worklist counts in one round-trip burst. Every count is a cheap
|
||||
* head-only query (categories.ts) and individually soft-fails to 0, so this
|
||||
* is safe to call from layouts and server components on every render.
|
||||
* All worklist counts in one round-trip burst. Each count is a bounded query
|
||||
* (mostly head-only; suggested_match revalidates its candidates, see
|
||||
* categories.ts) and individually soft-fails to 0, so this is safe to call
|
||||
* from layouts and server components on every render.
|
||||
*
|
||||
* `total` is the number of distinct actionable items: suggested_match is a
|
||||
* fast path over transactions already counted in book_transaction, so it is
|
||||
|
||||
+95
-49
@@ -129,20 +129,29 @@ export async function countInboxDocuments(
|
||||
const SUGGESTED_MATCH_OR =
|
||||
'potential_invoice_id.not.is.null,potential_supplier_invoice_id.not.is.null'
|
||||
|
||||
/** Unbooked transactions with an invoice/supplier-invoice match hint. */
|
||||
/**
|
||||
* Cap on the hint scan behind countSuggestedMatches; clamps like
|
||||
* INBOX_SCAN_CAP. Above IN_CLAUSE_CHUNK on purpose: the candidate lookups it
|
||||
* feeds are chunked (fetchCandidatesChunked), so the URL length stays bounded
|
||||
* regardless of this number.
|
||||
*/
|
||||
const SUGGESTED_MATCH_SCAN_CAP = 200
|
||||
|
||||
/**
|
||||
* Unbooked transactions with a still-actionable invoice/supplier-invoice match
|
||||
* hint.
|
||||
*
|
||||
* Delegates to listSuggestedMatches so the badge can never claim a number the
|
||||
* list cannot render: a head count over the raw hint columns still counts a
|
||||
* pointer at an invoice settled elsewhere (issue #1259), which is exactly the
|
||||
* divergence lib/worklist exists to prevent (see types.ts).
|
||||
*/
|
||||
export async function countSuggestedMatches(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<number> {
|
||||
const { count, error } = await supabase
|
||||
.from('transactions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.is('is_business', null)
|
||||
.eq('is_ignored', false)
|
||||
.or(SUGGESTED_MATCH_OR)
|
||||
if (error) return logAndZero('suggested_match', companyId, error)
|
||||
return count ?? 0
|
||||
const matches = await listSuggestedMatches(supabase, companyId, SUGGESTED_MATCH_SCAN_CAP)
|
||||
return matches.length
|
||||
}
|
||||
|
||||
/** Supplier invoices awaiting approval ("attestera"). */
|
||||
@@ -259,6 +268,37 @@ interface SuggestedMatchTxRow {
|
||||
potential_supplier_invoice_id: string | null
|
||||
}
|
||||
|
||||
type CandidateRow = {
|
||||
id: string
|
||||
invoice_number?: string | null
|
||||
supplier_invoice_number?: string | null
|
||||
total: number | null
|
||||
customer?: { name: string | null } | null
|
||||
supplier?: { name: string | null } | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one candidate lookup over a chunked id list. PostgREST serialises .in()
|
||||
* into the GET query string, so a long list can push the URL past proxy limits
|
||||
* (HTTP 414) exactly as countInboxDocuments guards against. The first error
|
||||
* short-circuits: a partial candidate set would silently drop rows from the
|
||||
* list and, through countSuggestedMatches, from the badge.
|
||||
*/
|
||||
async function fetchCandidatesChunked(
|
||||
ids: string[],
|
||||
runChunk: (
|
||||
chunk: string[],
|
||||
) => PromiseLike<{ data: unknown; error: { message?: string } | null }>,
|
||||
): Promise<{ rows: CandidateRow[]; error: { message?: string } | null }> {
|
||||
const rows: CandidateRow[] = []
|
||||
for (let i = 0; i < ids.length; i += IN_CLAUSE_CHUNK) {
|
||||
const { data, error } = await runChunk(ids.slice(i, i + IN_CLAUSE_CHUNK))
|
||||
if (error) return { rows: [], error }
|
||||
rows.push(...((data ?? []) as unknown as CandidateRow[]))
|
||||
}
|
||||
return { rows, error: null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggested transaction↔invoice matches with enough candidate context for a
|
||||
* one-click confirm row. Confirm endpoints:
|
||||
@@ -272,9 +312,11 @@ interface SuggestedMatchTxRow {
|
||||
* that has since been paid would otherwise render a one-click confirm row
|
||||
* whose endpoint can only answer ALREADY_PAID.
|
||||
*
|
||||
* Revalidation is done here, at read time, rather than by cleaning up sibling
|
||||
* pointers on settle: the settle paths are many and a missed one leaks, while
|
||||
* this check covers every route into the list.
|
||||
* Revalidation stays here, at read time, even though the high-traffic settle
|
||||
* paths now also retire sibling pointers
|
||||
* (lib/invoices/clear-settled-invoice-suggestions.ts, issue #1259): the settle
|
||||
* paths are many and a missed one leaks, while this check covers every route
|
||||
* into the list.
|
||||
*/
|
||||
export async function listSuggestedMatches(
|
||||
supabase: SupabaseClient,
|
||||
@@ -293,51 +335,55 @@ export async function listSuggestedMatches(
|
||||
.order('date', { ascending: false })
|
||||
.limit(limit)
|
||||
if (error) {
|
||||
log.error('worklist listSuggestedMatches failed', { reason: error.message })
|
||||
// companyId matches logAndZero's convention so repeated failures can be
|
||||
// correlated to a tenant in monitoring.
|
||||
log.error('worklist listSuggestedMatches failed', { companyId, reason: error.message })
|
||||
return []
|
||||
}
|
||||
|
||||
const txs = (txRows ?? []) as SuggestedMatchTxRow[]
|
||||
const invoiceIds = txs.map((t) => t.potential_invoice_id).filter((x): x is string => !!x)
|
||||
const supplierInvoiceIds = txs
|
||||
.map((t) => t.potential_supplier_invoice_id)
|
||||
.filter((x): x is string => !!x)
|
||||
const invoiceIds = [
|
||||
...new Set(txs.map((t) => t.potential_invoice_id).filter((x): x is string => !!x)),
|
||||
]
|
||||
const supplierInvoiceIds = [
|
||||
...new Set(txs.map((t) => t.potential_supplier_invoice_id).filter((x): x is string => !!x)),
|
||||
]
|
||||
|
||||
const [invoiceRes, supplierRes] = await Promise.all([
|
||||
invoiceIds.length > 0
|
||||
? supabase
|
||||
.from('invoices')
|
||||
.select('id, invoice_number, total, customer:customers(name)')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', invoiceIds)
|
||||
.in('status', [...MATCHABLE_INVOICE_STATUSES])
|
||||
.gt('remaining_amount', 0)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
supplierInvoiceIds.length > 0
|
||||
? supabase
|
||||
.from('supplier_invoices')
|
||||
.select('id, supplier_invoice_number, total, supplier:suppliers(name)')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', supplierInvoiceIds)
|
||||
.in('status', [...MATCHABLE_SUPPLIER_INVOICE_STATUSES])
|
||||
.gt('remaining_amount', 0)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
fetchCandidatesChunked(invoiceIds, (chunk) =>
|
||||
supabase
|
||||
.from('invoices')
|
||||
.select('id, invoice_number, total, customer:customers(name)')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', chunk)
|
||||
.in('status', [...MATCHABLE_INVOICE_STATUSES])
|
||||
.gt('remaining_amount', 0),
|
||||
),
|
||||
fetchCandidatesChunked(supplierInvoiceIds, (chunk) =>
|
||||
supabase
|
||||
.from('supplier_invoices')
|
||||
.select('id, supplier_invoice_number, total, supplier:suppliers(name)')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', chunk)
|
||||
.in('status', [...MATCHABLE_SUPPLIER_INVOICE_STATUSES])
|
||||
.gt('remaining_amount', 0),
|
||||
),
|
||||
])
|
||||
|
||||
type CandidateRow = {
|
||||
id: string
|
||||
invoice_number?: string | null
|
||||
supplier_invoice_number?: string | null
|
||||
total: number | null
|
||||
customer?: { name: string | null } | null
|
||||
supplier?: { name: string | null } | null
|
||||
// A failed candidate lookup must not pass for "nothing is matchable": that
|
||||
// would render an empty list and, through countSuggestedMatches, a silent
|
||||
// zero badge. Log it (with companyId) and bail, same as the tx query above.
|
||||
const candidateError = invoiceRes.error ?? supplierRes.error
|
||||
if (candidateError) {
|
||||
log.error('worklist listSuggestedMatches candidate lookup failed', {
|
||||
companyId,
|
||||
reason: candidateError.message,
|
||||
})
|
||||
return []
|
||||
}
|
||||
const invoiceById = new Map<string, CandidateRow>(
|
||||
((invoiceRes.data ?? []) as unknown as CandidateRow[]).map((r) => [r.id, r]),
|
||||
)
|
||||
const supplierById = new Map<string, CandidateRow>(
|
||||
((supplierRes.data ?? []) as unknown as CandidateRow[]).map((r) => [r.id, r]),
|
||||
)
|
||||
|
||||
const invoiceById = new Map<string, CandidateRow>(invoiceRes.rows.map((r) => [r.id, r]))
|
||||
const supplierById = new Map<string, CandidateRow>(supplierRes.rows.map((r) => [r.id, r]))
|
||||
|
||||
const matches: SuggestedMatch[] = []
|
||||
for (const tx of txs) {
|
||||
|
||||
Reference in New Issue
Block a user