Files
accounted/tests/pg/supplier-credit-note-not-payable.pg.test.ts
T
e684606b23 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>
2026-09-05 09:43:00 +02:00

100 lines
3.9 KiB
TypeScript

/**
* 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 })
}
})
})