fix(invoices): v1 mark-paid booking-state routing + journal_entry_id backfill (#713)

invoices.journal_entry_id means "the registration verifikat that booked
this invoice at issuance" — payment flows route on it (set → clear 1510,
NULL → kontantmetoden cash entry). Two bugs in v1 mark-paid broke that:

- The pre-flight select omitted journal_entry_id, so invoiceAlreadyBooked
  always read false — a kontantmetoden company paying an already-registered
  invoice would re-recognise revenue + VAT (double-booking) and orphan the
  1510 receivable. Fixed by fetching the column for routing only; the
  response contract and invoice.paid event payload are unchanged.
- The update wrote the just-created PAYMENT/cash entry id into the column
  (wrong semantic) — once routing reads the column, a cash partial payment
  #1 would make payment #2 clear a 1510 that was never debited. Removed;
  the payment entry id still returns in the response body.

New backfill migration links the earliest posted invoice_created entry to
historical invoices (353 registered-but-unlinked rows in hosted prod),
repairs any payment-type links, and links credit_note reversal entries to
credit-note rows. Idempotent; rows with no registration entry stay NULL
(correct for kontantmetoden/unsent invoices).

Tests: 3 new unit tests lock the select projection, the already-booked→
clearing routing, and the no-write-back semantics (the supabase mock now
records call args). New pg-real suite (11 tests) runs the actual migration
SQL: earliest-wins, reversed/draft exclusion, no-overwrite, cash stays
NULL, payment-link repair, credit notes, cross-company isolation,
idempotency. insertDraftJournalEntry fixture gains optional sourceType/
sourceId/createdAt (defaults unchanged).

Hosted prod requires manual migration apply after merge (Supabase MCP).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-11 11:51:31 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 0521c385d2
commit b7f60b23f5
5 changed files with 535 additions and 9 deletions
@@ -55,7 +55,13 @@ const mockPayment = mockedPayment as ReturnType<typeof vi.fn>
const mockCash = mockedCash as ReturnType<typeof vi.fn>
type MockResult = { data?: unknown; error?: unknown }
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
type RecordedCall = { table: string; method: string; args: unknown[] }
function makeFlexibleSupabase(
byTable: Record<string, MockResult | MockResult[]>,
// Optional recorder: collects every (table, method, args) so tests can
// assert on select projections and update payloads, not just results.
calls?: RecordedCall[],
) {
const queues = new Map<string, MockResult[]>()
for (const [t, val] of Object.entries(byTable)) {
queues.set(t, Array.isArray(val) ? [...val] : [val])
@@ -70,7 +76,10 @@ function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>
resolve(next)
}
}
return (..._args: unknown[]) => buildChain(table)
return (...args: unknown[]) => {
calls?.push({ table, method: String(prop), args })
return buildChain(table)
}
},
}
return new Proxy({}, handler)
@@ -192,6 +201,107 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/mark-paid', () => {
expect(mockPayment).not.toHaveBeenCalled()
})
it('fetches journal_entry_id in the pre-flight select but keeps it out of the response select', async () => {
const calls: RecordedCall[] = []
mockServiceClient.mockReturnValue(
makeFlexibleSupabase(
{
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
invoices: [
{ data: SENT_INVOICE, error: null },
{ data: PAID_INVOICE, error: null },
],
company_settings: { data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null },
},
calls,
),
)
const res = await markPaid(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/mark-paid`,
{ payment_date: '2026-05-12' },
),
detailParams(COMPANY_ID, INVOICE_ID),
)
expect(res.status).toBe(200)
const invoiceSelects = calls.filter((c) => c.table === 'invoices' && c.method === 'select')
// Pre-flight select must fetch journal_entry_id — invoiceAlreadyBooked
// routing reads it; omitting it silently forces the cash path.
expect(invoiceSelects.length).toBeGreaterThanOrEqual(2)
expect(String(invoiceSelects[0].args[0])).toContain('journal_entry_id')
// Response select (the update's .select) keeps the public contract unchanged.
expect(String(invoiceSelects[1].args[0])).not.toContain('journal_entry_id')
})
it('clears AR (payment entry) when a cash-method company pays an invoice booked at send', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
invoices: [
{
// Booked at send under accrual: registration entry linked.
data: { ...SENT_INVOICE, journal_entry_id: 'rrrrrrrr-rrrr-4rrr-8rrr-rrrrrrrrrrrr' },
error: null,
},
{ data: PAID_INVOICE, error: null },
],
company_settings: { data: { accounting_method: 'cash', entity_type: 'enskild_firma' }, error: null },
}),
)
const res = await markPaid(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/mark-paid`,
{ payment_date: '2026-05-12' },
),
detailParams(COMPANY_ID, INVOICE_ID),
)
expect(res.status).toBe(200)
// Already-booked → clearing entry (Dr 1930 / Cr 1510), NOT a cash entry —
// a cash entry here would re-recognise revenue + VAT (double-booking).
expect(mockPayment).toHaveBeenCalled()
expect(mockCash).not.toHaveBeenCalled()
})
it('does not write journal_entry_id back to the invoice row (registration semantics)', async () => {
const calls: RecordedCall[] = []
mockServiceClient.mockReturnValue(
makeFlexibleSupabase(
{
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
invoices: [
{ data: SENT_INVOICE, error: null },
{ data: PAID_INVOICE, error: null },
],
company_settings: { data: { accounting_method: 'accrual', entity_type: 'enskild_firma' }, error: null },
},
calls,
),
)
const res = await markPaid(
makeRequest(
`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/mark-paid`,
{ payment_date: '2026-05-12' },
),
detailParams(COMPANY_ID, INVOICE_ID),
)
expect(res.status).toBe(200)
// The column means "registration entry at issuance"; writing the payment
// entry id would make a kontantmetoden invoice look registered.
const update = calls.find((c) => c.table === 'invoices' && c.method === 'update')
expect(update).toBeDefined()
expect(Object.keys(update!.args[0] as Record<string, unknown>)).not.toContain('journal_entry_id')
// The payment entry id still reaches the caller via the response body.
const body = await res.json()
expect(body.data.journal_entry_id).toBe('jjjjjjjj-jjjj-4jjj-8jjj-jjjjjjjjjjjj')
})
it('returns 400 INVOICE_PAID_LINES_UNBALANCED when custom lines do not balance', async () => {
mockServiceClient.mockReturnValue(
makeFlexibleSupabase({
@@ -166,10 +166,13 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
}
// Pre-flight: fetch invoice with relations needed for journal entry.
// journal_entry_id is fetched for booking-state routing only (it stays out
// of INVOICE_MARK_PAID_RESPONSE_COLUMNS so the response contract and the
// invoice.paid event payload are unchanged).
const { data: invoice, error: fetchErr } = await ctx.supabase
.from('invoices')
.select(
`${INVOICE_MARK_PAID_RESPONSE_COLUMNS}, customer:customers(id, name, customer_type), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount)`,
`${INVOICE_MARK_PAID_RESPONSE_COLUMNS}, journal_entry_id, customer:customers(id, name, customer_type), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount)`,
)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
@@ -428,9 +431,12 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
if (newStatus === 'paid') {
updatePayload.paid_at = paymentDate
}
if (journalEntryId) {
updatePayload.journal_entry_id = journalEntryId
}
// Deliberately NOT writing journal_entry_id here: that column means "the
// registration entry that booked this invoice at issuance" and drives the
// invoiceAlreadyBooked routing above. Writing the payment/cash entry id
// would make a kontantmetoden invoice look registered, so a later partial
// payment would clear a 1510 that was never debited. The payment entry id
// is returned in the response body instead.
const { data: updated, error: updateErr } = await ctx.supabase
.from('invoices')