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
+9 -25
View File
@@ -65,6 +65,7 @@ import {
canApproveSupplierInvoice,
resolveUnsettledStatus,
} from '@/lib/supplier-invoices/lifecycle'
import { buildSupplierCreditNoteRow } from '@/lib/supplier-invoices/credit-note'
import { coerceDimensionsBag } from '@/lib/bookkeeping/dimension-resolver'
import { ACCOUNT_NUMBER_RE } from '@/lib/invariants/account-number'
import { ISO_DATE_RE } from '@/lib/invariants/iso-date'
@@ -4934,31 +4935,14 @@ async function commitCreditSupplierInvoice(
const { data: creditNote, error: creditError } = await supabase
.from('supplier_invoices')
.insert({
user_id: userId,
company_id: companyId,
supplier_id: original.supplier_id,
arrival_number: arrivalNum,
supplier_invoice_number: `KREDIT-${original.supplier_invoice_number}`,
invoice_date: new Date().toISOString().split('T')[0],
due_date: new Date().toISOString().split('T')[0],
status: 'registered',
currency: original.currency,
exchange_rate: original.exchange_rate,
vat_treatment: original.vat_treatment,
reverse_charge: original.reverse_charge,
subtotal: original.subtotal,
subtotal_sek: original.subtotal_sek,
vat_amount: original.vat_amount,
vat_amount_sek: original.vat_amount_sek,
total: original.total,
total_sek: original.total_sek,
remaining_amount: 0,
is_credit_note: true,
credited_invoice_id: id,
// Dimensions PR7: copy so the reversal nets against the same cells.
default_dimensions: original.default_dimensions ?? {},
})
.insert(
buildSupplierCreditNoteRow(original, {
userId,
companyId,
arrivalNumber: arrivalNum,
date: new Date().toISOString().split('T')[0],
}),
)
.select()
.single()
@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest'
import { makeSupplierInvoice } from '@/tests/helpers'
import { SUPPLIER_CREDIT_NOTE_STATUS, buildSupplierCreditNoteRow } from '../credit-note'
const CTX = { userId: 'user-1', companyId: 'company-1', arrivalNumber: 7, date: '2026-09-04' }
describe('buildSupplierCreditNoteRow', () => {
it('rests the credit note at credited, never at the attest entry state', () => {
const row = buildSupplierCreditNoteRow(makeSupplierInvoice({ id: 'si-1' }), CTX)
expect(SUPPLIER_CREDIT_NOTE_STATUS).toBe('credited')
expect(row.status).toBe('credited')
expect(row.is_credit_note).toBe(true)
expect(row.credited_invoice_id).toBe('si-1')
expect(row.remaining_amount).toBe(0)
})
it('mirrors the original amounts and identity under the KREDIT- prefix', () => {
const original = makeSupplierInvoice({
id: 'si-1',
supplier_id: 'sup-1',
supplier_invoice_number: '528285626420',
currency: 'EUR',
exchange_rate: 11.2,
vat_treatment: 'standard_25',
reverse_charge: false,
subtotal: 1048,
subtotal_sek: 11737.6,
vat_amount: 262,
vat_amount_sek: 2934.4,
total: 1310,
total_sek: 14672,
})
const row = buildSupplierCreditNoteRow(
{ ...original, default_dimensions: { cost_center: 'cc-1' } },
CTX,
)
expect(row).toMatchObject({
user_id: 'user-1',
company_id: 'company-1',
supplier_id: 'sup-1',
arrival_number: 7,
supplier_invoice_number: 'KREDIT-528285626420',
invoice_date: '2026-09-04',
due_date: '2026-09-04',
currency: 'EUR',
exchange_rate: 11.2,
subtotal: 1048,
subtotal_sek: 11737.6,
vat_amount: 262,
vat_amount_sek: 2934.4,
total: 1310,
total_sek: 14672,
default_dimensions: { cost_center: 'cc-1' },
})
})
it('defaults a missing dimension bag to an empty object', () => {
const row = buildSupplierCreditNoteRow(makeSupplierInvoice({ id: 'si-1' }), CTX)
expect(row.default_dimensions).toEqual({})
})
})
+90
View File
@@ -0,0 +1,90 @@
/**
* Where a supplier credit note rests, from the moment it is created.
*
* A kreditfaktura from a supplier is the reversal of an invoice we already
* registered: Accounted creates it from the original with Kreditera, books
* the reversing verifikat in the same request and moves the original to
* 'credited'. Nothing is left to attest and nothing is left to pay, so the
* row must never enter the payable lifecycle (registered, approved, overdue,
* paid, partially_paid).
*
* It used to be inserted at that lifecycle's entry state, 'registered', which
* every consumer reads as "waiting for attest": the worklist counted it as
* "1 leverantörsfaktura att attestera" while the detail page (correctly)
* offered no attest for a credit note, so the item could never be cleared
* (support case 2026-09-04). 'credited' is the status the provider importers
* already give incoming credit notes, and the CHECK constraint
* supplier_invoices_credit_note_not_payable (20260904190000) holds every
* writer to it.
*/
export const SUPPLIER_CREDIT_NOTE_STATUS = 'credited' as const
/**
* The columns of the original that a credit note mirrors. Deliberately a
* structural type (not Pick<SupplierInvoice>): the v1 route reads the original
* through a narrower projection whose vat_treatment is a plain string.
*/
export interface SupplierCreditNoteSource {
id: string
supplier_id: string
supplier_invoice_number: string
currency: string
exchange_rate: number | null
vat_treatment: string
reverse_charge: boolean
subtotal: number
subtotal_sek: number | null
vat_amount: number
vat_amount_sek: number | null
total: number
total_sek: number | null
default_dimensions?: Record<string, string> | null
}
export interface SupplierCreditNoteContext {
userId: string
companyId: string
arrivalNumber: number
/** ISO yyyy-MM-dd: the credit note's invoice and due date. */
date: string
}
/**
* The supplier_invoices row for a credit note that reverses `original`.
*
* One builder for the three creation paths (dashboard route, MCP executor,
* v1 API) so the resting status, the zero remaining amount and the copied
* amounts cannot drift between them.
*/
export function buildSupplierCreditNoteRow(
original: SupplierCreditNoteSource,
ctx: SupplierCreditNoteContext,
) {
return {
user_id: ctx.userId,
company_id: ctx.companyId,
supplier_id: original.supplier_id,
arrival_number: ctx.arrivalNumber,
supplier_invoice_number: `KREDIT-${original.supplier_invoice_number}`,
invoice_date: ctx.date,
due_date: ctx.date,
status: SUPPLIER_CREDIT_NOTE_STATUS,
currency: original.currency,
exchange_rate: original.exchange_rate,
vat_treatment: original.vat_treatment,
reverse_charge: original.reverse_charge,
subtotal: original.subtotal,
subtotal_sek: original.subtotal_sek,
vat_amount: original.vat_amount,
vat_amount_sek: original.vat_amount_sek,
total: original.total,
total_sek: original.total_sek,
// A credit note is never a payable: nothing remains to pay on it.
remaining_amount: 0,
is_credit_note: true,
credited_invoice_id: original.id,
// Copy the original's dimension bag so the reversal nets against the
// same dimension cells in reports (dimensions PR7).
default_dimensions: original.default_dimensions ?? {},
}
}
+13
View File
@@ -41,6 +41,19 @@ describe('countUnbookedTransactions', () => {
})
})
describe('countSupplierInvoicesAwaitingApproval', () => {
it('counts registered invoices but never credit notes', async () => {
// A credit note is a reversal with nothing to attest; the detail page
// offers no attest button for it, so counting one here made an item
// nobody could clear (support case 2026-09-04).
enqueue({ count: 1 })
await expect(countSupplierInvoicesAwaitingApproval(supabase, COMPANY)).resolves.toBe(1)
const eqCalls = findCalls('supplier_invoices', 'eq')
expect(eqCalls).toContainEqual(['status', 'registered'])
expect(eqCalls).toContainEqual(['is_credit_note', false])
})
})
describe('countUnbookedSkattekontoRows', () => {
it('counts only settled, unbooked, non-ignored skattekonto rows', async () => {
enqueue({ count: 3 })
+7
View File
@@ -184,6 +184,13 @@ export async function countSupplierInvoicesAwaitingApproval(
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('status', 'registered')
// A credit note is a reversal, never a payable: there is nothing to
// attest on it and the detail page offers no attest button, so counting
// one here made an item nobody could clear. The CHECK
// supplier_invoices_credit_note_not_payable keeps credit notes out of
// 'registered' since 20260904190000; the predicate states the rule where
// the count is defined.
.eq('is_credit_note', false)
if (error) return logAndZero('supplier_invoice_approval', companyId, error)
return count ?? 0
}
+2 -1
View File
@@ -59,7 +59,8 @@ export const WORKLIST_CATEGORIES = [
'suggested_match',
/**
* Supplier invoices awaiting approval ("attestera").
* Pending: supplier_invoices.status = 'registered'.
* Pending: supplier_invoices.status = 'registered' and not a credit note
* (a credit note is a reversal, never a payable).
* Done: status moves to approved/paid/credited/….
*/
'supplier_invoice_approval',