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:
Mattsson
2026-09-02 18:14:49 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent c40e63e3f7
commit c0818bb2d2
80 changed files with 11247 additions and 32 deletions
+112
View File
@@ -548,6 +548,12 @@ export interface CompanySettings {
// for correctness. The nav row also shows when mileage_trips rows exist.
mileage_enabled: boolean
// Kundorder (sales orders): UI-visibility toggle only, never load-bearing
// for correctness (the /sales-orders pages and APIs work regardless).
sales_orders_enabled: boolean
// Per-company counter behind generate_sales_order_number (OR-<n>).
next_sales_order_number?: number
// Data analysis consent (migration 20260828120000): when true, the
// company's bookkeeping outcomes may be read across companies to evaluate
// and improve automatic booking. Default false, enforced server-side
@@ -942,6 +948,96 @@ export interface SupplierPaymentBatchItem {
created_at: string
}
// Kundorder (sales order): the non-ledger document between agreement and
// invoice. Never books. Four-state header machine; delivery and invoicing
// progress are derived per line (see SalesOrderItem.invoiced_qty).
export type SalesOrderStatus = 'draft' | 'confirmed' | 'completed' | 'cancelled'
/** Derived per-axis progress: none / partial / full. */
export type SalesOrderProgress = 'none' | 'partial' | 'full'
export interface SalesOrder {
id: string
company_id: string
user_id: string
customer_id: string | null
/** OR-<n>, allocated at creation by generate_sales_order_number. */
order_number: string | null
status: SalesOrderStatus
/** Proforma the order was converted from, if any. */
source_invoice_id: string | null
order_date: string
requested_delivery_date: string | null
/** Latest registered delivery date across all lines (display only; invoices use per-line dates). */
last_delivery_date: string | null
/** Customer facts the lines were VAT-validated under; invoicing refuses when they changed. */
customer_type_snapshot?: CustomerType | null
customer_vat_validated_snapshot?: boolean | null
currency: string
subtotal: number
vat_amount: number
total: number
your_reference: string | null
our_reference: string | null
notes: string | null
default_dimensions: Record<string, string>
confirmed_at: string | null
completed_at: string | null
cancelled_at: string | null
created_at: string
updated_at: string
// Embeds / derived (list + detail responses)
customer?: Customer | null
items?: SalesOrderItem[]
delivery_progress?: SalesOrderProgress
invoicing_progress?: SalesOrderProgress
}
export interface SalesOrderItem {
id: string
company_id: string
sales_order_id: string
sort_order: number
line_type: 'product' | 'text'
description: string
quantity: number
/** Stored: registered by the user via the deliver action. */
delivered_qty: number
/** Latest delivery date registered for this line (null until delivered). */
last_delivery_date?: string | null
unit: string
unit_price: number
discount_percent: number
vat_rate: number
/** NET of discount, order currency. */
line_total: number
article_id: string | null
revenue_account: string | null
dimensions: Record<string, string>
created_at: string
updated_at: string
/** Derived from linked invoice_items on non-cancelled, non-credited invoices. */
invoiced_qty?: number
/** quantity - invoiced_qty (never negative). */
remaining_qty?: number
}
export interface SalesOrderItemInput {
id?: string
line_type?: 'product' | 'text'
description: string
quantity: number
unit: string
unit_price: number
discount_percent?: number | null
vat_rate?: number
article_id?: string | null
revenue_account?: string | null
dimensions?: Record<string, string>
}
// Article (artikelregister): reusable invoice-line preset. NON-INVENTORY:
// no stock fields and no inventory postings, by deliberate design.
export type ArticleType = 'vara' | 'tjanst'
@@ -1234,6 +1330,10 @@ export interface Invoice {
// Conversion tracking (proforma -> invoice)
converted_from_id: string | null
// Kundorder this invoice was created from (sales_orders.id). Header-level
// provenance only; the per-line link is invoice_items.sales_order_item_id.
sales_order_id?: string | null
// Self-billing received (mottagen självfaktura, ML 17 kap 15§). When
// `is_self_billed` is true the customer issued the invoice on our behalf;
// for us it is a sale. The counterparty's number lives in
@@ -1388,6 +1488,12 @@ export interface InvoiceItem {
article_id?: string | null
revenue_account?: string | null
// Kundorder line this invoice line was created from. The order line's
// invoiced quantity is DERIVED from these links (never stored), so an
// edit that drops the link would free the quantity for double invoicing:
// every write path round-trips it.
sales_order_item_id?: string | null
// Periodisering (förutbetald intäkt): when set, the revenue entry credits
// accrual_balance_account (29xx) instead of the line's revenue account, and
// an accrual_schedules row dissolves the net amount monthly over the
@@ -2205,6 +2311,12 @@ export type PendingOperationType =
| 'update_company_settings'
| 'create_article'
| 'update_article'
// Kundorder (gnubok_create_sales_order / _transition_sales_order /
// _register_sales_order_delivery / _create_invoice_from_sales_order)
| 'create_sales_order'
| 'transition_sales_order'
| 'register_sales_order_delivery'
| 'create_invoice_from_sales_order'
// Kontoplan reference data (gnubok_create_account / gnubok_update_account)
| 'create_account'
| 'update_account'