fix(bookkeeping): let a rättelseverifikation be stornoed; unblock aged supplier-invoice deletion (#1204)

* fix(bookkeeping): let a rättelseverifikation be stornoed; unblock aged supplier-invoice deletion

A user who corrected a booking (storno + rättelse) and then discovered the
affärshändelse was already booked by another verifikat had no sanctioned way
out: reverseEntry refused source_type 'correction' alongside 'storno', and
correctEntry rightly rejects a zeroing rättelse (BFL 5 kap 5 §). The same
guard also broke uncategorize-after-rättelse, since bank transactions are
relinked to the correction entry.

- reverseEntry now blocks only 'storno' (storno-of-a-storno keeps the chain
  ambiguity problem); a correction entry is a regular live verifikat and can
  be stornoed, with correction_of_id keeping the chain traceable.
- CANNOT_REVERSE_STORNO copy narrowed to stornos + remediation hint.
- Supplier-invoice DELETE now allows unbooked, unpaid invoices in
  registered/approved/overdue: the daily overdue cron flipped unbooked
  invoices past due_date into a state where deletion was blocked forever.
  Orphan-safety checks (registration JE, payments, accrual schedule) are what
  actually protect the books. UI shows the delete button accordingly.
- LinkVoucherPicker showed customer-side copy (kundfordran/1510) in
  supplier-invoice mode; supplier mode now explains the 2440-debit
  requirement, including why a direct-cost verifikat cannot be linked.

Support case 2026-07-26 (marcus@).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(supplier-invoices): review fixes: fail-closed orphan lookups, hide delete when payments loaded

- The payment and accrual-schedule lookups in DELETE now fail closed: a
  lookup error returns 500 instead of reading as "nothing linked" and
  letting the delete proceed unverified.
- The delete button also requires the loaded payment list to be empty,
  matching the server predicate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: authorize 'approved' in supplier-invoice delete allow-list (compliance-swarm V2.3)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-26 12:49:10 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 968161b42b
commit 1270b6daeb
12 changed files with 291 additions and 68 deletions
@@ -89,6 +89,31 @@ describe('DELETE /api/supplier-invoices/[id]', () => {
expect(mockSupabase.from).toHaveBeenCalledTimes(1)
})
it('blocks deletion when a payment row references the invoice', async () => {
// Belt-and-braces: payments normally move the status past the deletable
// list, but a payment row must block deletion regardless.
enqueue({
data: {
status: 'overdue',
registration_journal_entry_id: null,
is_credit_note: false,
},
})
enqueue({ data: { id: 'pay-1' } }) // supplier_invoice_payments lookup
const response = await deleteRequest()
const { status, body } = await parseJsonResponse<{
error: { code: string; details: { reason: string; paymentId: string } }
}>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('SI_DELETE_HAS_BOOKING')
expect(body.error.details.reason).toBe('payments')
expect(body.error.details.paymentId).toBe('pay-1')
// Only the existence fetch + payments lookup ran: no item deletion.
expect(mockSupabase.from).toHaveBeenCalledTimes(2)
})
it('blocks deletion when an accrual schedule references the invoice', async () => {
enqueue({
data: {
@@ -97,6 +122,7 @@ describe('DELETE /api/supplier-invoices/[id]', () => {
is_credit_note: false,
},
})
enqueue({ data: null }) // supplier_invoice_payments lookup: none
// accrual_schedules lookup finds a linked schedule (ON DELETE RESTRICT
// would otherwise fail AFTER the items were already deleted).
enqueue({ data: { id: 'sched-1' } })
@@ -110,10 +136,46 @@ describe('DELETE /api/supplier-invoices/[id]', () => {
expect(body.error.code).toBe('SI_DELETE_HAS_BOOKING')
expect(body.error.details.reason).toBe('accrual_schedule')
expect(body.error.details.scheduleId).toBe('sched-1')
// Only the existence fetch + schedule lookup ran: no item deletion.
// Existence fetch + payments lookup + schedule lookup: no item deletion.
expect(mockSupabase.from).toHaveBeenCalledTimes(3)
})
it('blocks deletion for a paid invoice', async () => {
enqueue({
data: { status: 'paid', registration_journal_entry_id: null, is_credit_note: false },
})
const { status } = await parseJsonResponse(await deleteRequest())
expect(status).toBe(400)
})
it('fails closed when the payment lookup errors', async () => {
// A transient DB/RLS failure must block the delete rather than read as
// "no payment exists".
enqueue({
data: { status: 'registered', registration_journal_entry_id: null, is_credit_note: false },
})
enqueue({ data: null, error: { message: 'permission denied' } })
const { status } = await parseJsonResponse(await deleteRequest())
expect(status).toBe(500)
// Existence fetch + payments lookup only: no item deletion.
expect(mockSupabase.from).toHaveBeenCalledTimes(2)
})
it('fails closed when the accrual-schedule lookup errors', async () => {
enqueue({
data: { status: 'registered', registration_journal_entry_id: null, is_credit_note: false },
})
enqueue({ data: null }) // supplier_invoice_payments lookup: none
enqueue({ data: null, error: { message: 'permission denied' } })
const { status } = await parseJsonResponse(await deleteRequest())
expect(status).toBe(500)
// Existence fetch + payments + schedule lookups: no item deletion.
expect(mockSupabase.from).toHaveBeenCalledTimes(3)
})
it('deletes an unbooked registered invoice', async () => {
enqueue({
data: {
@@ -122,6 +184,30 @@ describe('DELETE /api/supplier-invoices/[id]', () => {
is_credit_note: false,
},
})
enqueue({ data: null }) // supplier_invoice_payments lookup: none
enqueue({ data: null }) // accrual_schedules lookup: none
enqueue({ data: null }) // items delete
enqueue({ data: null }) // invoice delete
const response = await deleteRequest()
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
})
it('deletes an unbooked, unpaid overdue invoice', async () => {
// The overdue cron flips unbooked invoices past due_date from
// registered/approved to 'overdue'; a registered-only gate made them
// permanently undeletable just by aging (support case 2026-07-26).
enqueue({
data: {
status: 'overdue',
registration_journal_entry_id: null,
is_credit_note: false,
},
})
enqueue({ data: null }) // supplier_invoice_payments lookup: none
enqueue({ data: null }) // accrual_schedules lookup: none
enqueue({ data: null }) // items delete
enqueue({ data: null }) // invoice delete
+39 -5
View File
@@ -103,18 +103,27 @@ export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
)
}
if (existing.status !== 'registered') {
// 'overdue' and 'approved' are included: the daily cron flips unbooked
// invoices past due_date from registered/approved to 'overdue', and a
// registered-only gate made such an invoice permanently undeletable just by
// aging (support case 2026-07-26). What actually protects the books is the
// orphan-safety checks below (no registration verifikat, no payments, no
// accrual schedule), not the lifecycle label.
if (!['registered', 'approved', 'overdue'].includes(existing.status)) {
return NextResponse.json(
{ error: 'Kan bara ta bort registrerade fakturor' },
{ error: 'Endast obetalda fakturor utan bokföring kan tas bort' },
{ status: 400 }
)
}
// Booked invoices must go through the credit flow (mirrors the credit-note
// guard above). Two independent blockers:
// guard above). Three independent blockers:
// (a) a posted registration verifikat: deleting the row would orphan it
// and silently understate 2440/2641 for the momsdeklaration;
// (b) an accrual schedule: accrual_schedules.supplier_invoice_id is
// (b) a payment row: deleting the invoice would orphan the payment's
// journal-entry link (belt-and-braces: payments normally move the
// status to partially_paid/paid, which the gate above already blocks);
// (c) an accrual schedule: accrual_schedules.supplier_invoice_id is
// ON DELETE RESTRICT, so the invoice DELETE below would fail AFTER the
// items were already deleted, leaving a broken invoice with zero rows.
if (existing.registration_journal_entry_id) {
@@ -123,7 +132,28 @@ export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
})
}
const { data: linkedSchedule } = await supabase
// Both orphan-safety lookups fail CLOSED: a lookup error must block the
// delete, otherwise a transient DB/RLS failure would read as "no payment /
// no schedule" and let the delete through unverified.
const { data: linkedPayment, error: paymentLookupError } = await supabase
.from('supplier_invoice_payments')
.select('id')
.eq('company_id', companyId)
.eq('supplier_invoice_id', id)
.limit(1)
.maybeSingle()
if (paymentLookupError) {
return NextResponse.json({ error: getUserErrorMessage(paymentLookupError) }, { status: 500 })
}
if (linkedPayment) {
return errorResponseFromCode('SI_DELETE_HAS_BOOKING', log, {
details: { reason: 'payments', paymentId: linkedPayment.id },
})
}
const { data: linkedSchedule, error: scheduleLookupError } = await supabase
.from('accrual_schedules')
.select('id')
.eq('company_id', companyId)
@@ -131,6 +161,10 @@ export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
.limit(1)
.maybeSingle()
if (scheduleLookupError) {
return NextResponse.json({ error: getUserErrorMessage(scheduleLookupError) }, { status: 500 })
}
if (linkedSchedule) {
return errorResponseFromCode('SI_DELETE_HAS_BOOKING', log, {
details: { reason: 'accrual_schedule', scheduleId: linkedSchedule.id },