fix(supplier-invoices): duplicate-payment guard matches abbreviated bank text and shares one detector with the customer side (#2299) (#2345)
* fix(supplier-invoices): duplicate-payment guard matches abbreviated bank text and shares one detector with the customer side The mark-paid guard probed merchant_name for the FULL supplier name, so the row that paid Hi3G Access AB (bank text "HI3G", merchant_name empty) never matched and the payment was booked twice (#2299). - counterpartyNeedle(): first distinctive token of the name (alnum, legal forms dropped, >= 2 chars so initialisms like SJ and 3M survive), probed on merchant_name OR description in one .or() per currency sweep; the alnum shape is what makes the DSL interpolation safe. - findDuplicatePaymentCandidatesForSupplierInvoice() beside the customer detector; both share the sweep and the scorer. The dashboard route's inline copy is deleted; the v1 supplier mark-paid door gets the guard it lacked. - New match_reason already_booked (row already carries a verifikat, booked straight from the bank side): ranked first, carries journal_entry_id, and the dialogs, MCP path and pending-operation commit word the remedy as a rattelse rather than "link it". - Customer side gets the same token prefilter and classification. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6 * test(invoices): align customer mark-paid queued mocks with the one-probe duplicate guard The customer detector now issues one .or() counterparty probe per currency sweep instead of two ILIKE queries, so every queued answer after the guard was consumed one step early: the aggregate-sweep [] became company_settings, the settings row hit the entry builder, and two tests saw 500 / the wrong voucher id. Each guard block now enqueues one probe plus the aggregate sweep; the 409 tests drop the second-probe entry that is no longer read. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6 * fix(invoices): one logic expression per duplicate-payment sweep, never two or= params The sweep chain carried two .or() calls (currency clause, then name probe). postgrest-js appends a query parameter per call, so the client sent or= twice, and whether PostgREST ANDs a repeated key was never proven in this repo; had it kept one, the currency predicate would be gone and foreign rows banded against a kronor figure. counterpartySweepLogic() now nests both groups under one and() inside a single top-level or(): and(or(<currency>),or(merchant_name.ilike.*x*, description.ilike.*x*)). The sweep issues exactly one .or() per currency. Proof at three levels: unit tests pin the helper's string; a fake-fetch test runs the real postgrest-js builder and asserts exactly one or= search param per request; a tool-pg test seeds right-currency+hit, wrong-currency+hit (with an amount_sek that would pass every JS check) and right-currency+miss rows against a real PostgREST and asserts, for both detectors and both sweeps, that only the first comes back, from PostgREST's own response. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6 * fix(invoices): name storno as the already_booked remedy, never "makulera" A posted verifikat is never deleted; it is corrected by a storno entry (BFL 5 kap 5 §). The already_booked remedy text in the error catalogue, the MCP and pending-operation messages and both UI descriptions now say so: "vänd en av verifikationerna med storno och koppla underlaget till den som blir kvar" / "reverse one of the two vouchers with a storno entry and attach the underlag to the remaining one". Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
82d25b7dee
commit
272d19b287
+97
-2
@@ -1,10 +1,14 @@
|
||||
/**
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* The duplicate-payment guard (issue #2299): this door had none, so an agent
|
||||
* could book a payment the bank feed already carried. Same shared detector
|
||||
* as the dashboard route.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
@@ -233,4 +237,95 @@ describe('POST /api/v1/companies/:companyId/supplier-invoices/:id/mark-paid', ()
|
||||
expect(body.data.status).toBe('partially_paid')
|
||||
expect(mockClearSuggestions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
const hi3gRow = {
|
||||
id: 'tx-hi3g',
|
||||
date: '2026-05-11',
|
||||
amount: -1000,
|
||||
description: 'HI3G',
|
||||
merchant_name: null,
|
||||
reference: null,
|
||||
journal_entry_id: null,
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
}
|
||||
const hi3gSI = {
|
||||
...APPROVED_SI,
|
||||
supplier: { ...APPROVED_SI.supplier, name: 'Hi3G Access AB' },
|
||||
}
|
||||
|
||||
it('returns 409 SI_PAID_LIKELY_DUPLICATE when an outbound bank row carries the abbreviated supplier text (issue #2299)', async () => {
|
||||
const calls: RecordedCall[] = []
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
supplier_invoices: { data: hi3gSI, error: null },
|
||||
company_settings: { data: { accounting_method: 'accrual' }, error: null },
|
||||
transactions: { data: [hi3gRow], error: null },
|
||||
}, calls),
|
||||
)
|
||||
|
||||
const res = await markPaid(makeRequest({ payment_date: '2026-05-12' }), detailParams())
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('SI_PAID_LIKELY_DUPLICATE')
|
||||
expect(body.error.details.candidates.map((c: { id: string; match_reason: string }) => [c.id, c.match_reason]))
|
||||
.toEqual([['tx-hi3g', 'name_amount_fuzzy']])
|
||||
// Nothing was booked and nothing was flipped.
|
||||
expect(calls.some((c) => c.table === 'supplier_invoices' && c.method === 'update')).toBe(false)
|
||||
expect(calls.some((c) => c.table === 'supplier_invoice_payments' && c.method === 'insert')).toBe(false)
|
||||
// The probe is the first distinctive token on both name columns, nested
|
||||
// with the currency clause into ONE .or(), outbound.
|
||||
const sweep = calls.filter((c) => c.table === 'transactions')
|
||||
expect(sweep.filter((c) => c.method === 'or').map((c) => c.args)).toEqual([[
|
||||
'and(or(currency.is.null,currency.eq.SEK),or(merchant_name.ilike.*hi3g*,description.ilike.*hi3g*))',
|
||||
]])
|
||||
expect(sweep.map((c) => c.args)).toContainEqual(['amount', 0])
|
||||
})
|
||||
|
||||
it('force: true bypasses the guard and books the payment', async () => {
|
||||
const calls: RecordedCall[] = []
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
supplier_invoices: [
|
||||
{ data: hi3gSI, error: null },
|
||||
{ data: { ...hi3gSI, status: 'paid', paid_amount: 1000, remaining_amount: 0 }, error: null },
|
||||
],
|
||||
company_settings: { data: { accounting_method: 'accrual' }, error: null },
|
||||
transactions: { data: [hi3gRow], error: null },
|
||||
supplier_invoice_payments: { data: null, error: null },
|
||||
}, calls),
|
||||
)
|
||||
|
||||
const res = await markPaid(makeRequest({ payment_date: '2026-05-12', force: true }), detailParams())
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.status).toBe('paid')
|
||||
expect(calls.some((c) => c.table === 'transactions')).toBe(false)
|
||||
})
|
||||
|
||||
it('a partial payment skips the guard: it is an explicit, deliberate action', async () => {
|
||||
const calls: RecordedCall[] = []
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
supplier_invoices: [
|
||||
{ data: hi3gSI, error: null },
|
||||
{ data: { ...hi3gSI, status: 'partially_paid', paid_amount: 400, remaining_amount: 600 }, error: null },
|
||||
],
|
||||
company_settings: { data: { accounting_method: 'accrual' }, error: null },
|
||||
transactions: { data: [hi3gRow], error: null },
|
||||
supplier_invoice_payments: { data: null, error: null },
|
||||
}, calls),
|
||||
)
|
||||
|
||||
const res = await markPaid(makeRequest({ payment_date: '2026-05-12', amount: 400 }), detailParams())
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(calls.some((c) => c.table === 'transactions')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,6 +31,7 @@ import { cashPartialBlockReason } from '@/lib/bookkeeping/booking-mode'
|
||||
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 { findDuplicatePaymentCandidatesForSupplierInvoice } from '@/lib/invoices/duplicate-payment-candidates'
|
||||
import { paidAtFromDate } from '@/lib/invoices/paid-at'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { SupplierInvoice, SupplierInvoiceItem } from '@/types'
|
||||
@@ -68,6 +69,7 @@ registerEndpoint({
|
||||
'exchange_rate_difference (SEK delta vs the booked rate at registration) is required for foreign-currency SIs to book the FX gain/loss to 3960 / 7960. Omitting it on a non-SEK SI under accrual mis-books FX.',
|
||||
'Strict-mode: a JE creation failure ABORTS before the status flip. There is no partial-state recovery banner: retry the call.',
|
||||
'Cash basis (kontantmetoden) recognizes the expense + ingående moms HERE, not at :create.',
|
||||
'Duplicate-payment guard: on a full settlement, if a business bank transaction of the same amount around payment_date carries the supplier name (first distinctive token, so abbreviated bank text such as "HI3G" for Hi3G Access AB counts), returns 409 SI_PAID_LIKELY_DUPLICATE with candidate transactions. A candidate with match_reason `already_booked` is a bank row that is ALREADY a verifikat: do not pay the invoice, correct the double booking instead. Retry with `force: true` only after the user confirms, and with a fresh Idempotency-Key (the original is body-hash bound). Also evaluated under dry-run.',
|
||||
],
|
||||
example: {
|
||||
request: { payment_date: '2026-05-13' },
|
||||
@@ -122,6 +124,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
let bodyPaymentDate: string | undefined
|
||||
let exchangeRateDifference: number | undefined
|
||||
let bodyNotes: string | undefined
|
||||
let force = false
|
||||
let customLines:
|
||||
| Array<{ account_number: string; debit_amount: number; credit_amount: number; line_description?: string }>
|
||||
| undefined
|
||||
@@ -133,6 +136,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
exchangeRateDifference = parsed.data.exchange_rate_difference
|
||||
bodyNotes = parsed.data.notes
|
||||
customLines = parsed.data.lines
|
||||
force = parsed.data.force === true
|
||||
}
|
||||
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
@@ -161,7 +165,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
.from('supplier_invoices')
|
||||
.select(`
|
||||
id, supplier_id, status, currency, exchange_rate, total, paid_amount, remaining_amount,
|
||||
supplier_invoice_number, arrival_number, invoice_date, vat_treatment, reverse_charge,
|
||||
supplier_invoice_number, arrival_number, invoice_date, vat_treatment, reverse_charge, payment_reference,
|
||||
subtotal, subtotal_sek, vat_amount, vat_amount_sek, total_sek, due_date, received_date,
|
||||
is_credit_note, credited_invoice_id, payment_journal_entry_id, default_dimensions,
|
||||
supplier:suppliers(id, name, supplier_type),
|
||||
@@ -327,6 +331,47 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
const pickSupplier = (s: SI['supplier']): SupplierObj | null => {
|
||||
if (!s) return null
|
||||
return Array.isArray(s) ? (s[0] ?? null) : s
|
||||
}
|
||||
const supplierRow = pickSupplier(typed.supplier)
|
||||
|
||||
// Duplicate-payment guard: parity with the dashboard mark-paid route and
|
||||
// the v1 invoices twin, which this door lacked entirely. Runs before the
|
||||
// dry-run preview so a successful preview cannot mask the warning, only on
|
||||
// a full settlement (a partial is an explicit, deliberate action), and
|
||||
// never on force=true. Same shared detector as the dashboard route.
|
||||
if (!force && newStatus === 'paid') {
|
||||
const candidates = await findDuplicatePaymentCandidatesForSupplierInvoice(ctx.supabase, {
|
||||
companyId: ctx.companyId!,
|
||||
invoice: {
|
||||
supplier_invoice_number: typed.supplier_invoice_number ?? null,
|
||||
payment_reference: (typed as { payment_reference?: string | null }).payment_reference ?? null,
|
||||
supplier_name: supplierRow?.name,
|
||||
currency: typed.currency ?? null,
|
||||
total: typed.total ?? null,
|
||||
total_sek: (typed as { total_sek?: number | null }).total_sek ?? null,
|
||||
exchange_rate: (typed as { exchange_rate?: number | null }).exchange_rate ?? null,
|
||||
},
|
||||
paymentAmount,
|
||||
paymentDate,
|
||||
})
|
||||
if (candidates.length > 0) {
|
||||
return v1ErrorResponseFromCode('SI_PAID_LIKELY_DUPLICATE', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { candidates },
|
||||
})
|
||||
}
|
||||
} else if (force) {
|
||||
ctx.log.warn('duplicate-payment guard bypassed', {
|
||||
reason: 'force=true',
|
||||
invoiceId,
|
||||
userId: ctx.userId,
|
||||
paymentAmount,
|
||||
})
|
||||
}
|
||||
|
||||
if (ctx.dryRun) {
|
||||
// Keep the preview aligned with the live date-only payment timestamp.
|
||||
return dryRunPreview(
|
||||
@@ -344,12 +389,6 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
)
|
||||
}
|
||||
|
||||
const pickSupplier = (s: SI['supplier']): SupplierObj | null => {
|
||||
if (!s) return null
|
||||
return Array.isArray(s) ? (s[0] ?? null) : s
|
||||
}
|
||||
const supplierRow = pickSupplier(typed.supplier)
|
||||
|
||||
// Strict-mode: book the JE FIRST. Failure aborts before any SI mutation.
|
||||
let journalEntryId: string | null = null
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user