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:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
1e1e1d5d17
commit
e684606b23
@@ -7,7 +7,7 @@ import {
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
@@ -23,7 +23,7 @@ vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { DELETE } from '../route'
|
||||
import { DELETE, GET } from '../route'
|
||||
|
||||
describe('DELETE /api/supplier-invoices/[id]', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
@@ -219,3 +219,65 @@ describe('DELETE /api/supplier-invoices/[id]', () => {
|
||||
expect(body.success).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/supplier-invoices/[id]', () => {
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
function getRequest(id: string) {
|
||||
return GET(
|
||||
createMockRequest(`/api/supplier-invoices/${id}`, { method: 'GET' }),
|
||||
createMockRouteParams({ id }),
|
||||
)
|
||||
}
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
expect((await getRequest('si-1')).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the invoice does not exist', async () => {
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
expect((await getRequest('missing')).status).toBe(404)
|
||||
})
|
||||
|
||||
it('hydrates the credited original of a credit note with a company-scoped lookup', async () => {
|
||||
// credited_invoice_id is a self-reference, and a PostgREST embed on it
|
||||
// resolved to the one-to-many side (an empty array), which the detail
|
||||
// page rendered as "Krediterar: Ankomst #" with no number.
|
||||
enqueue({
|
||||
data: { id: 'cn-1', is_credit_note: true, credited_invoice_id: 'si-orig', items: [], payments: [] },
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: { id: 'si-orig', supplier_invoice_number: '528285626420', arrival_number: 4 }, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { credited_original: unknown } }>(await getRequest('cn-1'))
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.credited_original).toEqual({
|
||||
id: 'si-orig',
|
||||
supplier_invoice_number: '528285626420',
|
||||
arrival_number: 4,
|
||||
})
|
||||
const eqCalls = findCalls('supplier_invoices', 'eq')
|
||||
expect(eqCalls).toContainEqual(['id', 'si-orig'])
|
||||
expect(eqCalls.filter((c) => c[0] === 'company_id')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('leaves credited_original null on an ordinary invoice without a second query', async () => {
|
||||
enqueue({ data: { id: 'si-1', is_credit_note: false, credited_invoice_id: null, items: [], payments: [] }, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { credited_original: unknown } }>(await getRequest('si-1'))
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.credited_original).toBeNull()
|
||||
expect(mockSupabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -145,6 +145,16 @@ describe('POST /api/supplier-invoices/[id]/credit', () => {
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// The credit note rests at 'credited' from birth: it is a reversal with
|
||||
// nothing to attest or pay, so it must never enter the attest queue.
|
||||
const insertedRow = findCall('supplier_invoices', 'insert')?.[0]
|
||||
expect(insertedRow).toMatchObject({
|
||||
status: 'credited',
|
||||
is_credit_note: true,
|
||||
credited_invoice_id: 'invoice-1',
|
||||
remaining_amount: 0,
|
||||
supplier_invoice_number: 'KREDIT-LF-001',
|
||||
})
|
||||
const insertArgs = findCall('supplier_invoice_items', 'insert')
|
||||
const insertedItems = insertArgs?.[0] as Array<{ vat_rate: number }>
|
||||
expect(insertedItems[0]?.vat_rate).toBe(0.25)
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { createSupplierCreditNoteEntry } from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { supplierCreditNoteNeedsJournalEntry } from '@/lib/bookkeeping/booking-mode'
|
||||
import { buildSupplierCreditNoteRow } from '@/lib/supplier-invoices/credit-note'
|
||||
import { cancelSchedulesForSource } from '@/lib/bookkeeping/accruals/service'
|
||||
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
@@ -40,32 +41,14 @@ export const POST = withRouteContext(
|
||||
|
||||
const { data: creditNote, error: creditError } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
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,
|
||||
// Copy the original's dimension bag so the reversal nets against the
|
||||
// same dimension cells in reports (dimensions PR7).
|
||||
default_dimensions: original.default_dimensions ?? {},
|
||||
})
|
||||
.insert(
|
||||
buildSupplierCreditNoteRow(original, {
|
||||
userId: user.id,
|
||||
companyId,
|
||||
arrivalNumber: arrivalNum,
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
}),
|
||||
)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
|
||||
@@ -19,9 +19,7 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
|
||||
const { data: invoice, error } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(
|
||||
'*, supplier:suppliers(*), items:supplier_invoice_items(*), payments:supplier_invoice_payments(*), credited_original:supplier_invoices!credited_invoice_id(id, supplier_invoice_number, arrival_number)'
|
||||
)
|
||||
.select('*, supplier:suppliers(*), items:supplier_invoice_items(*), payments:supplier_invoice_payments(*)')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
@@ -30,7 +28,24 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
return NextResponse.json({ error: 'Supplier invoice not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: invoice })
|
||||
// The invoice a credit note reverses, fetched separately. credited_invoice_id
|
||||
// is a self-reference, and PostgREST cannot pick a direction for a
|
||||
// self-referencing embed from the column hint: the old
|
||||
// `credited_original:supplier_invoices!credited_invoice_id(...)` resolved to
|
||||
// the one-to-many side and came back as an empty array, which the detail
|
||||
// page rendered as "Krediterar: Ankomst #" with no number.
|
||||
let creditedOriginal: { id: string; supplier_invoice_number: string; arrival_number: number } | null = null
|
||||
if (invoice.credited_invoice_id) {
|
||||
const { data: original } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select('id, supplier_invoice_number, arrival_number')
|
||||
.eq('id', invoice.credited_invoice_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
creditedOriginal = original ?? null
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { ...invoice, credited_original: creditedOriginal } })
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { checkPeriodLock } from '@/lib/api/v1/check-period-lock'
|
||||
import { createSupplierCreditNoteEntry } from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { supplierCreditNoteNeedsJournalEntry } from '@/lib/bookkeeping/booking-mode'
|
||||
import {
|
||||
SUPPLIER_CREDIT_NOTE_STATUS,
|
||||
buildSupplierCreditNoteRow,
|
||||
} from '@/lib/supplier-invoices/credit-note'
|
||||
import { reverseEntry } from '@/lib/bookkeeping/engine'
|
||||
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
|
||||
import { eventBus } from '@/lib/events'
|
||||
@@ -250,7 +254,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
supplier_invoice_number: `KREDIT-${typed.supplier_invoice_number}`,
|
||||
invoice_date: today,
|
||||
due_date: today,
|
||||
status: 'registered',
|
||||
status: SUPPLIER_CREDIT_NOTE_STATUS,
|
||||
currency: typed.currency,
|
||||
exchange_rate: typed.exchange_rate,
|
||||
subtotal: typed.subtotal,
|
||||
@@ -281,32 +285,14 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
// Insert credit-note row.
|
||||
const { data: creditNote, error: creditErr } = await ctx.supabase
|
||||
.from('supplier_invoices')
|
||||
.insert({
|
||||
user_id: ctx.userId,
|
||||
company_id: ctx.companyId!,
|
||||
supplier_id: typed.supplier_id,
|
||||
arrival_number: arrivalNum,
|
||||
supplier_invoice_number: `KREDIT-${typed.supplier_invoice_number}`,
|
||||
invoice_date: today,
|
||||
due_date: today,
|
||||
status: 'registered',
|
||||
currency: typed.currency,
|
||||
exchange_rate: typed.exchange_rate,
|
||||
vat_treatment: typed.vat_treatment,
|
||||
reverse_charge: typed.reverse_charge,
|
||||
subtotal: typed.subtotal,
|
||||
subtotal_sek: typed.subtotal_sek,
|
||||
vat_amount: typed.vat_amount,
|
||||
vat_amount_sek: typed.vat_amount_sek,
|
||||
total: typed.total,
|
||||
total_sek: typed.total_sek,
|
||||
remaining_amount: 0,
|
||||
is_credit_note: true,
|
||||
credited_invoice_id: typed.id,
|
||||
// Copy the original's dimension bag so the credit-note verifikat nets
|
||||
// against the same dimension cells in reports (dimensions PR7).
|
||||
default_dimensions: typed.default_dimensions ?? {},
|
||||
})
|
||||
.insert(
|
||||
buildSupplierCreditNoteRow(typed, {
|
||||
userId: ctx.userId,
|
||||
companyId: ctx.companyId!,
|
||||
arrivalNumber: arrivalNum,
|
||||
date: today,
|
||||
}),
|
||||
)
|
||||
.select(SI_RESPONSE_COLUMNS)
|
||||
.single()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user