feat(sales-orders): kundorder with partial delivery and partial invoicing (#2166)
* feat(sales-orders): kundorder with partial delivery and partial invoicing Adds sales orders (kundorder) as their own non-ledger document between agreement and invoice, for companies that deliver or invoice in parts. Schema (20260902130000): sales_orders + sales_order_items with RLS via user_company_ids(), OR-<n> numbering RPC (membership-gated, no anon execute), company_settings.sales_orders_enabled UI gate, and back-links invoices.sales_order_id / invoice_items.sales_order_item_id. The invoiced quantity per order line is DERIVED from the linked invoice lines on non-cancelled, non-credited invoices and enforced by a BEFORE trigger, so no counter can drift and a credited invoice frees its quantity. Header status is draft / confirmed / completed / cancelled; completion is kept by DB triggers from the same derived quantity. Delivery and invoicing progress are derived per line, never stored as status. Service + API: lib/sales-orders (create/update with id-preserving line replace, transitions with compare-and-set, cumulative delivery registration, invoice-from-order through buildInvoiceWriteData so booking stays in the engine, proforma -> order conversion), routes under /api/sales-orders and /api/invoices/[id]/convert-to-order, structured SALES_ORDER_* error codes, archive classification of the new tables. The invoice editor round-trips sales_order_item_id so a draft edit cannot drop the link; GET /api/invoices gains ?sales_order_id=. UI: /sales-orders list, create/edit form reusing the invoice line conventions, detail with deliver and create-invoice dialogs and linked invoices; nav row behind the settings toggle; the webshop row is relabelled webshop_orders; "Skapa order" on proformas. MCP (20260902141000/141001): list/get reads plus four staged writes (create, transition, register delivery, create invoice from order) whose executors call the lib services; op types added to the pending operations CHECK. Tests: route tests for every route (401/400/404/happy), service unit tests, executor and tool tests, and tests/pg/sales-orders.pg.test.ts (16 cases, green on staging) covering RLS, numbering guards, the over-invoice trigger incl. release on cancel/credit and cross-company refusal, the quantity floor, and completion maintenance. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RQW7mXvbAPgjUHq7dSEamr * fix(sales-orders): harden kundorder after skeptic and security review Resolves every finding from the PR #2166 review pass in one batch. Order link integrity: replaceInvoiceItems now refuses a line set that drops an existing sales_order_item_id (INVOICE_UPDATE_DROPS_ORDER_LINK), closing the MCP update_invoice header-only edit and the v1 PATCH path that severed the link and freed the quantity for double invoicing. The update_invoice re-fetch, gnubok_get_invoice and the v1 item projection now carry sales_order_item_id so well-behaved clients round-trip it. Quantity math: derived remaining/invoiced quantities are rounded to six decimals and compared with an epsilon (roundQty, qtyGreater) so a float remainder such as 0.5999999999999996 can neither refuse the final partial invoice nor land as an invoice quantity; duplicate explicit picks are summed before validation. Leveransdatum: per-line last_delivery_date (migration 20260902160000); an invoice takes the latest date over the lines it covers and only when the covered quantity was delivered, never the header date and never for an advance invoice (ML 17 kap 24 p.7, FX anchor per ML 8 kap 21-23). VAT drift: the order stores the customer type and VAT-validation flag its lines were priced under; invoicing refuses with SALES_ORDER_CUSTOMER_VAT_CHANGED when they differ, and re-saving the order re-validates the lines. Customer and currency are frozen once invoices exist. Tenant and role gates: composite FK (sales_order_id, company_id) ties a line to its parent's company (Superagent P2); aa_enforce_company_writer_role on both tables so a viewer cannot write through the browser client. Proforma -> order refuses proformas with ROT/RUT, periodisering or negative-quantity lines instead of dropping those fields. RESTRICT FK errors on delete map to SALES_ORDER_LINE_LOCKED / SALES_ORDER_HAS_INVOICES. Also: schema-guard literal payloads in lib/sales-orders (ceiling +2 with reason), regenerated skills/accounted-api (sales_order_item_id on invoice items), pg tests for the composite FK, the viewer gate and the new columns, unit tests for every changed path. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): resolve CodeRabbit round on PR #2166 Quick wins from the review, all in one pass: - replaceInvoiceItems fails closed when the invoice_items snapshot cannot be read (it is both the restore source and the input to the kundorder link guard); the guard branch is explicit in both PATCH routes. - Cumulative delivery registration carries an optimistic predicate on the quantity it read, so two concurrent registrations cannot regress each other; DELETE of an order keeps its allowed status in the predicate and answers a conflict when zero rows match. - Business dates (order date, delivery date, invoice date) default to the Europe/Stockholm calendar day (todayIsoStockholm), never UTC: the delivery date is also the Riksbanken rate anchor. - The invoice-from-order executor treats an event emit failure as non-blocking: the draft already exists. - sales_order_items are archived through their parent with the order currency denormalised, like invoice_items. - Proforma "Skapa order" tolerates a 2xx without a parsable body; the settings toggle refreshes the server-rendered nav. - List route doc states that q matches the order number (customer names are matched client-side). Declined (out of scope for this PR): moving header + line writes and the delivery loop into transactional RPCs (same PostgREST pattern as the invoice PATCH path, tracked as a follow-up), the MCP approval handler's error message shape (pre-existing code outside this change), and the docstring-coverage warning (no repo convention). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): move hardening migration off a colliding version; archive contract; ceiling - 20260902160000_sales_orders_hardening.sql collided with main's 20260902160000_parties_substrate.sql after the third sync; renamed to 20260902180000 and made idempotent (DROP ... IF EXISTS before each ADD CONSTRAINT) so a preview branch that applied it under the old version replays it cleanly. Staging's schema_migrations row renamed. - sales_order_items goes back to a direct archive dump: the coverage contract (tests/pg/full-archive-coverage.pg.test.ts) requires it for a table with its own company_id; the currency lives on the parent order one file over, joined by sales_order_id. - Scanner ceiling re-baselined after merging main (parties phase 1): 397. - v1 PATCH test queues a real empty invoice_items snapshot now that replaceInvoiceItems fails closed on an unreadable one. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): drop the composite FK before its unique index on replay The idempotent guard in 20260902180000_sales_orders_hardening.sql dropped the unique (id, company_id) before the FK that depends on its index, so the preview branch replay (which had applied the file under its former version) failed with SQLSTATE 2BP01. Order swapped; replay verified on staging. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
c40e63e3f7
commit
c0818bb2d2
@@ -25,6 +25,7 @@ function makeItem(overrides: Partial<InvoiceWriteItemRow> = {}): InvoiceWriteIte
|
||||
vat_amount: 250,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
sales_order_item_id: null,
|
||||
deduction_type: null,
|
||||
deduction_amount: 0,
|
||||
labor_hours: null,
|
||||
@@ -62,6 +63,7 @@ function storedRow(overrides: Record<string, unknown> = {}): Record<string, unkn
|
||||
}
|
||||
|
||||
function createHarness(opts: {
|
||||
/** Snapshot rows; omit for an empty draft, pass null for "no rows came back". */
|
||||
snapshot?: unknown[] | null
|
||||
snapshotError?: unknown
|
||||
deleteError?: unknown
|
||||
@@ -69,16 +71,19 @@ function createHarness(opts: {
|
||||
insertErrors?: (unknown | null)[]
|
||||
}) {
|
||||
const inserts: Record<string, unknown>[][] = []
|
||||
const deletes: string[] = []
|
||||
let insertCall = 0
|
||||
const snapshot = opts.snapshot === undefined ? [] : opts.snapshot
|
||||
const supabase = {
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
eq: vi.fn(() =>
|
||||
Promise.resolve({ data: opts.snapshot ?? [], error: opts.snapshotError ?? null }),
|
||||
),
|
||||
eq: vi.fn(() => Promise.resolve({ data: snapshot, error: opts.snapshotError ?? null })),
|
||||
})),
|
||||
delete: vi.fn(() => ({
|
||||
eq: vi.fn(() => Promise.resolve({ error: opts.deleteError ?? null })),
|
||||
eq: vi.fn((_column: string, value: string) => {
|
||||
deletes.push(value)
|
||||
return Promise.resolve({ error: opts.deleteError ?? null })
|
||||
}),
|
||||
})),
|
||||
insert: vi.fn((rows: Record<string, unknown>[]) => {
|
||||
inserts.push(rows)
|
||||
@@ -88,11 +93,115 @@ function createHarness(opts: {
|
||||
}),
|
||||
})),
|
||||
}
|
||||
return { supabase: supabase as unknown as SupabaseClient, inserts }
|
||||
return { supabase: supabase as unknown as SupabaseClient, inserts, deletes }
|
||||
}
|
||||
|
||||
const insertBoom = { message: 'insert boom', code: '23502' }
|
||||
|
||||
const ORDER_LINE_1 = 'd1000000-0000-4000-8000-000000000001'
|
||||
const ORDER_LINE_2 = 'd1000000-0000-4000-8000-000000000002'
|
||||
|
||||
const guardResult = {
|
||||
ok: false,
|
||||
stage: 'guard',
|
||||
code: 'INVOICE_UPDATE_DROPS_ORDER_LINK',
|
||||
messageSv: expect.stringContaining('kundorder'),
|
||||
}
|
||||
|
||||
describe('replaceInvoiceItems order-link guard', () => {
|
||||
it('refuses before deleting when the new lines drop a sales_order_item_id link', async () => {
|
||||
const { supabase, inserts, deletes } = createHarness({
|
||||
snapshot: [storedRow({ sales_order_item_id: ORDER_LINE_1 })],
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: null })])
|
||||
|
||||
expect(result).toEqual(guardResult)
|
||||
expect(deletes).toHaveLength(0)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('proceeds when every existing link is kept on the new lines', async () => {
|
||||
const { supabase, inserts, deletes } = createHarness({
|
||||
snapshot: [
|
||||
storedRow({ sales_order_item_id: ORDER_LINE_1 }),
|
||||
storedRow({ id: 'item-old-2', sort_order: 1, sales_order_item_id: ORDER_LINE_2 }),
|
||||
],
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [
|
||||
// Reordered and with an extra unlinked line: still covers both links.
|
||||
makeItem({ sort_order: 0, sales_order_item_id: ORDER_LINE_2 }),
|
||||
makeItem({ sort_order: 1, description: 'Fri rad', sales_order_item_id: null }),
|
||||
makeItem({ sort_order: 2, sales_order_item_id: ORDER_LINE_1 }),
|
||||
])
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(deletes).toEqual(['inv-1'])
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(inserts[0].map((r) => r.sales_order_item_id)).toEqual([ORDER_LINE_2, null, ORDER_LINE_1])
|
||||
})
|
||||
|
||||
it('proceeds when the draft carries no order links at all', async () => {
|
||||
const { supabase, inserts, deletes } = createHarness({
|
||||
snapshot: [storedRow({ sales_order_item_id: null }), storedRow({ id: 'item-old-2', sort_order: 1 })],
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ description: 'Ny rad' })])
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(deletes).toEqual(['inv-1'])
|
||||
expect(inserts).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('compares links as a multiset: two rows on the same order line need two links back', async () => {
|
||||
const { supabase, inserts } = createHarness({
|
||||
snapshot: [
|
||||
storedRow({ sales_order_item_id: ORDER_LINE_1 }),
|
||||
storedRow({ id: 'item-old-2', sort_order: 1, sales_order_item_id: ORDER_LINE_1 }),
|
||||
],
|
||||
})
|
||||
|
||||
const dropped = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: ORDER_LINE_1 })])
|
||||
expect(dropped).toEqual(guardResult)
|
||||
expect(inserts).toHaveLength(0)
|
||||
|
||||
const kept = await replaceInvoiceItems(supabase, 'inv-1', [
|
||||
makeItem({ sales_order_item_id: ORDER_LINE_1 }),
|
||||
makeItem({ sort_order: 1, sales_order_item_id: ORDER_LINE_1 }),
|
||||
])
|
||||
expect(kept).toEqual({ ok: true })
|
||||
expect(inserts).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('refuses when a link is swapped for a different order line', async () => {
|
||||
const { supabase, inserts } = createHarness({
|
||||
snapshot: [storedRow({ sales_order_item_id: ORDER_LINE_1 })],
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: ORDER_LINE_2 })])
|
||||
|
||||
expect(result).toEqual(guardResult)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('fails closed before deleting when the snapshot could not be read (guard cannot run)', async () => {
|
||||
// Without the snapshot the link multiset is unknown: a draft that may
|
||||
// carry order links must not be emptied on a guess.
|
||||
const selectBoom = { message: 'select boom' }
|
||||
const { supabase, inserts, deletes } = createHarness({
|
||||
snapshot: null,
|
||||
snapshotError: selectBoom,
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem()])
|
||||
|
||||
expect(result).toEqual({ ok: false, stage: 'delete', error: selectBoom })
|
||||
expect(deletes).toEqual([])
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('replaceInvoiceItems', () => {
|
||||
it('replaces the rows and stamps invoice_id on the happy path', async () => {
|
||||
const { supabase, inserts } = createHarness({ snapshot: [storedRow()] })
|
||||
@@ -145,19 +254,24 @@ describe('replaceInvoiceItems', () => {
|
||||
expect(inserts).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('reports restored: false when the snapshot itself could not be read', async () => {
|
||||
// With no snapshot there is nothing to reinsert, and claiming the draft is
|
||||
// intact would be a guess: the delete may well have removed real rows.
|
||||
const { supabase, inserts } = createHarness({
|
||||
it('refuses at the delete stage when the snapshot read returns no rows at all (null, no error)', async () => {
|
||||
// A null snapshot without a driver error still leaves nothing to restore
|
||||
// and nothing to guard against: the function stops before the delete
|
||||
// instead of proceeding and later reporting restored: false.
|
||||
const { supabase, inserts, deletes } = createHarness({
|
||||
snapshot: null,
|
||||
snapshotError: { message: 'select boom' },
|
||||
insertErrors: [insertBoom],
|
||||
})
|
||||
|
||||
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem()])
|
||||
|
||||
expect(result).toMatchObject({ ok: false, stage: 'insert', restored: false })
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
stage: 'delete',
|
||||
error: { code: 'SNAPSHOT_UNAVAILABLE', message: 'invoice_items snapshot unavailable' },
|
||||
})
|
||||
expect(deletes).toEqual([])
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('reports restored: true when the draft had no items to begin with', async () => {
|
||||
|
||||
@@ -53,6 +53,9 @@ export interface InvoiceWriteItemInput {
|
||||
vat_rate?: number
|
||||
article_id?: string | null
|
||||
revenue_account?: string | null
|
||||
/** Kundorder line this invoice line was created from; round-tripped on
|
||||
* edit so the order's derived invoiced quantity never loses a link. */
|
||||
sales_order_item_id?: string | null
|
||||
deduction_type?: 'rot' | 'rut' | null
|
||||
labor_hours?: number | null
|
||||
work_type?: string | null
|
||||
@@ -142,6 +145,7 @@ export type InvoiceWriteItemRow = {
|
||||
vat_amount: number
|
||||
article_id: string | null
|
||||
revenue_account: string | null
|
||||
sales_order_item_id: string | null
|
||||
deduction_type: 'rot' | 'rut' | null
|
||||
deduction_amount: number
|
||||
labor_hours: number | null
|
||||
@@ -564,6 +568,7 @@ export async function buildInvoiceWriteData(params: {
|
||||
vat_amount: 0,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
sales_order_item_id: null,
|
||||
deduction_type: null,
|
||||
deduction_amount: 0,
|
||||
labor_hours: null,
|
||||
@@ -610,6 +615,7 @@ export async function buildInvoiceWriteData(params: {
|
||||
// VAT-treatment-derived account in generatePerRateLines().
|
||||
article_id: item.article_id ?? null,
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
sales_order_item_id: item.sales_order_item_id ?? null,
|
||||
deduction_type: deductionType,
|
||||
deduction_amount: deductionAmount,
|
||||
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
|
||||
|
||||
@@ -18,6 +18,8 @@ import type { InvoiceWriteItemRow } from '@/lib/invoices/build-invoice-write'
|
||||
* snapshot/restore idiom as commitUpdateRecurringSchedule in
|
||||
* lib/pending-operations/commit.ts. `restored` on the insert-failure shape
|
||||
* says whether the previous rows are back; the success path is unchanged.
|
||||
* An unreadable snapshot refuses the replace outright: it is both the
|
||||
* restore source and the input to the kundorder link guard below.
|
||||
*
|
||||
* Shared by the cookie PATCH route (app/api/invoices/[id]), the v1 REST PATCH
|
||||
* route, and the update_invoice commit executor so the replace logic cannot
|
||||
@@ -25,6 +27,14 @@ import type { InvoiceWriteItemRow } from '@/lib/invoices/build-invoice-write'
|
||||
*/
|
||||
export type ReplaceInvoiceItemsResult =
|
||||
| { ok: true }
|
||||
/**
|
||||
* Refused before any write: the draft was created from a kundorder and the
|
||||
* new line set drops one or more sales_order_item_id links. The order's
|
||||
* invoiced quantity is derived from those links, so losing them would free
|
||||
* the quantity for a second invoice. Every caller (cookie PATCH, v1 PATCH,
|
||||
* update_invoice executor) surfaces this as INVOICE_UPDATE_DROPS_ORDER_LINK.
|
||||
*/
|
||||
| { ok: false; stage: 'guard'; code: 'INVOICE_UPDATE_DROPS_ORDER_LINK'; messageSv: string }
|
||||
| { ok: false; stage: 'delete'; error: PostgrestError }
|
||||
| {
|
||||
ok: false
|
||||
@@ -55,6 +65,48 @@ export async function replaceInvoiceItems(
|
||||
.select('*')
|
||||
.eq('invoice_id', invoiceId)
|
||||
|
||||
// Order-link guard: a line set that forgets sales_order_item_id (a client
|
||||
// that read the lines through a projection without it, or a header-only
|
||||
// edit path that re-reads a narrow column list) must not silently sever
|
||||
// the kundorder link. Compare the link multiset before deleting anything.
|
||||
if (snapshotError || !snapshotRows) {
|
||||
// Without the snapshot the guard cannot run and the restore path has
|
||||
// nothing to put back: refuse rather than fail open on a draft that may
|
||||
// carry order links.
|
||||
return {
|
||||
ok: false,
|
||||
stage: 'delete',
|
||||
error:
|
||||
snapshotError ??
|
||||
({ message: 'invoice_items snapshot unavailable', code: 'SNAPSHOT_UNAVAILABLE' } as PostgrestError),
|
||||
}
|
||||
}
|
||||
{
|
||||
const existingLinks = (snapshotRows as Array<{ sales_order_item_id?: string | null }>)
|
||||
.map((row) => row.sales_order_item_id)
|
||||
.filter((id): id is string => typeof id === 'string')
|
||||
if (existingLinks.length > 0) {
|
||||
const incoming = new Map<string, number>()
|
||||
for (const item of items) {
|
||||
const link = (item as { sales_order_item_id?: string | null }).sales_order_item_id
|
||||
if (link) incoming.set(link, (incoming.get(link) ?? 0) + 1)
|
||||
}
|
||||
for (const link of existingLinks) {
|
||||
const left = incoming.get(link) ?? 0
|
||||
if (left === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
stage: 'guard',
|
||||
code: 'INVOICE_UPDATE_DROPS_ORDER_LINK',
|
||||
messageSv:
|
||||
'Fakturan är skapad från en kundorder och ändringen skulle tappa kopplingen till orderraderna.',
|
||||
}
|
||||
}
|
||||
incoming.set(link, left - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { error: deleteError } = await supabase
|
||||
.from('invoice_items')
|
||||
.delete()
|
||||
@@ -69,10 +121,10 @@ export async function replaceInvoiceItems(
|
||||
if (insertError) {
|
||||
// Best-effort restore of the snapshot so the draft keeps its lines. A
|
||||
// failed (or impossible) restore is reported, never swallowed.
|
||||
// The snapshot is guaranteed here: an unreadable one refuses the replace
|
||||
// before the delete (order-link guard above).
|
||||
let restored = false
|
||||
if (snapshotError || snapshotRows == null) {
|
||||
restored = false
|
||||
} else if (snapshotRows.length === 0) {
|
||||
if (snapshotRows.length === 0) {
|
||||
// Nothing existed before, so the draft is already in its prior state.
|
||||
restored = true
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user