fix(supplier-invoices): a credit note is never a payable, so it never waits for attest (#2289)

* fix(supplier-invoices): a credit note is never a payable, so it never waits for attest

A supplier credit note created with Kreditera was inserted at 'registered',
the attest entry state, while the detail page (rightly) offered no attest
for it. The worklist counted every 'registered' row, so Att göra showed
"1 leverantörsfaktura att attestera" that nobody could clear (support case
2026-09-04; 14 such rows on prod plus one MCP-approved credit note).

- One row builder (lib/supplier-invoices/credit-note.ts) for the dashboard
  route, the MCP executor and the v1 API: the credit note rests at
  'credited' from birth, the status the provider importers already use.
- CHECK supplier_invoices_credit_note_not_payable keeps every writer out of
  the payable states; migration backfills the stuck rows (one immutable
  reset-source row skipped, hence NOT VALID).
- The worklist attest count excludes credit notes explicitly.
- GET /api/supplier-invoices/[id] hydrates credited_original with a second
  scoped query: PostgREST cannot pick a direction for a self-referencing
  embed hint and returned the one-to-many side (an empty array), which the
  page rendered as "Krediterar: Ankomst #" with no number.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

* test(supplier-invoices): type the GET route response in the credited_original tests

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

* fix(migration): NOT EXISTS instead of NOT IN for the reset-source exclusion

A NULL source_company_id in the subquery would make NOT IN never true and
silently skip the whole backfill.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

* test(schema): raise the unresolved-payload ceiling by 3 for the credit-note row builder

The three credit-note creation paths now insert the row from one builder,
so the scanner sees three dynamic payloads instead of three literals. The
columns are the literal in lib/supplier-invoices/credit-note.ts, pinned by
its test; the resting status is additionally held by the DB CHECK.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

* test(pg): credit-note fixtures in the overdue-cron tests rest at credited

The two fixtures that seeded a credit note on 'registered'/'overdue' now
violate supplier_invoices_credit_note_not_payable. The cron test seeds the
credit note the way the routes create it since 20260904190000; the 20260607
backfill case asserts the scenario it repaired is now unreachable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

* test(pg): ledger-usage-stats seeds its credit note at credited

The fixture defaulted every row to 'registered', which the CHECK
supplier_invoices_credit_note_not_payable now refuses for a credit note.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S62AGZwsMoBc8x8obBDVqE

---------

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:
Jakob Wennberg
2026-09-05 09:43:00 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent 1e1e1d5d17
commit e684606b23
17 changed files with 469 additions and 102 deletions
+3 -1
View File
@@ -143,7 +143,9 @@ async function insertSupplierWithInvoices(params: {
arrival++,
`SI-${arrival}`,
inv.invoiceDate,
inv.status ?? 'registered',
// A credit note rests at 'credited' (never a payable): the CHECK
// supplier_invoices_credit_note_not_payable refuses 'registered'.
inv.status ?? (inv.isCreditNote ? 'credited' : 'registered'),
inv.vatTreatment ?? 'standard_25',
inv.isCreditNote ?? false,
],
@@ -0,0 +1,99 @@
/**
* pg-real tests for 20260904190000_supplier_credit_note_not_payable.sql.
*
* A supplier credit note is a reversal, never a payable: it must not sit in
* the attest/payment lifecycle (registered, approved, overdue, paid,
* partially_paid). Ordinary supplier invoices keep the whole lifecycle.
*/
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { insertAuthUser, insertCompany, insertCompanyMember } from '@/tests/pg/fixtures'
async function seedSupplierInvoicePair(): Promise<{
companyId: string
originalId: string
creditNoteId: string
insertCreditNote: (status: string) => Promise<unknown>
}> {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId })
const { rows } = await getPool().query<{ id: string }>(
`INSERT INTO public.suppliers (user_id, company_id, name)
VALUES ($1, $2, 'Hi3G Access AB') RETURNING id`,
[userId, companyId],
)
const supplierId = rows[0]!.id
const originalId = randomUUID()
await getPool().query(
`INSERT INTO public.supplier_invoices
(id, user_id, company_id, supplier_id, arrival_number, supplier_invoice_number,
invoice_date, due_date, status, subtotal, vat_amount, total, remaining_amount)
VALUES ($1, $2, $3, $4, 4, '528285626420', '2026-08-03', '2026-08-17', 'credited',
1048, 262, 1310, 0)`,
[originalId, userId, companyId, supplierId],
)
let nextArrival = 5
const insertCreditNote = (status: string) => {
const id = randomUUID()
const arrival = nextArrival++
return getPool().query(
`INSERT INTO public.supplier_invoices
(id, user_id, company_id, supplier_id, arrival_number, supplier_invoice_number,
invoice_date, due_date, status, subtotal, vat_amount, total, remaining_amount,
is_credit_note, credited_invoice_id)
VALUES ($1, $2, $3, $4, $5, $6, '2026-09-04', '2026-09-04', $7,
1048, 262, 1310, 0, true, $8)`,
[id, userId, companyId, supplierId, arrival, `KREDIT-528285626420-${arrival}`, status, originalId],
).then(() => id)
}
const creditNoteId = (await insertCreditNote('credited')) as string
return { companyId, originalId, creditNoteId, insertCreditNote }
}
describe('supplier_invoices_credit_note_not_payable constraint', () => {
it.each(['registered', 'approved', 'overdue', 'paid', 'partially_paid'])(
'rejects moving a credit note to %s',
async (status) => {
const { creditNoteId } = await seedSupplierInvoicePair()
await expect(
getPool().query(`UPDATE public.supplier_invoices SET status = $1 WHERE id = $2`, [
status,
creditNoteId,
]),
).rejects.toMatchObject({ code: '23514' })
},
)
it('rejects inserting a credit note at the attest entry state', async () => {
// The state every creation path used before 20260904190000.
const { insertCreditNote } = await seedSupplierInvoicePair()
await expect(insertCreditNote('registered')).rejects.toMatchObject({ code: '23514' })
})
it('lets a credit note rest at credited and be soft-deleted to reversed', async () => {
const { creditNoteId } = await seedSupplierInvoicePair()
await expect(
getPool().query(`UPDATE public.supplier_invoices SET status = 'reversed' WHERE id = $1`, [
creditNoteId,
]),
).resolves.toMatchObject({ rowCount: 1 })
})
it('leaves ordinary supplier invoices on the payable lifecycle', async () => {
const { originalId } = await seedSupplierInvoicePair()
for (const status of ['registered', 'approved', 'overdue', 'partially_paid', 'paid']) {
await expect(
getPool().query(`UPDATE public.supplier_invoices SET status = $1 WHERE id = $2`, [
status,
originalId,
]),
).resolves.toMatchObject({ rowCount: 1 })
}
})
})
@@ -128,20 +128,21 @@ describe('update_overdue_supplier_invoices()', () => {
expect(await statusOf(id)).toBe('overdue')
})
it('never marks a credit note overdue (remaining 0, status registered)', async () => {
it('never marks a credit note overdue (remaining 0, status credited)', async () => {
const { userId, companyId } = await seedCompany()
const supplierId = await insertSupplier(userId, companyId)
// Mirrors how the credit routes create a credit note: registered, fully
// settled (remaining 0), due today (here: long past).
// Mirrors how the credit routes create a credit note since 20260904190000:
// resting at 'credited' (a reversal is never a payable), fully settled
// (remaining 0), due today (here: long past).
const id = await insertSupplierInvoice({
userId, companyId, supplierId,
status: 'registered', dueDate: PAST, total: 1000, remaining: 0,
status: 'credited', dueDate: PAST, total: 1000, remaining: 0,
isCreditNote: true,
})
await getPool().query('SELECT public.update_overdue_supplier_invoices()')
expect(await statusOf(id)).toBe('registered')
expect(await statusOf(id)).toBe('credited')
})
it('never marks a fully-paid (remaining ~0) invoice overdue', async () => {
@@ -251,18 +252,21 @@ describe('overdue backfill (migration 20260607120000)', () => {
await getPool().query(SYMMETRIC_FUNCTION_SQL)
})
it('reverts a credit note wrongly stuck on overdue back to registered', async () => {
it('has nothing left to revert for credit notes: they can no longer reach overdue', async () => {
// The 20260607120000 backfill moved credit notes wrongly stuck on
// 'overdue' back to 'registered'. Since 20260904190000 a credit note
// cannot be in either state: supplier_invoices_credit_note_not_payable
// refuses the payable lifecycle for credit notes at the row level
// (tests/pg/supplier-credit-note-not-payable.pg.test.ts), so the
// scenario this backfill repaired is unreachable.
const { userId, companyId } = await seedCompany()
const supplierId = await insertSupplier(userId, companyId)
const id = await insertSupplierInvoice({
userId, companyId, supplierId,
status: 'overdue', dueDate: PAST, total: 1000, remaining: 0, isCreditNote: true,
})
// Idempotent: re-running the migration only touches status='overdue' rows.
await getPool().query(MIGRATION_SQL)
expect(await statusOf(id)).toBe('registered')
await expect(
insertSupplierInvoice({
userId, companyId, supplierId,
status: 'overdue', dueDate: PAST, total: 1000, remaining: 0, isCreditNote: true,
}),
).rejects.toMatchObject({ code: '23514', constraint: 'supplier_invoices_credit_note_not_payable' })
})
it('marks a fully-paid invoice stuck on overdue as paid (and stamps paid_at)', async () => {
+8 -1
View File
@@ -167,7 +167,14 @@ const KNOWN_STALE_ON_CONFLICT: Record<string, string> = {}
// (parties phase 1, #2162/#2168/#2169) at 395: 397.
// 2026-09-04: +2 recurring lines (#2044, see the 2026-08-30 recurring payroll
// lines note above); merged with main (#2141/#2164/#2170/#2192) at 397: 399.
const UNRESOLVED_CEILING = 399
// 2026-09-04: +3 supplier credit notes (#2289): the dashboard credit route,
// commitCreditSupplierInvoice (MCP) and the v1 credit route insert the
// credit-note row from one builder, buildSupplierCreditNoteRow() in
// lib/supplier-invoices/credit-note.ts, so the resting status is decided in
// one place (and held by CHECK supplier_invoices_credit_note_not_payable);
// its columns are the object literal in that file, pinned by
// credit-note.test.ts. Merged with main (#2288) at 399: 402.
const UNRESOLVED_CEILING = 402
/**
* Floor on statically resolved column references. Guards the guard: if a change