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
+9 -3
View File
@@ -170,15 +170,18 @@ export async function insertDraftJournalEntry(params: {
entryDate?: string
description?: string
voucherSeries?: string
status?: 'draft' | 'posted'
status?: 'draft' | 'posted' | 'reversed' | 'cancelled'
voucherNumber?: number
sourceType?: string
sourceId?: string | null
createdAt?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.journal_entries
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
entry_date, description, source_type, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'manual', $9)`,
entry_date, description, source_type, source_id, status, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::timestamptz, now()))`,
[
id,
params.userId,
@@ -188,7 +191,10 @@ export async function insertDraftJournalEntry(params: {
params.voucherSeries ?? 'A',
params.entryDate ?? '2026-06-01',
params.description ?? 'Test entry',
params.sourceType ?? 'manual',
params.sourceId ?? null,
params.status ?? 'draft',
params.createdAt ?? null,
],
)
return id
@@ -0,0 +1,332 @@
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { seedCompany, insertDraftJournalEntry } from '@/tests/pg/fixtures'
import { getPool } from '@/tests/pg/setup'
/**
* pg-real coverage for 20260622120000_invoices_journal_entry_id_backfill.sql.
*
* invoices.journal_entry_id means "the registration verifikat that booked the
* invoice at issuance" — payment flows route on it (set → clear 1510; NULL →
* kontantmetoden cash entry). A wrong link silently double-books revenue +
* VAT, so the backfill's guards are load-bearing:
* - only posted invoice_created entries qualify (reversed/draft excluded)
* - earliest entry wins deterministically on duplicates
* - rows with an existing link are never overwritten
* - payment-type links (wrong semantic from an earlier route version) are
* repaired: nulled, then re-linked from the registration entry if any
* - kontantmetoden invoices (no registration entry) stay NULL
* - credit-note rows link their credit_note reversal entry
* - cross-company isolation
* - idempotent (re-run is a no-op)
*/
// Run the real migration SQL so the test exercises exactly what ships.
const BACKFILL_SQL = readFileSync(
join(process.cwd(), 'supabase/migrations/20260622120000_invoices_journal_entry_id_backfill.sql'),
'utf8',
)
async function runBackfill(): Promise<void> {
await getPool().query(BACKFILL_SQL)
}
async function insertInvoice(params: {
userId: string
companyId: string
status?: string
creditedInvoiceId?: string | null
journalEntryId?: string | null
}): Promise<string> {
const id = randomUUID()
const customerId = randomUUID()
await getPool().query(
`INSERT INTO public.customers (id, user_id, company_id, name)
VALUES ($1, $2, $3, 'Testkund AB')`,
[customerId, params.userId, params.companyId],
)
await getPool().query(
`INSERT INTO public.invoices
(id, user_id, company_id, customer_id, invoice_number,
invoice_date, due_date, currency, subtotal, vat_amount, total,
vat_treatment, vat_rate, moms_ruta, status, credited_invoice_id,
journal_entry_id)
VALUES ($1, $2, $3, $4, $5,
'2026-06-01', '2026-06-30', 'SEK', 10000, 2500, 12500,
'standard_25', 25, '05', $6, $7, $8)`,
[
id,
params.userId,
params.companyId,
customerId,
`F-${randomUUID().slice(0, 8)}`,
params.status ?? 'sent',
params.creditedInvoiceId ?? null,
params.journalEntryId ?? null,
],
)
return id
}
async function getLink(invoiceId: string): Promise<string | null> {
const { rows } = await getPool().query(
`SELECT journal_entry_id FROM public.invoices WHERE id = $1`,
[invoiceId],
)
return rows[0]?.journal_entry_id ?? null
}
describe('invoices.journal_entry_id backfill — Pass 1 (registration entries)', () => {
it('links the posted invoice_created entry to its invoice', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId })
const jeId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
await runBackfill()
expect(await getLink(invoiceId)).toBe(jeId)
})
it('picks the earliest posted entry when duplicates exist', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId })
const early = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
createdAt: '2026-06-01T08:00:00Z',
})
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
createdAt: '2026-06-02T08:00:00Z',
})
await runBackfill()
expect(await getLink(invoiceId)).toBe(early)
})
it('skips reversed and draft registration entries (invoice stays NULL)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId })
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'reversed',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'draft',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
await runBackfill()
// A stornoed registration must not mark the invoice as booked — the
// payment flow should recognise revenue via the cash path instead.
expect(await getLink(invoiceId)).toBeNull()
})
it('never overwrites an existing link', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
// Existing link points at a manual entry (e.g. user-curated) — backfill
// must leave it alone even though a registration entry also exists.
const manual = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
})
const invoiceId = await insertInvoice({ userId, companyId, journalEntryId: manual })
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
await runBackfill()
expect(await getLink(invoiceId)).toBe(manual)
})
it('leaves kontantmetoden invoices NULL (only a cash payment entry exists)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId, status: 'paid' })
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_cash_payment',
sourceId: invoiceId,
})
await runBackfill()
// NULL is the CORRECT value here — revenue was recognised at payment.
expect(await getLink(invoiceId)).toBeNull()
})
it('does not cross-link between companies', async () => {
const a = await seedCompany()
const b = await seedCompany()
const invoiceA = await insertInvoice({ userId: a.userId, companyId: a.companyId })
// Company B has a posted registration entry whose source_id happens to
// reference company A's invoice (corrupt/cross-tenant data) — the
// company_id guard must refuse the link.
await insertDraftJournalEntry({
userId: b.userId,
companyId: b.companyId,
fiscalPeriodId: b.fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceA,
})
await runBackfill()
expect(await getLink(invoiceA)).toBeNull()
})
})
describe('invoices.journal_entry_id backfill — Pass 0 (payment-link repair)', () => {
it('nulls a payment-type link, then re-links the registration entry', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId, status: 'paid' })
const registration = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
const payment = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_paid',
sourceId: invoiceId,
})
// Simulate the old v1 mark-paid write-back: payment entry id in the column.
await getPool().query(
`UPDATE public.invoices SET journal_entry_id = $1 WHERE id = $2`,
[payment, invoiceId],
)
await runBackfill()
expect(await getLink(invoiceId)).toBe(registration)
})
it('nulls a cash-payment link with no registration entry (stays NULL)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId, status: 'paid' })
const cash = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_cash_payment',
sourceId: invoiceId,
})
await getPool().query(
`UPDATE public.invoices SET journal_entry_id = $1 WHERE id = $2`,
[cash, invoiceId],
)
await runBackfill()
expect(await getLink(invoiceId)).toBeNull()
})
})
describe('invoices.journal_entry_id backfill — Pass 2 (credit notes)', () => {
it('links the credit_note reversal entry to the credit-note row', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const original = await insertInvoice({ userId, companyId })
const creditNote = await insertInvoice({
userId,
companyId,
creditedInvoiceId: original,
})
const reversal = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'credit_note',
sourceId: creditNote,
})
await runBackfill()
expect(await getLink(creditNote)).toBe(reversal)
expect(await getLink(original)).toBeNull()
})
it('ignores credit_note entries pointing at non-credit-note rows', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId })
await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'credit_note',
sourceId: invoiceId,
})
await runBackfill()
// credited_invoice_id IS NULL → Pass 2 must not touch the row.
expect(await getLink(invoiceId)).toBeNull()
})
})
describe('invoices.journal_entry_id backfill — idempotency', () => {
it('re-running the backfill changes nothing', async () => {
const { userId, companyId, fiscalPeriodId } = await seedCompany()
const invoiceId = await insertInvoice({ userId, companyId })
const jeId = await insertDraftJournalEntry({
userId,
companyId,
fiscalPeriodId,
status: 'posted',
sourceType: 'invoice_created',
sourceId: invoiceId,
})
await runBackfill()
expect(await getLink(invoiceId)).toBe(jeId)
await runBackfill()
expect(await getLink(invoiceId)).toBe(jeId)
})
})