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
@@ -411,6 +411,10 @@ export const CreateInvoiceItemSchema = z
|
||||
// accounts are only accepted on zero-VAT lines (build-invoice-write.ts).
|
||||
article_id: uuid.nullable().optional(),
|
||||
revenue_account: invoicePostingAccount.nullable().optional(),
|
||||
// Kundorder provenance: the order line this invoice line was created
|
||||
// from. Round-tripped on draft edits; the DB trigger refuses a quantity
|
||||
// that would over-invoice the order line.
|
||||
sales_order_item_id: uuid.nullable().optional(),
|
||||
// ROT/RUT-avdrag fields. `deduction_amount` is intentionally omitted from
|
||||
// the client schema: the API computes it from rot-rut-rules.ts so a
|
||||
// tampered client can't expand the 1513 receivable beyond the line total.
|
||||
@@ -2284,6 +2288,9 @@ export const UpdateSettingsSchema = z.object({
|
||||
// Körjournal (mileage log): UI-visibility toggle only, never load-bearing
|
||||
// for correctness (trips created via API/MCP work regardless).
|
||||
mileage_enabled: z.boolean().optional(),
|
||||
// Kundorder (sales orders): UI-visibility toggle only, never load-bearing
|
||||
// for correctness (the pages and APIs work regardless).
|
||||
sales_orders_enabled: z.boolean().optional(),
|
||||
// Data analysis consent (#1346): gates cross-company analysis of this
|
||||
// company's bookkeeping outcomes. Flipped by a human in the settings UI
|
||||
// only; deliberately absent from the v1 REST / MCP settings pick lists.
|
||||
@@ -3780,3 +3787,93 @@ export const BrandAllowlistAddSchema = z.object({
|
||||
export const BrandAllowlistRemoveSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Kundorder (sales orders) schemas
|
||||
// ============================================================
|
||||
|
||||
// Order lines mirror the invoice line shape (same editor, same line math)
|
||||
// minus the invoice-only fields (ROT/RUT, periodisering). Text rows carry a
|
||||
// description only.
|
||||
export const SalesOrderItemSchema = z
|
||||
.object({
|
||||
id: uuid.optional(),
|
||||
line_type: z.enum(['product', 'text']).optional(),
|
||||
description: z.string().max(2000),
|
||||
quantity: z.number().nonnegative(),
|
||||
unit: z.string().max(32),
|
||||
unit_price: z.number(),
|
||||
discount_percent: z.number().min(0).max(100).nullable().optional(),
|
||||
vat_rate: z.number().min(0).max(100).optional(),
|
||||
article_id: uuid.nullable().optional(),
|
||||
revenue_account: invoicePostingAccount.nullable().optional(),
|
||||
dimensions: DimensionsBagSchema.optional(),
|
||||
})
|
||||
.superRefine((item, ctx) => {
|
||||
if (item.line_type === 'text') return
|
||||
if (!item.description.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['description'], message: 'Beskrivning krävs' })
|
||||
}
|
||||
})
|
||||
|
||||
export const CreateSalesOrderSchema = z.object({
|
||||
customer_id: uuid,
|
||||
order_date: isoDate.optional(),
|
||||
requested_delivery_date: isoDate.nullable().optional(),
|
||||
currency: CurrencySchema.optional(),
|
||||
your_reference: z.string().max(200).nullable().optional(),
|
||||
our_reference: z.string().max(200).nullable().optional(),
|
||||
notes: z.string().max(4000).nullable().optional(),
|
||||
default_dimensions: DimensionsBagSchema.optional(),
|
||||
items: z.array(SalesOrderItemSchema).min(1, 'Minst en orderrad krävs').max(500),
|
||||
})
|
||||
|
||||
// Full replace of header + lines. Lines that carry an `id` keep their
|
||||
// delivered/invoiced history (the DB refuses lowering quantity below the
|
||||
// invoiced quantity); lines without an id are new; omitted ids are deleted.
|
||||
export const UpdateSalesOrderSchema = CreateSalesOrderSchema.partial().extend({
|
||||
items: z.array(SalesOrderItemSchema).min(1).max(500).optional(),
|
||||
})
|
||||
|
||||
export const SalesOrderTransitionSchema = z.object({
|
||||
action: z.enum(['confirm', 'cancel', 'reopen']),
|
||||
})
|
||||
|
||||
export const RegisterSalesOrderDeliverySchema = z.object({
|
||||
delivery_date: isoDate.optional(),
|
||||
lines: z
|
||||
.array(
|
||||
z.object({
|
||||
sales_order_item_id: uuid,
|
||||
// Cumulative delivered quantity after this registration (not a delta):
|
||||
// idempotent on retry, and what the user sees in the dialog.
|
||||
delivered_qty: z.number().nonnegative(),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(500),
|
||||
})
|
||||
|
||||
export const CreateInvoiceFromSalesOrderSchema = z.object({
|
||||
// Explicit picks win. Without them, `mode` selects the lines:
|
||||
// remaining = every line with quantity left to invoice (default)
|
||||
// delivered = only what has been delivered but not yet invoiced
|
||||
mode: z.enum(['remaining', 'delivered']).optional(),
|
||||
lines: z
|
||||
.array(
|
||||
z.object({
|
||||
sales_order_item_id: uuid,
|
||||
quantity: z.number().positive(),
|
||||
}),
|
||||
)
|
||||
.max(500)
|
||||
.optional(),
|
||||
invoice_date: isoDate.optional(),
|
||||
due_date: isoDate.optional(),
|
||||
})
|
||||
|
||||
export const SalesOrderListQuerySchema = z.object({
|
||||
status: z.enum(['draft', 'confirmed', 'completed', 'cancelled']).optional(),
|
||||
customer_id: uuid.optional(),
|
||||
q: z.string().max(200).optional(),
|
||||
})
|
||||
|
||||
@@ -35,4 +35,4 @@ export const INVOICE_PDF_COLUMNS =
|
||||
'paid_amount, remaining_amount, deduction_total, deduction_personnummer_last4'
|
||||
|
||||
export const INVOICE_ITEM_FULL_COLUMNS =
|
||||
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, created_at'
|
||||
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, sales_order_item_id, created_at'
|
||||
|
||||
@@ -16,8 +16,8 @@ export const API_KEY_SCOPES = {
|
||||
'customers:write': { label: 'Kunder: skriv', description: 'Skapa och uppdatera kunder' },
|
||||
'articles:read': { label: 'Artiklar: läs', description: 'Lista artiklar i artikelregistret' },
|
||||
'articles:write': { label: 'Artiklar: skriv', description: 'Skapa och uppdatera artiklar' },
|
||||
'invoices:read': { label: 'Fakturor: läs', description: 'Lista fakturor' },
|
||||
'invoices:write': { label: 'Fakturor: skriv', description: 'Skapa, skicka, markera betald/skickad' },
|
||||
'invoices:read': { label: 'Fakturor: läs', description: 'Lista fakturor och kundorder' },
|
||||
'invoices:write': { label: 'Fakturor: skriv', description: 'Skapa, skicka, markera betald/skickad; kundorder (skapa, bekräfta, leverera, fakturera)' },
|
||||
'suppliers:read': { label: 'Leverantörer: läs', description: 'Lista leverantörer och leverantörsfakturor, hitta verifikat-kandidater' },
|
||||
'suppliers:write': { label: 'Leverantörer: skriv', description: 'Skapa leverantörer; godkänn, kreditera, betal-länka och hantera leverantörsfakturor' },
|
||||
'reports:read': { label: 'Rapporter: läs', description: 'Kontoplan, huvudbok, balansräkning, resultaträkning, moms, KPI, reskontra, perioder, bankavstämning, SIE-export' },
|
||||
@@ -260,6 +260,14 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_send_invoice: 'invoices:write',
|
||||
gnubok_mark_invoice_as_paid: 'invoices:write',
|
||||
gnubok_mark_invoice_as_sent: 'invoices:write',
|
||||
// Kundorder (sales orders): the pre-invoice document. Reads and staged
|
||||
// writes ride the invoice scopes (an order exists only to become one).
|
||||
gnubok_list_sales_orders: 'invoices:read',
|
||||
gnubok_get_sales_order: 'invoices:read',
|
||||
gnubok_create_sales_order: 'invoices:write',
|
||||
gnubok_transition_sales_order: 'invoices:write',
|
||||
gnubok_register_sales_order_delivery: 'invoices:write',
|
||||
gnubok_create_invoice_from_sales_order: 'invoices:write',
|
||||
// Recurring invoice schedules (staged template writes; no send/book at commit)
|
||||
gnubok_list_recurring_schedules: 'invoices:read',
|
||||
gnubok_create_recurring_schedule: 'invoices:write',
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { addDaysIso, daysBetweenIso, todayIsoStockholm, toIsoDate } from '../iso'
|
||||
|
||||
describe('todayIsoStockholm', () => {
|
||||
it('rolls over to the next Swedish calendar day before UTC midnight (CEST, UTC+2)', () => {
|
||||
expect(todayIsoStockholm(new Date('2026-06-30T22:30:00Z'))).toBe('2026-07-01')
|
||||
})
|
||||
|
||||
it('keeps the same day at midday', () => {
|
||||
expect(todayIsoStockholm(new Date('2026-01-15T12:00:00Z'))).toBe('2026-01-15')
|
||||
})
|
||||
|
||||
it('rolls over one hour later in winter (CET, UTC+1)', () => {
|
||||
expect(todayIsoStockholm(new Date('2026-01-15T22:30:00Z'))).toBe('2026-01-15')
|
||||
expect(todayIsoStockholm(new Date('2026-01-15T23:30:00Z'))).toBe('2026-01-16')
|
||||
})
|
||||
|
||||
it('defaults to now and returns a YYYY-MM-DD string', () => {
|
||||
expect(todayIsoStockholm()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('UTC helpers', () => {
|
||||
it('addDaysIso is pure UTC arithmetic', () => {
|
||||
expect(addDaysIso('2026-02-28', 1)).toBe('2026-03-01')
|
||||
expect(addDaysIso('2026-03-29', 1)).toBe('2026-03-30')
|
||||
expect(addDaysIso('2026-01-01', -1)).toBe('2025-12-31')
|
||||
})
|
||||
|
||||
it('daysBetweenIso is signed', () => {
|
||||
expect(daysBetweenIso('2026-01-01', '2026-01-31')).toBe(30)
|
||||
expect(daysBetweenIso('2026-01-31', '2026-01-01')).toBe(-30)
|
||||
})
|
||||
|
||||
it('toIsoDate takes the UTC calendar date, unlike todayIsoStockholm', () => {
|
||||
const late = new Date('2026-06-30T22:30:00Z')
|
||||
expect(toIsoDate(late)).toBe('2026-06-30')
|
||||
expect(todayIsoStockholm(late)).toBe('2026-07-01')
|
||||
})
|
||||
})
|
||||
@@ -30,3 +30,19 @@ export function toIsoDate(d: Date): string {
|
||||
export function todayIsoUtc(): string {
|
||||
return new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/**
|
||||
* Today's calendar date in Europe/Stockholm as YYYY-MM-DD. Business dates
|
||||
* (order date, delivery date, invoice date) belong to the Swedish calendar
|
||||
* day, not UTC: near midnight the UTC date is still yesterday, and a
|
||||
* delivery date is also the Riksbanken rate anchor for foreign-currency
|
||||
* invoices.
|
||||
*/
|
||||
export function todayIsoStockholm(now: Date = new Date()): string {
|
||||
return new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: 'Europe/Stockholm',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).format(now)
|
||||
}
|
||||
|
||||
@@ -1364,6 +1364,92 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Detta dokument är inte en offert.',
|
||||
message_en: 'This document is not a quote.',
|
||||
},
|
||||
// Kundorder (sales orders): lib/sales-orders/*, app/api/sales-orders/*
|
||||
SALES_ORDER_NOT_FOUND: {
|
||||
httpStatus: 404,
|
||||
message_sv: 'Kundordern hittades inte.',
|
||||
message_en: 'The sales order was not found.',
|
||||
},
|
||||
SALES_ORDER_INVALID_STATE: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Kundordern har inte en status som tillåter den här åtgärden.',
|
||||
message_en: 'The sales order is not in a state that allows this action.',
|
||||
},
|
||||
SALES_ORDER_NOT_EDITABLE: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Kundordern kan bara ändras medan den är utkast eller bekräftad.',
|
||||
message_en: 'A sales order can only be edited while it is a draft or confirmed.',
|
||||
},
|
||||
SALES_ORDER_HAS_INVOICES: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Kundordern kan inte makuleras: det finns fakturor som skapats från den. Makulera eller kreditera fakturorna först.',
|
||||
message_en: 'The sales order cannot be cancelled: invoices have been created from it. Cancel or credit those invoices first.',
|
||||
},
|
||||
SALES_ORDER_LINE_NOT_FOUND: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'En angiven orderrad finns inte på kundordern.',
|
||||
message_en: 'A referenced line does not exist on the sales order.',
|
||||
},
|
||||
SALES_ORDER_OVER_INVOICED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Angivet antal överstiger vad som återstår att fakturera på orderraden.',
|
||||
message_en: 'The requested quantity exceeds what remains to be invoiced on the order line.',
|
||||
},
|
||||
SALES_ORDER_OVER_DELIVERED: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Levererat antal kan inte överstiga beställt antal.',
|
||||
message_en: 'Delivered quantity cannot exceed the ordered quantity.',
|
||||
},
|
||||
SALES_ORDER_QUANTITY_BELOW_INVOICED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Antalet på en orderrad kan inte sänkas under det som redan fakturerats.',
|
||||
message_en: 'An order line quantity cannot be lowered below what has already been invoiced.',
|
||||
},
|
||||
SALES_ORDER_NOTHING_TO_INVOICE: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Det finns inget kvar att fakturera på kundordern.',
|
||||
message_en: 'There is nothing left to invoice on the sales order.',
|
||||
},
|
||||
SALES_ORDER_CUSTOMER_MISSING: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Kundordern saknar kund. Ange en kund innan du fakturerar.',
|
||||
message_en: 'The sales order has no customer. Set a customer before invoicing.',
|
||||
},
|
||||
SALES_ORDER_CREATE_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Kundordern kunde inte sparas.',
|
||||
message_en: 'The sales order could not be saved.',
|
||||
},
|
||||
SALES_ORDER_LINE_LOCKED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'En orderrad med fakturerat eller levererat antal kan inte tas bort.',
|
||||
message_en: 'An order line with invoiced or delivered quantity cannot be removed.',
|
||||
},
|
||||
SALES_ORDER_SOURCE_NOT_PROFORMA: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Bara en proformafaktura kan omvandlas till kundorder.',
|
||||
message_en: 'Only a proforma invoice can be converted into a sales order.',
|
||||
},
|
||||
SALES_ORDER_SOURCE_UNSUPPORTED_LINES: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Proformafakturan innehåller rader som inte kan föras över till en kundorder (ROT/RUT-avdrag, periodisering eller negativt antal). Skapa kundordern manuellt.',
|
||||
message_en: 'The proforma has lines that cannot be carried into a sales order (ROT/RUT deduction, accrual period or negative quantity). Create the sales order manually.',
|
||||
},
|
||||
SALES_ORDER_CUSTOMER_VAT_CHANGED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Kundens momsuppgifter (kundtyp eller VAT-nummer) har ändrats sedan kundordern prissattes. Öppna och spara kundordern igen så att momssatserna kontrolleras innan du fakturerar.',
|
||||
message_en: 'The customer VAT facts (customer type or VAT number validation) changed after the sales order was priced. Open and save the order again so the VAT rates are re-checked before invoicing.',
|
||||
},
|
||||
INVOICE_UPDATE_DROPS_ORDER_LINK: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Fakturan är skapad från en kundorder och ändringen skulle tappa kopplingen till orderraderna. Skicka med sales_order_item_id på raderna, eller makulera fakturan och skapa en ny från kundordern.',
|
||||
message_en: 'The invoice was created from a sales order and this edit would drop the link to its order lines. Keep sales_order_item_id on the lines, or cancel the invoice and create a new one from the order.',
|
||||
},
|
||||
SALES_ORDER_SOURCE_ALREADY_CONVERTED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Proformafakturan har redan omvandlats till en kundorder.',
|
||||
message_en: 'The proforma has already been converted into a sales order.',
|
||||
},
|
||||
// POST /api/invoices/{id}/peppol/send. The Access Point is an environment
|
||||
// decision (PEPPOL_TRANSPORT_PROVIDER + adapter credentials); the product
|
||||
// never pretends to send when no adapter is switched on.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
/**
|
||||
* Executor tests for the four staged kundorder (sales order) operations.
|
||||
* The executors are private to commit.ts and reached through
|
||||
* commitPendingOperation (same pattern as ignore-transaction-executor.test.ts).
|
||||
*
|
||||
* The lib/sales-orders services are mocked: the executors own only the
|
||||
* commit-boundary re-validation, the service call and the mapping of a
|
||||
* ServiceFailure onto the CommitResult contract. Totals, VAT and the state
|
||||
* machine are the services' business and are tested there.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { PendingOperation, SalesOrder } from '@/types'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sales-orders/write', () => ({
|
||||
createSalesOrder: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/transitions', () => ({
|
||||
transitionSalesOrder: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/register-delivery', () => ({
|
||||
registerSalesOrderDelivery: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/create-invoice-from-order', () => ({
|
||||
createInvoiceFromSalesOrder: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createSalesOrder } from '@/lib/sales-orders/write'
|
||||
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
|
||||
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
|
||||
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
const ORDER_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
const CUSTOMER_ID = '00000000-0000-4000-8000-0000000000bb'
|
||||
const ITEM_ID = '00000000-0000-4000-8000-0000000000cc'
|
||||
const INVOICE_ID = '00000000-0000-4000-8000-0000000000dd'
|
||||
|
||||
function makeOrder(overrides: Partial<SalesOrder> = {}): SalesOrder {
|
||||
return {
|
||||
id: ORDER_ID,
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
customer_id: CUSTOMER_ID,
|
||||
order_number: 'OR-7',
|
||||
status: 'draft',
|
||||
source_invoice_id: null,
|
||||
order_date: '2026-09-01',
|
||||
requested_delivery_date: null,
|
||||
last_delivery_date: null,
|
||||
currency: 'SEK',
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
your_reference: null,
|
||||
our_reference: null,
|
||||
notes: null,
|
||||
default_dimensions: {},
|
||||
confirmed_at: null,
|
||||
completed_at: null,
|
||||
cancelled_at: null,
|
||||
created_at: '2026-09-01T00:00:00Z',
|
||||
updated_at: '2026-09-01T00:00:00Z',
|
||||
items: [],
|
||||
delivery_progress: 'none',
|
||||
invoicing_progress: 'none',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'create_sales_order',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: {},
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'low',
|
||||
created_at: '2026-09-01T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-09-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
const CREATE_PARAMS = {
|
||||
customer_id: CUSTOMER_ID,
|
||||
order_date: '2026-09-01',
|
||||
currency: 'SEK',
|
||||
items: [{ description: 'Konsulttimmar', quantity: 10, unit: 'tim', unit_price: 100 }],
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: create_sales_order', () => {
|
||||
it('happy path: validates the staged params, calls the service and returns the order ids', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, order_number: 'OR-7', status: 'draft', total: 1250 })
|
||||
expect(createSalesOrder).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
input: expect.objectContaining({ customer_id: CUSTOMER_ID, items: expect.any(Array) }),
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a coded service failure onto the structured error (CUSTOMER_NOT_FOUND -> 404 auto-reject)', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: CUSTOMER_ID } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // reject write
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(404)
|
||||
expect(result.code).toBe('CUSTOMER_NOT_FOUND')
|
||||
expect(result.data).toEqual({ customerId: CUSTOMER_ID })
|
||||
})
|
||||
|
||||
it('rejects tampered params at the commit boundary before the service runs', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // reject write
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: { ...CREATE_PARAMS, customer_id: 'not-a-uuid' } }),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(result.error).toMatch(/customer_id/)
|
||||
expect(createSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a raw DB failure as a 500 with the driver message', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, dbError: { message: 'connection reset' } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(500)
|
||||
expect(result.error).toBe('connection reset')
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: transition_sales_order', () => {
|
||||
it('happy path: confirms through the service', async () => {
|
||||
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'confirmed' }) })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'confirm' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, status: 'confirmed', action: 'confirm' })
|
||||
expect(transitionSalesOrder).toHaveBeenCalledWith(supabase, { companyId: 'company-1', orderId: ORDER_ID, action: 'confirm' })
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_HAS_INVOICES onto a 409 auto-reject', async () => {
|
||||
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_HAS_INVOICES' })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'cancel' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('SALES_ORDER_HAS_INVOICES')
|
||||
expect(result.error).toMatch(/fakturor/i)
|
||||
})
|
||||
|
||||
it('rejects an action outside the enum before the service runs', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'complete' } }),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.error).toMatch(/action/)
|
||||
expect(transitionSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: register_sales_order_delivery', () => {
|
||||
const params = {
|
||||
sales_order_id: ORDER_ID,
|
||||
delivery_date: '2026-09-02',
|
||||
lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }],
|
||||
}
|
||||
|
||||
it('happy path: passes the cumulative quantities to the service', async () => {
|
||||
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
|
||||
ok: true,
|
||||
order: makeOrder({ status: 'confirmed', last_delivery_date: '2026-09-02', delivery_progress: 'partial' }),
|
||||
})
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, last_delivery_date: '2026-09-02', delivery_progress: 'partial' })
|
||||
expect(registerSalesOrderDelivery).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
orderId: ORDER_ID,
|
||||
input: { delivery_date: '2026-09-02', lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }] },
|
||||
})
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_OVER_DELIVERED (400) onto a failed op with the line details', async () => {
|
||||
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_DELIVERED',
|
||||
details: { sales_order_item_id: ITEM_ID, quantity: 3, delivered_qty: 4 },
|
||||
})
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(result.code).toBe('SALES_ORDER_OVER_DELIVERED')
|
||||
expect(result.data).toMatchObject({ sales_order_item_id: ITEM_ID, quantity: 3 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: create_invoice_from_sales_order', () => {
|
||||
const params = { sales_order_id: ORDER_ID, mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' }
|
||||
const invoice = { id: INVOICE_ID, invoice_number: null, status: 'draft', total: 1250, currency: 'SEK' }
|
||||
|
||||
it('happy path: creates the draft through the service and emits invoice.created', async () => {
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
|
||||
ok: true,
|
||||
invoice: invoice as never,
|
||||
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
|
||||
})
|
||||
const handler = vi.fn()
|
||||
eventBus.on('invoice.created', handler)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({
|
||||
invoice_id: INVOICE_ID,
|
||||
invoice_number: null,
|
||||
sales_order_id: ORDER_ID,
|
||||
order_status: 'completed',
|
||||
invoicing_progress: 'full',
|
||||
})
|
||||
expect(createInvoiceFromSalesOrder).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
orderId: ORDER_ID,
|
||||
input: { mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' },
|
||||
})
|
||||
expect(handler).toHaveBeenCalledTimes(1)
|
||||
// Handlers receive the payload, not the envelope.
|
||||
expect(handler.mock.calls[0][0]).toMatchObject({
|
||||
invoice: expect.objectContaining({ id: INVOICE_ID }),
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('still commits when the invoice.created emit rejects (the draft already exists)', async () => {
|
||||
// eventBus.emit settles handler failures itself, so the only way the emit
|
||||
// can reject is the bus throwing; the executor must treat that as a
|
||||
// post-commit notification failure, not as a failed operation.
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
|
||||
ok: true,
|
||||
invoice: invoice as never,
|
||||
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
|
||||
})
|
||||
const emitSpy = vi.spyOn(eventBus, 'emit').mockRejectedValueOnce(new Error('bus down'))
|
||||
try {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ invoice_id: INVOICE_ID, sales_order_id: ORDER_ID })
|
||||
expect(emitSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'invoice.created' }),
|
||||
)
|
||||
} finally {
|
||||
emitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_NOTHING_TO_INVOICE onto a 409 auto-reject and emits nothing', async () => {
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
|
||||
const handler = vi.fn()
|
||||
eventBus.on('invoice.created', handler)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('SALES_ORDER_NOTHING_TO_INVOICE')
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a non-positive explicit pick at the commit boundary', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({
|
||||
operation_type: 'create_invoice_from_sales_order',
|
||||
params: { sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, quantity: 0 }] },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.error).toMatch(/lines\.0\.quantity/)
|
||||
expect(createInvoiceFromSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { commitPendingOperation } from '../commit'
|
||||
|
||||
const INVOICE_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const CUSTOMER_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const SALES_ORDER_ITEM_ID = 'd1000000-0000-4000-8000-000000000001'
|
||||
|
||||
function makePendingOp(params: Record<string, unknown>): PendingOperation {
|
||||
return {
|
||||
@@ -88,6 +89,7 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings (builder VAT gate)
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (draft-guarded)
|
||||
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no prior rows)
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // pending_operations final status update
|
||||
@@ -110,8 +112,10 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
items_replaced: true,
|
||||
})
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(2, 'invoices')
|
||||
// snapshot, delete, insert
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(6, 'invoice_items')
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(7, 'invoice_items')
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(8, 'invoice_items')
|
||||
})
|
||||
|
||||
it('keeps the existing lines on a header-only edit (no full replace staged)', async () => {
|
||||
@@ -146,6 +150,7 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
})
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
|
||||
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no order links)
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // final status update
|
||||
@@ -306,6 +311,96 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
expect(findCall('invoice_items', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('auto-rejects with INVOICE_UPDATE_DROPS_ORDER_LINK when replaced lines drop a kundorder link', async () => {
|
||||
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
||||
enqueue({ data: existingDraft() }) // invoices: existing draft (created from an order)
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (header)
|
||||
enqueue({
|
||||
// invoice_items snapshot (replaceInvoiceItems): the stored row is linked
|
||||
// to an order line; the staged items carry no sales_order_item_id.
|
||||
data: [{ id: 'item-old-1', invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID, description: 'Orderrad' }],
|
||||
})
|
||||
enqueue({ data: null }) // pending_operations final status update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp({ invoice_id: INVOICE_ID, changes: { items: NEW_ITEMS } }),
|
||||
)
|
||||
|
||||
// 409 from the executor: auto-rejected with the structured code so the
|
||||
// approver sees WHY, same as the cookie and v1 PATCH routes.
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.auto_rejected).toBe(true)
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('INVOICE_UPDATE_DROPS_ORDER_LINK')
|
||||
expect(result.error).toMatch(/kundorder/)
|
||||
// The guard fires before the delete: the lines are untouched.
|
||||
expect(findCall('invoice_items', 'delete')).toBeUndefined()
|
||||
expect(findCall('invoice_items', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the kundorder link on a header-only edit (re-fetch carries sales_order_item_id)', async () => {
|
||||
const { supabase, enqueue, findCall, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
||||
enqueue({ data: existingDraft() }) // invoices
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({
|
||||
// invoice_items re-fetch for the header-only edit
|
||||
data: [
|
||||
{
|
||||
line_type: 'product',
|
||||
description: 'Orderrad',
|
||||
quantity: 4,
|
||||
unit: 'h',
|
||||
unit_price: 100,
|
||||
discount_percent: null,
|
||||
vat_rate: 25,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
sales_order_item_id: SALES_ORDER_ITEM_ID,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
accrual_period_start: null,
|
||||
accrual_period_end: null,
|
||||
accrual_balance_account: null,
|
||||
dimensions: {},
|
||||
},
|
||||
],
|
||||
})
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
|
||||
enqueue({ data: [{ id: 'item-old-1', sales_order_item_id: SALES_ORDER_ITEM_ID }] }) // snapshot
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // final status update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'Ny anteckning' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ items_replaced: false, item_count: 1 })
|
||||
// The narrow re-fetch must include the link column, or the guard would
|
||||
// refuse every header-only edit of an order-created draft.
|
||||
const refetchColumns = findCalls('invoice_items', 'select')[0][0] as string
|
||||
expect(refetchColumns.split(',').map((c) => c.trim())).toContain('sales_order_item_id')
|
||||
const inserted = findCall('invoice_items', 'insert')![0] as Array<Record<string, unknown>>
|
||||
expect(inserted).toHaveLength(1)
|
||||
expect(inserted[0]).toMatchObject({ invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID })
|
||||
})
|
||||
|
||||
it('rejects tampered staged params before reading the invoice', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } })
|
||||
|
||||
@@ -156,6 +156,17 @@ import { defaultRateForVatTreatment } from '@/lib/vat/account-vat-treatment'
|
||||
import { SetVoucherNoteParamsSchema } from '@/lib/pending-operations/schemas/voucher-note'
|
||||
import { IgnoreTransactionParamsSchema } from '@/lib/pending-operations/schemas/ignore-transaction'
|
||||
import { setTransactionIgnored } from '@/lib/transactions/ignore'
|
||||
import {
|
||||
CreateInvoiceFromSalesOrderParamsSchema,
|
||||
CreateSalesOrderParamsSchema,
|
||||
RegisterSalesOrderDeliveryParamsSchema,
|
||||
TransitionSalesOrderParamsSchema,
|
||||
} from '@/lib/pending-operations/schemas/sales-order'
|
||||
import { createSalesOrder } from '@/lib/sales-orders/write'
|
||||
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
|
||||
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
|
||||
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
|
||||
import type { ServiceFailure } from '@/lib/sales-orders/result'
|
||||
import { UpdateCompanySettingsParamsSchema } from '@/lib/pending-operations/schemas/company-settings'
|
||||
import { UpdateCustomerParamsSchema } from '@/lib/pending-operations/schemas/customer'
|
||||
import {
|
||||
@@ -1282,6 +1293,192 @@ async function commitIgnoreTransaction(
|
||||
}
|
||||
}
|
||||
|
||||
// ── Kundorder (sales orders) ────────────────────────────────────────
|
||||
//
|
||||
// The four executors below never touch totals, VAT or the order state
|
||||
// machine themselves: they re-validate the staged params (ASVS V4.5) and
|
||||
// hand them to the lib/sales-orders service the cookie routes use, so the
|
||||
// MCP door and the web door produce identical rows and identical refusals.
|
||||
|
||||
/** Zod failure on a staged row -> 400 with the first issue named. */
|
||||
function invalidStagedParams(err: unknown): ExecutorResult {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a lib/sales-orders ServiceFailure onto the ExecutorResult contract.
|
||||
* A coded failure carries the structured-error httpStatus (404/409 auto-
|
||||
* reject the op, 400 fails it) and its Swedish message, with the service's
|
||||
* details persisted so the approver sees WHICH line was refused; a raw DB
|
||||
* failure is a 500 with the driver message.
|
||||
*/
|
||||
function salesOrderFailure(failure: ServiceFailure): ExecutorResult {
|
||||
if ('code' in failure) {
|
||||
const entry = getErrorEntry(failure.code)
|
||||
return {
|
||||
error: entry?.message_sv ?? failure.code,
|
||||
errorCode: failure.code,
|
||||
status: entry?.httpStatus ?? 400,
|
||||
...(failure.details ? { data: failure.details } : {}),
|
||||
}
|
||||
}
|
||||
const dbMessage =
|
||||
typeof failure.dbError === 'object' && failure.dbError !== null && 'message' in failure.dbError
|
||||
? String((failure.dbError as { message: unknown }).message)
|
||||
: null
|
||||
return { error: dbMessage || getErrorEntry('SALES_ORDER_CREATE_FAILED')?.message_sv || 'Kundordern kunde inte sparas.', status: 500 }
|
||||
}
|
||||
|
||||
async function commitCreateSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = CreateSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
const result = await createSalesOrder(supabase, { companyId, userId, input: validated })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
total: order.total,
|
||||
currency: order.currency,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitTransitionSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = TransitionSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
// The service re-reads the order and refuses a transition the current
|
||||
// status does not allow (compare-and-set), so an order that moved between
|
||||
// staging and approval lands as SALES_ORDER_INVALID_STATE, never as a
|
||||
// silent overwrite.
|
||||
const result = await transitionSalesOrder(supabase, {
|
||||
companyId,
|
||||
orderId: validated.sales_order_id,
|
||||
action: validated.action,
|
||||
})
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
action: validated.action,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitRegisterSalesOrderDelivery(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = RegisterSalesOrderDeliveryParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
const { sales_order_id: orderId, ...input } = validated
|
||||
const result = await registerSalesOrderDelivery(supabase, { companyId, orderId, input })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
last_delivery_date: order.last_delivery_date,
|
||||
delivery_progress: order.delivery_progress ?? null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCreateInvoiceFromSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = CreateInvoiceFromSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
// The service re-reads the order, re-picks the lines against the CURRENT
|
||||
// invoiced quantities and builds the draft through buildInvoiceWriteData,
|
||||
// so a line invoiced elsewhere between staging and approval is refused
|
||||
// (SALES_ORDER_OVER_INVOICED / NOTHING_TO_INVOICE) instead of double-billed.
|
||||
const { sales_order_id: orderId, ...input } = validated
|
||||
const result = await createInvoiceFromSalesOrder(supabase, { companyId, userId, orderId, input })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { invoice, order } = result
|
||||
|
||||
// Same event the direct create_invoice executor emits, so extension
|
||||
// handlers (webhooks, digests) see order-born drafts too.
|
||||
const { data: completeInvoice } = await supabase
|
||||
.from('invoices')
|
||||
.select('*, customer:customers(*), items:invoice_items(*)')
|
||||
.eq('id', invoice.id)
|
||||
.single()
|
||||
// Post-commit notification only: the draft already exists, so an event
|
||||
// failure must not reject an operation whose write succeeded.
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
payload: { invoice: (completeInvoice ?? invoice) as Invoice, userId, companyId },
|
||||
})
|
||||
} catch {
|
||||
// Non-critical
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
invoice_id: invoice.id,
|
||||
// Unnumbered draft: the F-series number is assigned on send.
|
||||
invoice_number: invoice.invoice_number ?? null,
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
order_status: order.status,
|
||||
invoicing_progress: order.invoicing_progress ?? null,
|
||||
total: invoice.total,
|
||||
currency: invoice.currency,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCreateSupplier(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -2061,7 +2258,7 @@ async function commitUpdateInvoice(
|
||||
const { data: itemRows, error: itemsFetchError } = await supabase
|
||||
.from('invoice_items')
|
||||
.select(
|
||||
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
|
||||
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, sales_order_item_id, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
|
||||
)
|
||||
.eq('invoice_id', invoiceId)
|
||||
.order('sort_order', { ascending: true })
|
||||
@@ -2150,6 +2347,9 @@ async function commitUpdateInvoice(
|
||||
|
||||
const replaced = await replaceInvoiceItems(supabase, invoiceId, build.items)
|
||||
if (!replaced.ok) {
|
||||
if (replaced.stage === 'guard') {
|
||||
return { error: replaced.messageSv, errorCode: replaced.code, status: 409 }
|
||||
}
|
||||
return {
|
||||
error: `Fakturaraderna kunde inte skrivas om (${replaced.stage}): ${replaced.error.message}`,
|
||||
status: 500,
|
||||
@@ -6759,6 +6959,18 @@ async function commitPendingOperationInner(
|
||||
case 'ignore_transaction':
|
||||
result = await commitIgnoreTransaction(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_sales_order':
|
||||
result = await commitCreateSalesOrder(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'transition_sales_order':
|
||||
result = await commitTransitionSalesOrder(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'register_sales_order_delivery':
|
||||
result = await commitRegisterSalesOrderDelivery(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_invoice_from_sales_order':
|
||||
result = await commitCreateInvoiceFromSalesOrder(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_dimension_value':
|
||||
result = await commitCreateDimensionValue(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -51,6 +51,15 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// and the executor's isTransactionBooked() refusal keep it off booked rows,
|
||||
// so the op cannot hide a booking even if tampered with (issue #1661).
|
||||
ignore_transaction: 'low',
|
||||
// Kundorder (sales orders) never book: an order is the non-ledger document
|
||||
// between agreement and invoice. Creating one, moving it through its
|
||||
// header state machine (confirm / cancel / reopen) and registering
|
||||
// delivered quantities write only sales_orders / sales_order_items, no
|
||||
// verifikat and no external side-effect, and all three are re-editable
|
||||
// (cancel is refused while invoices exist, reopen undoes it).
|
||||
create_sales_order: 'low',
|
||||
transition_sales_order: 'low',
|
||||
register_sales_order_delivery: 'low',
|
||||
|
||||
// ── Medium: reversible booking ─────────────────────────────────────
|
||||
categorize_transaction: 'medium',
|
||||
@@ -70,6 +79,10 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// create_invoice: the target has no verifikat yet (isEditableInvoiceDraft
|
||||
// is re-checked at commit), so the edit is fully reversible by editing again.
|
||||
update_invoice: 'medium',
|
||||
// Creates an unnumbered DRAFT kundfaktura from a confirmed order through
|
||||
// the same builder as create_invoice (nothing is booked or sent at commit;
|
||||
// the draft can be deleted). Same tier as create_invoice.
|
||||
create_invoice_from_sales_order: 'medium',
|
||||
// Recurring invoice schedules: the commit only creates/edits the monthly
|
||||
// template (nothing is booked or sent at commit time), and the schedule is
|
||||
// pausable/deletable before the next cron run. Not 'low' because an
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
CreateInvoiceFromSalesOrderSchema,
|
||||
CreateSalesOrderSchema,
|
||||
RegisterSalesOrderDeliverySchema,
|
||||
SalesOrderTransitionSchema,
|
||||
} from '@/lib/api/schemas'
|
||||
|
||||
// Commit-boundary re-validation for the staged kundorder (sales order)
|
||||
// operations. A staged pending_operations row is re-parsed here before the
|
||||
// lib/sales-orders service runs so a tampered row cannot inject unexpected
|
||||
// fields or malformed data (defense in depth, ASVS V4.5): mirrors
|
||||
// lib/pending-operations/schemas/article.ts.
|
||||
//
|
||||
// The shapes are the same Zod schemas the cookie routes under
|
||||
// app/api/sales-orders validate with, so the MCP door and the web door
|
||||
// accept exactly the same payloads. Every executor also needs the target
|
||||
// order, which the route carries in the URL and the staged params carry as
|
||||
// sales_order_id.
|
||||
|
||||
const salesOrderId = z.string().uuid()
|
||||
|
||||
export const CreateSalesOrderParamsSchema = CreateSalesOrderSchema
|
||||
|
||||
export const TransitionSalesOrderParamsSchema = SalesOrderTransitionSchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
|
||||
export const RegisterSalesOrderDeliveryParamsSchema = RegisterSalesOrderDeliverySchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
|
||||
export const CreateInvoiceFromSalesOrderParamsSchema = CreateInvoiceFromSalesOrderSchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
@@ -1066,6 +1066,15 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
|
||||
// Webshop order rows are booking underlag (and carry customer personal
|
||||
// data), so they belong in the archive like transactions do.
|
||||
{ name: 'webshop_orders', file: 'webshop_orders.json', orderBy: 'order_date' },
|
||||
// Kundorder: non-ledger sales documents. Not räkenskapsinformation on
|
||||
// their own, but the provenance of invoices created from them
|
||||
// (invoices.sales_order_id / invoice_items.sales_order_item_id) points
|
||||
// here, so a revisor reading the archive can follow the link.
|
||||
{ name: 'sales_orders', file: 'sales_orders.json', orderBy: 'order_date' },
|
||||
// Direct dump (the coverage contract requires it for a table with its own
|
||||
// company_id); the line's currency is the parent order's, one file over,
|
||||
// joined by sales_order_id.
|
||||
{ name: 'sales_order_items', file: 'sales_order_items.json', orderBy: 'created_at' },
|
||||
{ name: 'webshop_store_settings', file: 'webshop_store_settings.json' },
|
||||
{ name: 'transaction_voucher_links', file: 'transaction_voucher_links.json' },
|
||||
{ name: 'bank_file_imports', file: 'bank_file_imports.json', orderBy: 'created_at' },
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
/**
|
||||
* pickLines (pure) and createInvoiceFromSalesOrder (queued mock, with the
|
||||
* invoice builder mocked).
|
||||
*
|
||||
* createInvoiceFromSalesOrder queue order: loadSalesOrder (sales_orders
|
||||
* select, invoiced rpc), customers select, invoices insert, invoice_items
|
||||
* insert, then loadSalesOrder again. On an items-insert failure the two
|
||||
* rollback deletes (invoice_items, invoices) come before the failure returns.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { IDS, invoicedRow, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem } from './fixtures'
|
||||
|
||||
const mockBuildInvoiceWriteData = vi.fn()
|
||||
vi.mock('@/lib/invoices/build-invoice-write', () => ({
|
||||
buildInvoiceWriteData: (...args: unknown[]) => mockBuildInvoiceWriteData(...args),
|
||||
}))
|
||||
|
||||
import { createInvoiceFromSalesOrder, deliveryDateFor, pickLines } from '../create-invoice-from-order'
|
||||
|
||||
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
const sb = supabase as unknown as SupabaseClient
|
||||
|
||||
function orderWith(items = [makeSalesOrderItem()], overrides = {}) {
|
||||
return makeSalesOrder({ status: 'confirmed', confirmed_at: '2026-09-01T10:00:00Z', items, ...overrides })
|
||||
}
|
||||
|
||||
describe('pickLines', () => {
|
||||
const order = makeSalesOrder({
|
||||
items: [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, remaining_qty: 8 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 4, delivered_qty: 0, invoiced_qty: 4, remaining_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item3, sort_order: 2, line_type: 'text', quantity: 0, delivered_qty: 0 }),
|
||||
],
|
||||
})
|
||||
|
||||
it('refuses an explicit pick above the remaining quantity', () => {
|
||||
const result = pickLines(order, { lines: [{ sales_order_item_id: IDS.item1, quantity: 9 }] })
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_INVOICED',
|
||||
details: { sales_order_item_id: IDS.item1, remaining_qty: 8, requested_qty: 9 },
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts an explicit pick at exactly the remaining quantity', () => {
|
||||
const result = pickLines(order, { lines: [{ sales_order_item_id: IDS.item1, quantity: 8 }] })
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.picked).toHaveLength(1)
|
||||
expect(result.picked[0]).toMatchObject({ quantity: 8, item: { id: IDS.item1 } })
|
||||
})
|
||||
|
||||
it('derives remaining from quantity - invoiced_qty when remaining_qty is absent', () => {
|
||||
const bare = makeSalesOrder({ items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10, invoiced_qty: 7 })] })
|
||||
expect(pickLines(bare, { lines: [{ sales_order_item_id: IDS.item1, quantity: 4 }] })).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_INVOICED',
|
||||
details: { remaining_qty: 3 },
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses an explicit pick of a text row or an unknown line', () => {
|
||||
expect(pickLines(order, { lines: [{ sales_order_item_id: IDS.item3, quantity: 1 }] })).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_LINE_NOT_FOUND',
|
||||
})
|
||||
expect(pickLines(order, { lines: [{ sales_order_item_id: IDS.unknownItem, quantity: 1 }] })).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_LINE_NOT_FOUND',
|
||||
details: { sales_order_item_id: IDS.unknownItem },
|
||||
})
|
||||
})
|
||||
|
||||
it('mode remaining (default) picks everything not yet invoiced', () => {
|
||||
const result = pickLines(order, {})
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
// item2 is fully invoiced, the text row never counts.
|
||||
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item1, 8]])
|
||||
})
|
||||
|
||||
it('mode delivered picks delivered minus invoiced, capped at remaining', () => {
|
||||
const result = pickLines(order, { mode: 'delivered' })
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
// item1: delivered 5 - invoiced 2 = 3
|
||||
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item1, 3]])
|
||||
})
|
||||
|
||||
it('mode delivered never goes negative when more is invoiced than delivered', () => {
|
||||
const advance = makeSalesOrder({
|
||||
items: [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 1, invoiced_qty: 5 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 10, delivered_qty: 6, invoiced_qty: 5 }),
|
||||
],
|
||||
})
|
||||
const result = pickLines(advance, { mode: 'delivered' })
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item2, 1]])
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_NOTHING_TO_INVOICE when every line is fully invoiced', () => {
|
||||
const done = makeSalesOrder({
|
||||
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 4, invoiced_qty: 4, remaining_qty: 0 })],
|
||||
})
|
||||
expect(pickLines(done, {})).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
|
||||
expect(pickLines(done, { mode: 'delivered' })).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_NOTHING_TO_INVOICE in delivered mode when nothing was delivered', () => {
|
||||
const undelivered = makeSalesOrder({ items: [makeSalesOrderItem({ quantity: 4, delivered_qty: 0 })] })
|
||||
expect(pickLines(undelivered, { mode: 'delivered' })).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_NOTHING_TO_INVOICE',
|
||||
})
|
||||
})
|
||||
|
||||
it('treats an empty explicit lines array like no picks', () => {
|
||||
const result = pickLines(order, { lines: [] })
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.picked.map((p) => p.item.id)).toEqual([IDS.item1])
|
||||
})
|
||||
|
||||
it('sums duplicate picks of the same line into one invoice line', () => {
|
||||
const result = pickLines(order, {
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, quantity: 3 },
|
||||
{ sales_order_item_id: IDS.item1, quantity: 5 },
|
||||
],
|
||||
})
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.picked).toHaveLength(1)
|
||||
expect(result.picked[0]).toMatchObject({ quantity: 8, item: { id: IDS.item1 } })
|
||||
})
|
||||
|
||||
it('refuses duplicate picks whose SUM exceeds the remaining quantity', () => {
|
||||
// 5 and 4 each fit within the remaining 8; together they do not.
|
||||
const result = pickLines(order, {
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, quantity: 5 },
|
||||
{ sales_order_item_id: IDS.item1, quantity: 4 },
|
||||
],
|
||||
})
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_INVOICED',
|
||||
details: { sales_order_item_id: IDS.item1, remaining_qty: 8, requested_qty: 9 },
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts a pick equal to a float remainder (7.5 ordered, 6.9 invoiced, pick 0.6)', () => {
|
||||
// 7.5 - 6.9 is 0.5999999999999996 in doubles; the pick must still fit.
|
||||
const fractional = makeSalesOrder({
|
||||
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 7.5, invoiced_qty: 6.9 })],
|
||||
})
|
||||
const explicit = pickLines(fractional, { lines: [{ sales_order_item_id: IDS.item1, quantity: 0.6 }] })
|
||||
expect(explicit.ok).toBe(true)
|
||||
if (!explicit.ok) return
|
||||
expect(explicit.picked[0].quantity).toBe(0.6)
|
||||
|
||||
const remaining = pickLines(fractional, {})
|
||||
expect(remaining.ok).toBe(true)
|
||||
if (!remaining.ok) return
|
||||
expect(remaining.picked[0].quantity).toBe(0.6)
|
||||
})
|
||||
|
||||
it('rounds a summed fractional pick before comparing it to the remainder', () => {
|
||||
const fractional = makeSalesOrder({
|
||||
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 1, invoiced_qty: 0.7 })],
|
||||
})
|
||||
// 0.1 + 0.2 = 0.30000000000000004 in doubles; remaining is exactly 0.3.
|
||||
const result = pickLines(fractional, {
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, quantity: 0.1 },
|
||||
{ sales_order_item_id: IDS.item1, quantity: 0.2 },
|
||||
],
|
||||
})
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.picked[0].quantity).toBe(0.3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deliveryDateFor', () => {
|
||||
it('is the latest per-line last_delivery_date when every pick is covered by deliveries', () => {
|
||||
const picked = [
|
||||
{
|
||||
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, last_delivery_date: '2026-08-20' }),
|
||||
quantity: 3,
|
||||
},
|
||||
{
|
||||
item: makeSalesOrderItem({ id: IDS.item2, quantity: 4, delivered_qty: 4, invoiced_qty: 0, last_delivery_date: '2026-08-30' }),
|
||||
quantity: 4,
|
||||
},
|
||||
]
|
||||
expect(deliveryDateFor(picked)).toBe('2026-08-30')
|
||||
})
|
||||
|
||||
it('is null when a pick exceeds what was delivered but not yet invoiced (advance invoice)', () => {
|
||||
const picked = [
|
||||
{
|
||||
// delivered 5 - invoiced 2 = 3 available; picking 4 reaches undelivered quantity.
|
||||
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, last_delivery_date: '2026-08-20' }),
|
||||
quantity: 4,
|
||||
},
|
||||
]
|
||||
expect(deliveryDateFor(picked)).toBeNull()
|
||||
expect(
|
||||
deliveryDateFor([
|
||||
{ item: makeSalesOrderItem({ quantity: 10, delivered_qty: 0, last_delivery_date: null }), quantity: 1 },
|
||||
]),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('is null when any covered line lacks a per-line delivery date', () => {
|
||||
const picked = [
|
||||
{
|
||||
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 0, last_delivery_date: '2026-08-20' }),
|
||||
quantity: 5,
|
||||
},
|
||||
{
|
||||
// Delivered before per-line dates existed: no date to anchor on.
|
||||
item: makeSalesOrderItem({ id: IDS.item2, quantity: 4, delivered_qty: 4, invoiced_qty: 0, last_delivery_date: null }),
|
||||
quantity: 4,
|
||||
},
|
||||
]
|
||||
expect(deliveryDateFor(picked)).toBeNull()
|
||||
})
|
||||
|
||||
it('tolerates float drift in the covered check (7.5 delivered, 6.9 invoiced, pick 0.6)', () => {
|
||||
const picked = [
|
||||
{
|
||||
item: makeSalesOrderItem({ id: IDS.item1, quantity: 7.5, delivered_qty: 7.5, invoiced_qty: 6.9, last_delivery_date: '2026-08-30' }),
|
||||
quantity: 0.6,
|
||||
},
|
||||
]
|
||||
expect(deliveryDateFor(picked)).toBe('2026-08-30')
|
||||
})
|
||||
})
|
||||
|
||||
const okBuild = {
|
||||
ok: true,
|
||||
invoiceFields: {
|
||||
customer_id: IDS.customer,
|
||||
invoice_date: '2026-09-02',
|
||||
due_date: '2026-10-02',
|
||||
currency: 'SEK',
|
||||
subtotal: 800,
|
||||
vat_amount: 200,
|
||||
total: 1000,
|
||||
vat_treatment: 'standard_25',
|
||||
},
|
||||
items: [
|
||||
{
|
||||
sort_order: 0,
|
||||
line_type: 'product',
|
||||
description: 'Konsulttimme',
|
||||
quantity: 8,
|
||||
unit: 'h',
|
||||
unit_price: 100,
|
||||
line_total: 800,
|
||||
vat_rate: 25,
|
||||
vat_amount: 200,
|
||||
sales_order_item_id: IDS.item1,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('createInvoiceFromSalesOrder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockBuildInvoiceWriteData.mockResolvedValue(okBuild)
|
||||
})
|
||||
|
||||
const params = { companyId: IDS.company, userId: IDS.user, orderId: IDS.order }
|
||||
|
||||
it('returns SALES_ORDER_NOT_FOUND for a missing order', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses invoicing an order that is not confirmed', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_INVALID_STATE',
|
||||
details: { status: 'draft', action: 'invoice' },
|
||||
})
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses when nothing remains to invoice', async () => {
|
||||
enqueue({ data: orderWith([makeSalesOrderItem({ id: IDS.item1, quantity: 4 })]) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 4)] })
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
|
||||
expect(findCall('invoices', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns CUSTOMER_NOT_FOUND when the raw customer row is gone', async () => {
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null })
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
expect(result).toMatchObject({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: IDS.customer } })
|
||||
})
|
||||
|
||||
it('creates an unnumbered draft linked to the order, each line carrying its sales_order_item_id', async () => {
|
||||
enqueue({
|
||||
data: orderWith(
|
||||
[
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0, discount_percent: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item3, sort_order: 1, line_type: 'text', description: 'Tack', quantity: 0 }),
|
||||
],
|
||||
{ order_number: 'OR-7', your_reference: 'Anna', last_delivery_date: '2026-08-30' },
|
||||
),
|
||||
})
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 2)] })
|
||||
enqueue({ data: makeOrderCustomer({ default_payment_terms: 20 }) })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft', invoice_number: null, sales_order_id: IDS.order } })
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: orderWith() }) // reload
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 10)] })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: { invoice_date: '2026-09-02' } })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.invoice.id).toBe(IDS.invoice)
|
||||
expect(result.order.invoicing_progress).toBe('full')
|
||||
|
||||
// Builder input: the remaining 8 of item1, the text row carried along,
|
||||
// sales_order_item_id on the product line, due date from customer terms,
|
||||
// no delivery date because nothing was delivered.
|
||||
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as {
|
||||
documentType: string
|
||||
input: { items: Record<string, unknown>[]; due_date: string; delivery_date: unknown; notes?: string; your_reference?: string }
|
||||
}
|
||||
expect(buildArg.documentType).toBe('invoice')
|
||||
expect(buildArg.input.due_date).toBe('2026-09-22')
|
||||
expect(buildArg.input.delivery_date).toBeNull()
|
||||
expect(buildArg.input.notes).toBe('Kundorder OR-7')
|
||||
expect(buildArg.input.your_reference).toBe('Anna')
|
||||
expect(buildArg.input.items).toEqual([
|
||||
expect.objectContaining({
|
||||
line_type: 'product',
|
||||
quantity: 8,
|
||||
unit_price: 100,
|
||||
discount_percent: 10,
|
||||
vat_rate: 25,
|
||||
sales_order_item_id: IDS.item1,
|
||||
}),
|
||||
expect.objectContaining({ line_type: 'text', description: 'Tack', quantity: 0 }),
|
||||
])
|
||||
|
||||
const invoiceInsert = findCall('invoices', 'insert')![0] as Record<string, unknown>
|
||||
expect(invoiceInsert).toMatchObject({
|
||||
user_id: IDS.user,
|
||||
company_id: IDS.company,
|
||||
invoice_number: null,
|
||||
status: 'draft',
|
||||
sales_order_id: IDS.order,
|
||||
subtotal: 800,
|
||||
total: 1000,
|
||||
})
|
||||
|
||||
const itemRows = findCall('invoice_items', 'insert')![0] as Record<string, unknown>[]
|
||||
expect(itemRows).toHaveLength(1)
|
||||
for (const row of itemRows) {
|
||||
expect(row.invoice_id).toBe(IDS.invoice)
|
||||
expect(row.sales_order_item_id).toBe(IDS.item1)
|
||||
}
|
||||
expect(findCall('invoices', 'delete')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('sets delivery_date from the picked lines when the pick is covered by deliveries', async () => {
|
||||
// The header last_delivery_date is display-only and deliberately later
|
||||
// than the line's date: the invoice must take the LINE date.
|
||||
enqueue({
|
||||
data: orderWith(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4, last_delivery_date: '2026-08-30' })],
|
||||
{ last_delivery_date: '2026-09-01' },
|
||||
),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, {
|
||||
...params,
|
||||
input: { mode: 'delivered', due_date: '2026-09-30' },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as { input: { delivery_date: unknown; due_date: string; items: { quantity: number }[] } }
|
||||
expect(buildArg.input.delivery_date).toBe('2026-08-30')
|
||||
expect(buildArg.input.due_date).toBe('2026-09-30')
|
||||
expect(buildArg.input.items[0].quantity).toBe(4)
|
||||
})
|
||||
|
||||
it('leaves delivery_date null when the pick reaches undelivered quantity (advance invoice)', async () => {
|
||||
enqueue({
|
||||
data: orderWith(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4, last_delivery_date: '2026-08-30' })],
|
||||
{ last_delivery_date: '2026-08-30' },
|
||||
),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
|
||||
// mode remaining: all 10, of which only 4 were delivered.
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: { due_date: '2026-09-30' } })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as { input: { delivery_date: unknown; items: { quantity: number }[] } }
|
||||
expect(buildArg.input.delivery_date).toBeNull()
|
||||
expect(buildArg.input.items[0].quantity).toBe(10)
|
||||
})
|
||||
|
||||
it('refuses with SALES_ORDER_CUSTOMER_VAT_CHANGED when the customer type differs from the order snapshot', async () => {
|
||||
enqueue({
|
||||
data: orderWith([makeSalesOrderItem()], {
|
||||
customer_type_snapshot: 'swedish_business',
|
||||
customer_vat_validated_snapshot: false,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
// Since validated as an EU business: the frozen 25 % line would pass the
|
||||
// permitted-set gate but is no longer what the customer should be charged.
|
||||
enqueue({
|
||||
data: makeOrderCustomer({ customer_type: 'eu_business', vat_number: 'DE123456789', vat_number_validated: true }),
|
||||
})
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_CUSTOMER_VAT_CHANGED',
|
||||
details: {
|
||||
snapshot: { customer_type: 'swedish_business', vat_number_validated: false },
|
||||
current: { customer_type: 'eu_business', vat_number_validated: true },
|
||||
},
|
||||
})
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
expect(findCall('invoices', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses when only the VAT-number validation flag changed since the snapshot', async () => {
|
||||
enqueue({
|
||||
data: orderWith([makeSalesOrderItem()], {
|
||||
customer_type_snapshot: 'eu_business',
|
||||
customer_vat_validated_snapshot: false,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer({ customer_type: 'eu_business', vat_number_validated: true }) })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_CUSTOMER_VAT_CHANGED' })
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('treats a null validation snapshot as false and passes when the customer still matches', async () => {
|
||||
enqueue({
|
||||
data: orderWith([makeSalesOrderItem()], {
|
||||
customer_type_snapshot: 'swedish_business',
|
||||
customer_vat_validated_snapshot: null,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer({ customer_type: 'swedish_business', vat_number_validated: null as unknown as boolean }) })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(mockBuildInvoiceWriteData).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('passes without a snapshot check when the order carries no customer_type_snapshot (pre-snapshot orders)', async () => {
|
||||
enqueue({
|
||||
data: orderWith([makeSalesOrderItem()], { customer_type_snapshot: null, customer_vat_validated_snapshot: null }),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer({ customer_type: 'eu_business', vat_number_validated: true }) })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(mockBuildInvoiceWriteData).toHaveBeenCalledTimes(1)
|
||||
expect(findCall('invoices', 'insert')).toBeDefined()
|
||||
})
|
||||
|
||||
it('propagates a builder domain failure without inserting', async () => {
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
mockBuildInvoiceWriteData.mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'INVOICE_CREATE_VAT_RULE_VIOLATION',
|
||||
details: { attemptedRate: 25 },
|
||||
})
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'INVOICE_CREATE_VAT_RULE_VIOLATION', details: { attemptedRate: 25 } })
|
||||
expect(findCall('invoices', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('deletes the draft and maps the over-invoice trigger when the line insert fails', async () => {
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { message: 'SALES_ORDER_OVER_INVOICED: line d1000000 would exceed ordered quantity', code: 'P0001' },
|
||||
})
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoices delete
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_OVER_INVOICED' })
|
||||
expect(findCall('invoice_items', 'delete')).toBeDefined()
|
||||
expect(findCall('invoice_items', 'eq')).toEqual(['invoice_id', IDS.invoice])
|
||||
expect(findCall('invoices', 'delete')).toBeDefined()
|
||||
expect(findCall('invoices', 'eq')).toEqual(['id', IDS.invoice])
|
||||
})
|
||||
|
||||
it('deletes the draft and returns the raw DB error when the line insert fails for another reason', async () => {
|
||||
enqueue({ data: orderWith() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
|
||||
enqueue({ data: null, error: { message: 'null value in column "description"', code: '23502' } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect('dbError' in result && result.dbError).toMatchObject({ code: '23502' })
|
||||
expect(findCall('invoices', 'delete')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Synthetic fixtures for the kundorder (sales order) tests. Shared by the
|
||||
* service tests in this directory and the route tests under
|
||||
* app/api/sales-orders and app/api/invoices/[id]/convert-to-order.
|
||||
*
|
||||
* Ids are RFC 4122 v4-shaped so they pass the Zod `uuid` primitive.
|
||||
*/
|
||||
import type { Customer, SalesOrder, SalesOrderItem } from '@/types'
|
||||
import { makeCustomer } from '@/tests/helpers'
|
||||
|
||||
export const IDS = {
|
||||
company: 'company-1',
|
||||
user: 'user-1',
|
||||
order: 'a1000000-0000-4000-8000-000000000001',
|
||||
customer: 'c1000000-0000-4000-8000-000000000001',
|
||||
otherCustomer: 'c1000000-0000-4000-8000-000000000002',
|
||||
item1: 'd1000000-0000-4000-8000-000000000001',
|
||||
item2: 'd1000000-0000-4000-8000-000000000002',
|
||||
item3: 'd1000000-0000-4000-8000-000000000003',
|
||||
unknownItem: 'e1000000-0000-4000-8000-000000000009',
|
||||
invoice: 'f1000000-0000-4000-8000-000000000001',
|
||||
} as const
|
||||
|
||||
export function makeOrderCustomer(overrides: Partial<Customer> = {}): Customer {
|
||||
return makeCustomer({
|
||||
id: IDS.customer,
|
||||
name: 'Testbrand AB',
|
||||
email: 'test@testbrand.example',
|
||||
customer_type: 'swedish_business',
|
||||
vat_number: null,
|
||||
vat_number_validated: false,
|
||||
vat_number_validated_at: null,
|
||||
personal_number: null,
|
||||
default_payment_terms: 30,
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
export function makeSalesOrderItem(overrides: Partial<SalesOrderItem> = {}): SalesOrderItem {
|
||||
return {
|
||||
id: IDS.item1,
|
||||
company_id: IDS.company,
|
||||
sales_order_id: IDS.order,
|
||||
sort_order: 0,
|
||||
line_type: 'product',
|
||||
description: 'Konsulttimme',
|
||||
quantity: 10,
|
||||
delivered_qty: 0,
|
||||
unit: 'h',
|
||||
unit_price: 100,
|
||||
discount_percent: 0,
|
||||
vat_rate: 25,
|
||||
line_total: 1000,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
dimensions: {},
|
||||
created_at: '2026-09-01T08:00:00Z',
|
||||
updated_at: '2026-09-01T08:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
export function makeSalesOrder(overrides: Partial<SalesOrder> = {}): SalesOrder {
|
||||
return {
|
||||
id: IDS.order,
|
||||
company_id: IDS.company,
|
||||
user_id: IDS.user,
|
||||
customer_id: IDS.customer,
|
||||
order_number: 'OR-1',
|
||||
status: 'draft',
|
||||
source_invoice_id: null,
|
||||
order_date: '2026-09-01',
|
||||
requested_delivery_date: null,
|
||||
last_delivery_date: null,
|
||||
currency: 'SEK',
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
your_reference: null,
|
||||
our_reference: null,
|
||||
notes: null,
|
||||
default_dimensions: {},
|
||||
confirmed_at: null,
|
||||
completed_at: null,
|
||||
cancelled_at: null,
|
||||
created_at: '2026-09-01T08:00:00Z',
|
||||
updated_at: '2026-09-01T08:00:00Z',
|
||||
customer: makeOrderCustomer(),
|
||||
items: [makeSalesOrderItem()],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Row shape returned by the sales_order_invoiced_quantities RPC. */
|
||||
export function invoicedRow(itemId: string, qty: number | string) {
|
||||
return { sales_order_item_id: itemId, invoiced_qty: qty }
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Pure tests for normalizeSalesOrderLines: öre-exact line math shared with
|
||||
* invoices, text rows, and the per-customer VAT gate.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { normalizeSalesOrderLines } from '../lines'
|
||||
|
||||
const swedish = { customer_type: 'swedish_business' as const, vat_number_validated: false }
|
||||
const euValidated = { customer_type: 'eu_business' as const, vat_number_validated: true }
|
||||
|
||||
describe('normalizeSalesOrderLines', () => {
|
||||
it('computes öre-exact totals with a percentage discount and mixed VAT rates', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[
|
||||
// gross 299.97, discount 30.00 (29.997 rounded), net 269.97, VAT 67.49 (67.4925 rounded)
|
||||
{ description: 'Konsulttimme', quantity: 3, unit: 'h', unit_price: 99.99, discount_percent: 10, vat_rate: 25 },
|
||||
// net 100, VAT 12
|
||||
{ description: 'Bok', quantity: 1, unit: 'st', unit_price: 100, vat_rate: 12 },
|
||||
// net 66.66, VAT 4.00 (3.9996 rounded)
|
||||
{ description: 'Tidning', quantity: 2, unit: 'st', unit_price: 33.33, vat_rate: 6 },
|
||||
],
|
||||
swedish,
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.rows.map((r) => r.line_total)).toEqual([269.97, 100, 66.66])
|
||||
expect(result.rows[0].discount_percent).toBe(10)
|
||||
expect(result.rows.map((r) => r.vat_rate)).toEqual([25, 12, 6])
|
||||
expect(result.totals).toEqual({ subtotal: 436.63, vat_amount: 83.49, total: 520.12 })
|
||||
})
|
||||
|
||||
it('accumulates many small lines without floating-point drift', () => {
|
||||
// 0.1 + 0.2 style drift: ten lines of 0.10 must sum to exactly 1.00.
|
||||
const items = Array.from({ length: 10 }, (_, i) => ({
|
||||
description: `Rad ${i + 1}`,
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: 0.1,
|
||||
vat_rate: 25,
|
||||
}))
|
||||
const result = normalizeSalesOrderLines(items, swedish)
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.totals.subtotal).toBe(1)
|
||||
// Per-line VAT is 0.025 -> 0.03 (rounded per line, like the invoice builder).
|
||||
expect(result.totals.vat_amount).toBe(0.3)
|
||||
expect(result.totals.total).toBe(1.3)
|
||||
})
|
||||
|
||||
it('normalises text rows to zero and excludes them from the totals', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[
|
||||
// Whatever numbers a text row carries in, they are discarded.
|
||||
{ line_type: 'text', description: 'Leverans vecka 36', quantity: 5, unit: 'st', unit_price: 1000, vat_rate: 25 },
|
||||
{ description: 'Vara', quantity: 1, unit: 'st', unit_price: 100, vat_rate: 25 },
|
||||
],
|
||||
swedish,
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.rows[0]).toMatchObject({
|
||||
sort_order: 0,
|
||||
line_type: 'text',
|
||||
description: 'Leverans vecka 36',
|
||||
quantity: 0,
|
||||
unit: '',
|
||||
unit_price: 0,
|
||||
discount_percent: 0,
|
||||
vat_rate: 0,
|
||||
line_total: 0,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
dimensions: {},
|
||||
})
|
||||
expect(result.rows[1].sort_order).toBe(1)
|
||||
expect(result.totals).toEqual({ subtotal: 100, vat_amount: 25, total: 125 })
|
||||
})
|
||||
|
||||
it('keeps line ids, article, revenue account and dimensions on product rows', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[
|
||||
{
|
||||
id: 'd1000000-0000-4000-8000-000000000001',
|
||||
description: 'Licens',
|
||||
quantity: 2,
|
||||
unit: 'st',
|
||||
unit_price: 500,
|
||||
vat_rate: 25,
|
||||
article_id: 'b1000000-0000-4000-8000-000000000001',
|
||||
revenue_account: '3011',
|
||||
dimensions: { project: 'P1' },
|
||||
},
|
||||
],
|
||||
swedish,
|
||||
)
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.rows[0]).toMatchObject({
|
||||
id: 'd1000000-0000-4000-8000-000000000001',
|
||||
article_id: 'b1000000-0000-4000-8000-000000000001',
|
||||
revenue_account: '3011',
|
||||
dimensions: { project: 'P1' },
|
||||
line_total: 1000,
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a VAT rate the customer type does not permit (validated EU business)', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[
|
||||
{ description: 'Konsult', quantity: 1, unit: 'h', unit_price: 1000, vat_rate: 0 },
|
||||
{ description: 'Udda sats', quantity: 1, unit: 'h', unit_price: 1000, vat_rate: 20 },
|
||||
],
|
||||
euValidated,
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) return
|
||||
expect(result.code).toBe('INVOICE_CREATE_VAT_RULE_VIOLATION')
|
||||
expect(result.details).toMatchObject({
|
||||
attemptedRate: 20,
|
||||
customerType: 'eu_business',
|
||||
line: 1,
|
||||
})
|
||||
// 0 % reverse charge plus the taxed-where-performed Swedish rates.
|
||||
expect(result.details?.allowedRates).toEqual(expect.arrayContaining([0, 25, 12, 6]))
|
||||
expect(result.details?.allowedRates).not.toContain(20)
|
||||
})
|
||||
|
||||
it('refuses a non-Swedish VAT rate for a domestic customer', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[{ description: 'Konsult', quantity: 1, unit: 'h', unit_price: 1000, vat_rate: 20 }],
|
||||
swedish,
|
||||
)
|
||||
expect(result).toMatchObject({ ok: false, code: 'INVOICE_CREATE_VAT_RULE_VIOLATION' })
|
||||
})
|
||||
|
||||
it('defaults a line without vat_rate to the customer rule (0 % reverse charge for validated EU)', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[{ description: 'Konsult', quantity: 4, unit: 'h', unit_price: 250 }],
|
||||
euValidated,
|
||||
)
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.rows[0].vat_rate).toBe(0)
|
||||
expect(result.totals).toEqual({ subtotal: 1000, vat_amount: 0, total: 1000 })
|
||||
})
|
||||
|
||||
it('defaults a line without vat_rate to 25 % for a domestic customer', () => {
|
||||
const result = normalizeSalesOrderLines(
|
||||
[{ description: 'Konsult', quantity: 1, unit: 'h', unit_price: 100 }],
|
||||
swedish,
|
||||
)
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.totals.vat_amount).toBe(25)
|
||||
})
|
||||
|
||||
it('returns empty rows and zero totals for no items', () => {
|
||||
const result = normalizeSalesOrderLines([], swedish)
|
||||
expect(result).toEqual({ ok: true, rows: [], totals: { subtotal: 0, vat_amount: 0, total: 0 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Pure tests for the derived delivery / invoicing progress and the
|
||||
* invoiced_qty / remaining_qty decoration.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
QTY_DECIMALS,
|
||||
QTY_EPSILON,
|
||||
deliveryProgress,
|
||||
invoicingProgress,
|
||||
qtyGreater,
|
||||
roundQty,
|
||||
withInvoicedQuantities,
|
||||
} from '../progress'
|
||||
import { IDS, makeSalesOrderItem } from './fixtures'
|
||||
|
||||
describe('roundQty', () => {
|
||||
it('rounds to 6 decimals (Postgres numeric precision for quantities)', () => {
|
||||
expect(QTY_DECIMALS).toBe(6)
|
||||
expect(roundQty(1.23456789)).toBe(1.234568)
|
||||
expect(roundQty(1.2345644)).toBe(1.234564)
|
||||
expect(roundQty(3)).toBe(3)
|
||||
})
|
||||
|
||||
it('collapses double drift onto the exact decimal value', () => {
|
||||
expect(7.5 - 6.9).not.toBe(0.6)
|
||||
expect(roundQty(7.5 - 6.9)).toBe(0.6)
|
||||
expect(roundQty(0.3 - 0.2)).toBe(0.1)
|
||||
expect(roundQty(0.1 + 0.2)).toBe(0.3)
|
||||
})
|
||||
|
||||
it('returns a plain 0 for zero (never -0)', () => {
|
||||
expect(Object.is(roundQty(0), 0)).toBe(true)
|
||||
expect(Object.is(roundQty(-0), 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('handles negative quantities symmetrically', () => {
|
||||
expect(roundQty(-0.6000000000000001)).toBe(-0.6)
|
||||
expect(roundQty(-1.2345678)).toBe(-1.234568)
|
||||
})
|
||||
})
|
||||
|
||||
describe('qtyGreater', () => {
|
||||
it('is half a quantity unit of tolerance', () => {
|
||||
expect(QTY_EPSILON).toBe(0.0000005)
|
||||
})
|
||||
|
||||
it('ignores float drift below quantity precision', () => {
|
||||
expect(qtyGreater(0.1 + 0.2, 0.3)).toBe(false)
|
||||
expect(qtyGreater(0.6, 7.5 - 6.9)).toBe(false)
|
||||
expect(qtyGreater(5, 5)).toBe(false)
|
||||
expect(qtyGreater(4.9999999, 5)).toBe(false)
|
||||
})
|
||||
|
||||
it('detects a real difference at or above one quantity unit', () => {
|
||||
expect(qtyGreater(5.000001, 5)).toBe(true)
|
||||
expect(qtyGreater(5.1, 5)).toBe(true)
|
||||
expect(qtyGreater(9, 8)).toBe(true)
|
||||
expect(qtyGreater(8, 9)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deliveryProgress', () => {
|
||||
it('is none when no line has been delivered', () => {
|
||||
const items = [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, delivered_qty: 0 }),
|
||||
]
|
||||
expect(deliveryProgress(items)).toBe('none')
|
||||
})
|
||||
|
||||
it('is partial when some quantity is delivered but not everything', () => {
|
||||
const items = [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, delivered_qty: 0 }),
|
||||
]
|
||||
expect(deliveryProgress(items)).toBe('partial')
|
||||
})
|
||||
|
||||
it('is partial when a single line is half delivered', () => {
|
||||
expect(deliveryProgress([makeSalesOrderItem({ quantity: 10, delivered_qty: 4 })])).toBe('partial')
|
||||
})
|
||||
|
||||
it('is full when every product line is delivered in full', () => {
|
||||
const items = [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, delivered_qty: 5 }),
|
||||
]
|
||||
expect(deliveryProgress(items)).toBe('full')
|
||||
})
|
||||
|
||||
it('ignores text rows and zero-quantity rows', () => {
|
||||
const items = [
|
||||
makeSalesOrderItem({ id: IDS.item1, line_type: 'text', quantity: 0, delivered_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 0, delivered_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item3, quantity: 2, delivered_qty: 2 }),
|
||||
]
|
||||
expect(deliveryProgress(items)).toBe('full')
|
||||
})
|
||||
|
||||
it('is none for an order with only text rows or no lines', () => {
|
||||
expect(deliveryProgress([])).toBe('none')
|
||||
expect(deliveryProgress([makeSalesOrderItem({ line_type: 'text', quantity: 0 })])).toBe('none')
|
||||
})
|
||||
})
|
||||
|
||||
describe('invoicingProgress', () => {
|
||||
it('treats a missing invoiced_qty as zero', () => {
|
||||
expect(invoicingProgress([makeSalesOrderItem({ quantity: 10 })])).toBe('none')
|
||||
})
|
||||
|
||||
it('reports none / partial / full from invoiced_qty', () => {
|
||||
expect(
|
||||
invoicingProgress([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, invoiced_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, invoiced_qty: 0 }),
|
||||
]),
|
||||
).toBe('none')
|
||||
expect(
|
||||
invoicingProgress([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, invoiced_qty: 3 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, invoiced_qty: 5 }),
|
||||
]),
|
||||
).toBe('partial')
|
||||
expect(
|
||||
invoicingProgress([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, invoiced_qty: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5, invoiced_qty: 5 }),
|
||||
]),
|
||||
).toBe('full')
|
||||
})
|
||||
|
||||
it('is independent of delivery', () => {
|
||||
const items = [makeSalesOrderItem({ quantity: 10, delivered_qty: 10, invoiced_qty: 0 })]
|
||||
expect(deliveryProgress(items)).toBe('full')
|
||||
expect(invoicingProgress(items)).toBe('none')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withInvoicedQuantities', () => {
|
||||
it('attaches invoiced_qty and remaining_qty from the RPC map', () => {
|
||||
const items = [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, quantity: 5 }),
|
||||
]
|
||||
const decorated = withInvoicedQuantities(items, new Map([[IDS.item1, 4]]))
|
||||
expect(decorated[0]).toMatchObject({ invoiced_qty: 4, remaining_qty: 6 })
|
||||
// Not in the map: nothing invoiced yet.
|
||||
expect(decorated[1]).toMatchObject({ invoiced_qty: 0, remaining_qty: 5 })
|
||||
})
|
||||
|
||||
it('never reports a negative remaining_qty when more was invoiced than ordered', () => {
|
||||
const decorated = withInvoicedQuantities(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 3 })],
|
||||
new Map([[IDS.item1, 7]]),
|
||||
)
|
||||
expect(decorated[0].invoiced_qty).toBe(7)
|
||||
expect(decorated[0].remaining_qty).toBe(0)
|
||||
})
|
||||
|
||||
it('does not mutate the input items', () => {
|
||||
const item = makeSalesOrderItem({ id: IDS.item1, quantity: 3 })
|
||||
withInvoicedQuantities([item], new Map([[IDS.item1, 1]]))
|
||||
expect(item.invoiced_qty).toBeUndefined()
|
||||
expect(item.remaining_qty).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reports an exact remaining_qty for fractional quantities (7.5 - 6.9, 0.3 - 0.2)', () => {
|
||||
const decorated = withInvoicedQuantities(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 7.5 }), makeSalesOrderItem({ id: IDS.item2, quantity: 0.3 })],
|
||||
new Map([
|
||||
[IDS.item1, 6.9],
|
||||
[IDS.item2, 0.2],
|
||||
]),
|
||||
)
|
||||
// Raw doubles give 0.5999999999999996 and 0.09999999999999998, which the
|
||||
// DB refuses as "0.6 > remaining". The decorated values must be exact.
|
||||
expect(decorated[0].remaining_qty).toBe(0.6)
|
||||
expect(decorated[1].remaining_qty).toBe(0.1)
|
||||
expect(decorated[0].invoiced_qty).toBe(6.9)
|
||||
expect(decorated[1].invoiced_qty).toBe(0.2)
|
||||
})
|
||||
|
||||
it('rounds the invoiced quantity coming from the RPC to quantity precision', () => {
|
||||
const decorated = withInvoicedQuantities(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 10 })],
|
||||
new Map([[IDS.item1, 2.0000000004]]),
|
||||
)
|
||||
expect(decorated[0].invoiced_qty).toBe(2)
|
||||
expect(decorated[0].remaining_qty).toBe(8)
|
||||
})
|
||||
|
||||
it('counts a line as fully invoiced when the float remainder is below quantity precision', () => {
|
||||
const items = withInvoicedQuantities(
|
||||
[makeSalesOrderItem({ id: IDS.item1, quantity: 0.3 })],
|
||||
new Map([[IDS.item1, 0.1 + 0.2]]),
|
||||
)
|
||||
expect(items[0].remaining_qty).toBe(0)
|
||||
expect(invoicingProgress(items)).toBe('full')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* registerSalesOrderDelivery: cumulative delivered quantities on a
|
||||
* confirmed order, over-delivery guard, last_delivery_date bump.
|
||||
*
|
||||
* Queue order: loadSalesOrder (sales_orders select, invoiced rpc), one
|
||||
* sales_order_items update per product line, an optional sales_orders
|
||||
* update when any quantity increased, then loadSalesOrder again.
|
||||
*
|
||||
* Each line update is an optimistic write (.eq('delivered_qty', previous)
|
||||
* + .select('id')): the queued result must carry the matched row, since an
|
||||
* empty array or null now means the quantity moved concurrently.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { registerSalesOrderDelivery } from '../register-delivery'
|
||||
import { IDS, makeSalesOrder, makeSalesOrderItem } from './fixtures'
|
||||
|
||||
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
|
||||
const sb = supabase as unknown as SupabaseClient
|
||||
|
||||
function confirmedOrder(items = [makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0 })]) {
|
||||
return makeSalesOrder({ status: 'confirmed', confirmed_at: '2026-09-01T10:00:00Z', items })
|
||||
}
|
||||
|
||||
/** The matched-row result of a successful optimistic line update. */
|
||||
const matched = (id: string) => ({ data: [{ id }] })
|
||||
|
||||
describe('registerSalesOrderDelivery', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_NOT_FOUND for a missing order', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] },
|
||||
})
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('refuses delivery on an order that is not confirmed', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_INVALID_STATE',
|
||||
details: { status: 'draft', action: 'deliver' },
|
||||
})
|
||||
expect(findCall('sales_order_items', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses delivery on a cancelled order', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'cancelled' }) })
|
||||
enqueue({ data: [] })
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] },
|
||||
})
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_INVALID_STATE' })
|
||||
})
|
||||
|
||||
it('refuses delivering more than the ordered quantity before touching any line', async () => {
|
||||
enqueue({
|
||||
data: confirmedOrder([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 5, delivered_qty: 0 }),
|
||||
]),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: {
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, delivered_qty: 10 },
|
||||
{ sales_order_item_id: IDS.item2, delivered_qty: 6 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_DELIVERED',
|
||||
details: { sales_order_item_id: IDS.item2, quantity: 5, delivered_qty: 6 },
|
||||
})
|
||||
// Validation runs over every line first: the valid first line is not written either.
|
||||
expect(findCall('sales_order_items', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses a line id that is not on the order', async () => {
|
||||
enqueue({ data: confirmedOrder() })
|
||||
enqueue({ data: [] })
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.unknownItem, delivered_qty: 1 }] },
|
||||
})
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_LINE_NOT_FOUND',
|
||||
details: { sales_order_item_id: IDS.unknownItem },
|
||||
})
|
||||
})
|
||||
|
||||
it('writes the cumulative quantity and moves last_delivery_date when a quantity increased', async () => {
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 2 })]) })
|
||||
enqueue({ data: [] })
|
||||
enqueue(matched(IDS.item1)) // sales_order_items update
|
||||
enqueue({ data: null }) // sales_orders update (last_delivery_date)
|
||||
enqueue({
|
||||
data: confirmedOrder([makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 6 })]),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { delivery_date: '2026-09-02', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 6 }] },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.order.delivery_progress).toBe('partial')
|
||||
// The line that increased records the delivery date as its own
|
||||
// last_delivery_date: invoices later take leveransdatum from the lines.
|
||||
expect(findCall('sales_order_items', 'update')![0]).toEqual({
|
||||
delivered_qty: 6,
|
||||
last_delivery_date: '2026-09-02',
|
||||
})
|
||||
expect(findCalls('sales_order_items', 'eq')).toContainEqual(['id', IDS.item1])
|
||||
expect(findCalls('sales_order_items', 'eq')).toContainEqual(['company_id', IDS.company])
|
||||
// Optimistic predicate on the quantity read before the write.
|
||||
expect(findCalls('sales_order_items', 'eq')).toContainEqual(['delivered_qty', 2])
|
||||
expect(findCall('sales_order_items', 'select')).toEqual(['id'])
|
||||
expect(findCall('sales_orders', 'update')![0]).toEqual({ last_delivery_date: '2026-09-02' })
|
||||
})
|
||||
|
||||
it('defaults the delivery date to today in Europe/Stockholm when none is given', async () => {
|
||||
// 22:30 UTC on 30 June is already 1 July in Stockholm (CEST, UTC+2).
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-06-30T22:30:00Z'))
|
||||
enqueue({ data: confirmedOrder() })
|
||||
enqueue({ data: [] })
|
||||
enqueue(matched(IDS.item1))
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ delivered_qty: 3 })]) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 3 }] },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const patch = findCall('sales_orders', 'update')![0] as { last_delivery_date: string }
|
||||
expect(patch.last_delivery_date).toBe('2026-07-01')
|
||||
expect(findCall('sales_order_items', 'update')![0]).toEqual({
|
||||
delivered_qty: 3,
|
||||
last_delivery_date: '2026-07-01',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_INVALID_STATE when a line update matches zero rows (concurrent registration)', async () => {
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0 })]) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // sales_order_items update: delivered_qty no longer 0, nothing matched
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { delivery_date: '2026-09-02', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 6 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_INVALID_STATE',
|
||||
details: {
|
||||
action: 'deliver',
|
||||
sales_order_item_id: IDS.item1,
|
||||
reason: 'delivered quantity changed concurrently',
|
||||
},
|
||||
})
|
||||
expect(findCalls('sales_order_items', 'eq')).toContainEqual(['delivered_qty', 0])
|
||||
// The header is never stamped when a line refused the write.
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats a null update result as the same concurrency conflict', async () => {
|
||||
enqueue({ data: confirmedOrder() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null }) // sales_order_items update
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_INVALID_STATE' })
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not move last_delivery_date when no quantity increased (idempotent retry)', async () => {
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 6 })]) })
|
||||
enqueue({ data: [] })
|
||||
enqueue(matched(IDS.item1)) // sales_order_items update (same value)
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 6 })]) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { delivery_date: '2026-09-05', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 6 }] },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
// The line is still written (cumulative value), but its last_delivery_date
|
||||
// is left untouched: undefined drops out of the PostgREST payload.
|
||||
const lineUpdate = findCall('sales_order_items', 'update')![0] as Record<string, unknown>
|
||||
expect(lineUpdate).toEqual({ delivered_qty: 6, last_delivery_date: undefined })
|
||||
expect(lineUpdate.last_delivery_date).toBeUndefined()
|
||||
expect(findCalls('sales_order_items', 'eq')).toContainEqual(['delivered_qty', 6])
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('stamps last_delivery_date only on the lines that increased in a mixed delivery', async () => {
|
||||
enqueue({
|
||||
data: confirmedOrder([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4, last_delivery_date: '2026-08-20' }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 5, delivered_qty: 1 }),
|
||||
]),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue(matched(IDS.item1)) // item1 update (unchanged quantity)
|
||||
enqueue(matched(IDS.item2)) // item2 update (increased)
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({
|
||||
data: confirmedOrder([
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 5, delivered_qty: 3 }),
|
||||
]),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: {
|
||||
delivery_date: '2026-09-03',
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, delivered_qty: 4 },
|
||||
{ sales_order_item_id: IDS.item2, delivered_qty: 3 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const updates = findCalls('sales_order_items', 'update').map((args) => args[0])
|
||||
expect(updates).toEqual([
|
||||
{ delivered_qty: 4, last_delivery_date: undefined },
|
||||
{ delivered_qty: 3, last_delivery_date: '2026-09-03' },
|
||||
])
|
||||
expect((updates[0] as Record<string, unknown>).last_delivery_date).toBeUndefined()
|
||||
expect(findCall('sales_orders', 'update')![0]).toEqual({ last_delivery_date: '2026-09-03' })
|
||||
})
|
||||
|
||||
it('skips text rows without writing them', async () => {
|
||||
enqueue({
|
||||
data: confirmedOrder([
|
||||
makeSalesOrderItem({ id: IDS.item1, line_type: 'text', quantity: 0, delivered_qty: 0 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 4, delivered_qty: 0 }),
|
||||
]),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue(matched(IDS.item2)) // item2 update
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: confirmedOrder([makeSalesOrderItem({ id: IDS.item2, quantity: 4, delivered_qty: 4 })]) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: {
|
||||
lines: [
|
||||
{ sales_order_item_id: IDS.item1, delivered_qty: 99 },
|
||||
{ sales_order_item_id: IDS.item2, delivered_qty: 4 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(findCalls('sales_order_items', 'update')).toHaveLength(1)
|
||||
expect(findCalls('sales_order_items', 'eq')).not.toContainEqual(['id', IDS.item1])
|
||||
})
|
||||
|
||||
it('maps the delivered-within-ordered DB constraint onto SALES_ORDER_OVER_DELIVERED', async () => {
|
||||
enqueue({ data: confirmedOrder() })
|
||||
enqueue({ data: [] })
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { message: 'new row violates check constraint "sales_order_items_delivered_within_ordered"' },
|
||||
})
|
||||
|
||||
const result = await registerSalesOrderDelivery(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 5 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_OVER_DELIVERED' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* codeFromPgError: the DB-side guards (triggers, CHECK, RESTRICT FKs) raise
|
||||
* with stable identifiers in the message; the service layer maps them onto
|
||||
* the same structured codes the pre-checks use.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { codeFromPgError, fail, failDb } from '../result'
|
||||
|
||||
describe('codeFromPgError', () => {
|
||||
it('maps the trigger-raised SALES_ORDER_* prefixes', () => {
|
||||
expect(codeFromPgError({ message: 'SALES_ORDER_OVER_INVOICED: line d1 would exceed ordered quantity' })).toBe(
|
||||
'SALES_ORDER_OVER_INVOICED',
|
||||
)
|
||||
expect(codeFromPgError({ message: 'SALES_ORDER_QUANTITY_BELOW_INVOICED: line d1 has 4 invoiced' })).toBe(
|
||||
'SALES_ORDER_QUANTITY_BELOW_INVOICED',
|
||||
)
|
||||
expect(codeFromPgError({ message: 'SALES_ORDER_ITEM_NOT_FOUND: d1' })).toBe('SALES_ORDER_LINE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('maps the delivered-within-ordered CHECK constraint', () => {
|
||||
expect(
|
||||
codeFromPgError({
|
||||
message: 'new row for relation "sales_order_items" violates check constraint "sales_order_items_delivered_within_ordered"',
|
||||
}),
|
||||
).toBe('SALES_ORDER_OVER_DELIVERED')
|
||||
})
|
||||
|
||||
it('maps the RESTRICT FK from invoice_items onto SALES_ORDER_LINE_LOCKED', () => {
|
||||
expect(
|
||||
codeFromPgError({
|
||||
code: '23503',
|
||||
message:
|
||||
'update or delete on table "sales_order_items" violates foreign key constraint "invoice_items_sales_order_item_id_fkey" on table "invoice_items"',
|
||||
}),
|
||||
).toBe('SALES_ORDER_LINE_LOCKED')
|
||||
})
|
||||
|
||||
it('maps the RESTRICT FK from invoices onto SALES_ORDER_HAS_INVOICES', () => {
|
||||
expect(
|
||||
codeFromPgError({
|
||||
code: '23503',
|
||||
message:
|
||||
'update or delete on table "sales_orders" violates foreign key constraint "invoices_sales_order_id_fkey" on table "invoices"',
|
||||
}),
|
||||
).toBe('SALES_ORDER_HAS_INVOICES')
|
||||
})
|
||||
|
||||
it('returns null for anything else (the raw error is surfaced instead)', () => {
|
||||
expect(codeFromPgError({ message: 'null value in column "description"', code: '23502' })).toBeNull()
|
||||
expect(codeFromPgError(new Error('connection reset'))).toBeNull()
|
||||
expect(codeFromPgError(null)).toBeNull()
|
||||
expect(codeFromPgError(undefined)).toBeNull()
|
||||
expect(codeFromPgError('SALES_ORDER_OVER_INVOICED')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('fail / failDb', () => {
|
||||
it('omits details when none are given', () => {
|
||||
expect(fail('SALES_ORDER_NOT_FOUND')).toEqual({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
|
||||
expect(fail('SALES_ORDER_LINE_NOT_FOUND', { sales_order_item_id: 'x' })).toEqual({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_LINE_NOT_FOUND',
|
||||
details: { sales_order_item_id: 'x' },
|
||||
})
|
||||
})
|
||||
|
||||
it('carries the raw DB error', () => {
|
||||
const error = { message: 'boom', code: '42P01' }
|
||||
expect(failDb(error)).toEqual({ ok: false, dbError: error })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* transitionSalesOrder: the header state machine (confirm / cancel / reopen)
|
||||
* with the queued Supabase mock.
|
||||
*
|
||||
* Queue order per loadSalesOrder: from('sales_orders') select, then
|
||||
* rpc('sales_order_invoiced_quantities'). hasOpenInvoices adds one more
|
||||
* rpc call and, when no line carries invoiced quantity, a from('invoices')
|
||||
* head count.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { transitionSalesOrder } from '../transitions'
|
||||
import { IDS, invoicedRow, makeSalesOrder, makeSalesOrderItem } from './fixtures'
|
||||
|
||||
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
|
||||
const sb = supabase as unknown as SupabaseClient
|
||||
|
||||
describe('transitionSalesOrder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_NOT_FOUND when the order does not exist', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('refuses a transition from a state the action does not allow', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_INVALID_STATE',
|
||||
details: { status: 'confirmed', action: 'confirm' },
|
||||
})
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses reopen of a draft (only cancelled orders reopen)', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'reopen' })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_INVALID_STATE' })
|
||||
})
|
||||
|
||||
it('refuses cancel while a linked invoice carries invoiced quantity', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, '2')] }) // load
|
||||
enqueue({ data: [invoicedRow(IDS.item1, '2')] }) // hasOpenInvoices
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'cancel' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_HAS_INVOICES' })
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses cancel while a header-linked invoice exists even with zero invoiced quantity', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [] }) // load: nothing invoiced per line
|
||||
enqueue({ data: [] }) // hasOpenInvoices rpc: nothing per line
|
||||
enqueue({ data: null, count: 1 }) // invoices head count: one open invoice
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'cancel' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_HAS_INVOICES' })
|
||||
expect(findCall('invoices', 'select')).toBeDefined()
|
||||
})
|
||||
|
||||
it('refuses confirm when the order has no customer', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', customer_id: null, customer: null }) })
|
||||
enqueue({ data: [] })
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_CUSTOMER_MISSING' })
|
||||
})
|
||||
|
||||
it('confirms a draft: sets confirmed_at, compare-and-sets on status, refreshes completion', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [{ id: IDS.order }] }) // CAS update matched one row
|
||||
enqueue({ data: null }) // refresh_sales_order_completion
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed', confirmed_at: '2026-09-02T10:00:00Z' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.order.status).toBe('confirmed')
|
||||
expect(result.order.delivery_progress).toBe('none')
|
||||
expect(result.order.invoicing_progress).toBe('none')
|
||||
|
||||
const patch = findCall('sales_orders', 'update')![0] as Record<string, unknown>
|
||||
expect(patch.status).toBe('confirmed')
|
||||
expect(typeof patch.confirmed_at).toBe('string')
|
||||
expect(() => new Date(patch.confirmed_at as string).toISOString()).not.toThrow()
|
||||
// Compare-and-set on the status that was read.
|
||||
expect(findCalls('sales_orders', 'eq')).toContainEqual(['status', 'draft'])
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('refresh_sales_order_completion', { p_order_id: IDS.order })
|
||||
})
|
||||
|
||||
it('reports SALES_ORDER_INVALID_STATE when the compare-and-set matches no row (lost race)', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // CAS update matched nothing
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_INVALID_STATE' })
|
||||
expect(supabase.rpc).not.toHaveBeenCalledWith('refresh_sales_order_completion', expect.anything())
|
||||
})
|
||||
|
||||
it('cancels a draft with no invoices and stamps cancelled_at', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // hasOpenInvoices rpc
|
||||
enqueue({ data: null, count: 0 }) // no header-linked invoices
|
||||
enqueue({ data: [{ id: IDS.order }] })
|
||||
enqueue({ data: makeSalesOrder({ status: 'cancelled', cancelled_at: '2026-09-02T10:00:00Z' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'cancel' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
const patch = findCall('sales_orders', 'update')![0] as Record<string, unknown>
|
||||
expect(patch.status).toBe('cancelled')
|
||||
expect(typeof patch.cancelled_at).toBe('string')
|
||||
expect(supabase.rpc).not.toHaveBeenCalledWith('refresh_sales_order_completion', expect.anything())
|
||||
})
|
||||
|
||||
it('reopens a cancelled order back to draft and clears every timestamp', async () => {
|
||||
enqueue({
|
||||
data: makeSalesOrder({
|
||||
status: 'cancelled',
|
||||
cancelled_at: '2026-09-02T10:00:00Z',
|
||||
confirmed_at: '2026-09-01T10:00:00Z',
|
||||
items: [makeSalesOrderItem()],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null, count: 0 })
|
||||
enqueue({ data: [{ id: IDS.order }] })
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'reopen' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(findCall('sales_orders', 'update')![0]).toEqual({
|
||||
status: 'draft',
|
||||
cancelled_at: null,
|
||||
confirmed_at: null,
|
||||
completed_at: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('surfaces a DB error from the update as a dbError failure', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null, error: { message: 'connection reset', code: '08006' } })
|
||||
|
||||
const result = await transitionSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, action: 'confirm' })
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect('dbError' in result && result.dbError).toMatchObject({ message: 'connection reset' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,512 @@
|
||||
/**
|
||||
* createSalesOrder / updateSalesOrder with the queued Supabase mock.
|
||||
*
|
||||
* updateSalesOrder queue order: loadSalesOrder (sales_orders select,
|
||||
* invoiced rpc), then ONLY when customer_id or currency changes:
|
||||
* hasOpenInvoices (invoiced rpc, and an invoices head count when no line
|
||||
* carries invoiced quantity), then customers select, sales_orders update,
|
||||
* then when lines are given: sales_order_items delete (only if any
|
||||
* dropped), one sales_order_items update per kept line, one insert for new
|
||||
* lines, and a final loadSalesOrder.
|
||||
*
|
||||
* The header update is an object literal with every column present (an
|
||||
* omitted input leaves undefined, which PostgREST drops), so assertions use
|
||||
* toMatchObject and check the untouched keys are undefined explicitly.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { createSalesOrder, hasOpenInvoices, updateSalesOrder } from '../write'
|
||||
import { IDS, invoicedRow, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem } from './fixtures'
|
||||
|
||||
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
|
||||
const sb = supabase as unknown as SupabaseClient
|
||||
|
||||
const baseLine = { description: 'Konsulttimme', quantity: 10, unit: 'h', unit_price: 100, vat_rate: 25 }
|
||||
|
||||
describe('updateSalesOrder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('returns SALES_ORDER_NOT_FOUND for a missing order', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await updateSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, input: { notes: 'x' } })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('refuses edits on a completed order', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'completed', completed_at: '2026-09-02T10:00:00Z' }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 10)] })
|
||||
|
||||
const result = await updateSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, input: { notes: 'Sen' } })
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_EDITABLE', details: { status: 'completed' } })
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses edits on a cancelled order', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'cancelled' }) })
|
||||
enqueue({ data: [] })
|
||||
const result = await updateSalesOrder(sb, { companyId: IDS.company, orderId: IDS.order, input: { notes: 'Sen' } })
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_EDITABLE' })
|
||||
})
|
||||
|
||||
it('refuses dropping a line that has invoiced quantity', async () => {
|
||||
enqueue({
|
||||
data: makeSalesOrder({
|
||||
status: 'confirmed',
|
||||
items: [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, description: 'Licens', quantity: 2 }),
|
||||
],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 3)] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
|
||||
// Only item2 comes back: item1 (3 invoiced) would be deleted.
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.item2, ...baseLine, description: 'Licens', quantity: 2 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_LINE_LOCKED',
|
||||
details: { sales_order_item_id: IDS.item1 },
|
||||
})
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
expect(findCall('sales_order_items', 'delete')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses dropping a line that has delivered quantity', async () => {
|
||||
enqueue({
|
||||
data: makeSalesOrder({
|
||||
status: 'confirmed',
|
||||
items: [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 1 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 2 }),
|
||||
],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.item2, ...baseLine, quantity: 2 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_LINE_LOCKED' })
|
||||
})
|
||||
|
||||
it('refuses lowering a line below its delivered quantity', async () => {
|
||||
enqueue({
|
||||
data: makeSalesOrder({
|
||||
status: 'confirmed',
|
||||
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5 })],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.item1, ...baseLine, quantity: 3 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_DELIVERED',
|
||||
details: { sales_order_item_id: IDS.item1, delivered_qty: 5 },
|
||||
})
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses lowering a line below its invoiced quantity', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed', items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10 })] }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 4)] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.item1, ...baseLine, quantity: 3 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_QUANTITY_BELOW_INVOICED',
|
||||
details: { sales_order_item_id: IDS.item1, invoiced_qty: 4 },
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a line id that does not belong to the order', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.unknownItem, ...baseLine }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_LINE_NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('returns CUSTOMER_NOT_FOUND when the new customer is not in the company', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { customer_id: IDS.otherCustomer },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'CUSTOMER_NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('re-validates stored lines when only the customer changes (25 % line to a validated EU business)', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', items: [makeSalesOrderItem({ vat_rate: 25 })] }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // hasOpenInvoices: invoiced rpc (nothing invoiced)
|
||||
enqueue({ data: null, count: 0 }) // hasOpenInvoices: no header-linked invoice
|
||||
enqueue({
|
||||
data: makeOrderCustomer({
|
||||
id: IDS.otherCustomer,
|
||||
customer_type: 'eu_business',
|
||||
vat_number: 'DE123456789',
|
||||
vat_number_validated: true,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', customer_id: IDS.otherCustomer }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { customer_id: IDS.otherCustomer },
|
||||
})
|
||||
|
||||
// 25 % is permitted for a validated EU business (taxed where performed),
|
||||
// so the customer change goes through and only the header is written,
|
||||
// with the snapshot refreshed to the NEW customer's VAT facts.
|
||||
expect(result.ok).toBe(true)
|
||||
expect(findCall('sales_orders', 'update')![0]).toMatchObject({
|
||||
customer_id: IDS.otherCustomer,
|
||||
customer_type_snapshot: 'eu_business',
|
||||
customer_vat_validated_snapshot: true,
|
||||
})
|
||||
expect(findCall('sales_order_items', 'update')).toBeUndefined()
|
||||
expect(findCalls('invoices', 'eq')).toContainEqual(['sales_order_id', IDS.order])
|
||||
})
|
||||
|
||||
it('refuses a customer change with SALES_ORDER_HAS_INVOICES once a line has invoiced quantity', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed', items: [makeSalesOrderItem({ id: IDS.item1 })] }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 2)] }) // loadSalesOrder
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 2)] }) // hasOpenInvoices rpc
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { customer_id: IDS.otherCustomer, notes: 'Byt kund' },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_HAS_INVOICES', details: { field: 'customer_id' } })
|
||||
// The check runs before the customer is even loaded and nothing is written.
|
||||
expect(findCall('customers', 'select')).toBeUndefined()
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses a currency change when a header-linked invoice exists even with zero invoiced quantity', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // hasOpenInvoices rpc: nothing invoiced
|
||||
enqueue({ data: null, count: 1 }) // but an invoice still points at the order
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { currency: 'EUR' },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_HAS_INVOICES', details: { field: 'currency' } })
|
||||
expect(findCall('customers', 'select')).toBeUndefined()
|
||||
expect(findCall('sales_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('skips the open-invoice check when customer_id and currency are unchanged', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 2)] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed', notes: 'Samma kund' }) })
|
||||
enqueue({ data: [invoicedRow(IDS.item1, 2)] })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { customer_id: IDS.customer, currency: 'SEK', notes: 'Samma kund' },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
// Two rpc calls: the two loadSalesOrder calls, no hasOpenInvoices in between.
|
||||
expect(supabase.rpc).toHaveBeenCalledTimes(2)
|
||||
expect(findCall('invoices', 'select')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('updates header only when no lines are given, keeping stored totals', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', subtotal: 1000, vat_amount: 250, total: 1250 }) })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', notes: 'Leverans till lagret' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { notes: 'Leverans till lagret', requested_delivery_date: '2026-09-15' },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.order.notes).toBe('Leverans till lagret')
|
||||
const headerUpdate = findCall('sales_orders', 'update')![0] as Record<string, unknown>
|
||||
expect(headerUpdate).toMatchObject({
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
notes: 'Leverans till lagret',
|
||||
requested_delivery_date: '2026-09-15',
|
||||
customer_type_snapshot: 'swedish_business',
|
||||
customer_vat_validated_snapshot: false,
|
||||
})
|
||||
// Omitted inputs stay undefined so PostgREST leaves the columns alone.
|
||||
for (const key of ['customer_id', 'currency', 'order_date', 'your_reference', 'our_reference', 'default_dimensions']) {
|
||||
expect(headerUpdate).toHaveProperty(key)
|
||||
expect(headerUpdate[key]).toBeUndefined()
|
||||
}
|
||||
expect(findCall('sales_order_items', 'update')).toBeUndefined()
|
||||
expect(findCall('sales_order_items', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('replaces lines: updates kept lines by id, inserts new ones, deletes omitted ones, recomputes totals', async () => {
|
||||
enqueue({
|
||||
data: makeSalesOrder({
|
||||
status: 'confirmed',
|
||||
items: [
|
||||
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 2 }),
|
||||
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, description: 'Bortplockad', quantity: 1 }),
|
||||
],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: null }) // delete item2
|
||||
enqueue({ data: null }) // update item1
|
||||
enqueue({ data: null }) // insert new line
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: {
|
||||
items: [
|
||||
{ id: IDS.item1, ...baseLine, quantity: 12 },
|
||||
{ description: 'Resa', quantity: 1, unit: 'st', unit_price: 500, vat_rate: 6 },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
// 12 x 100 @ 25 % + 500 @ 6 %
|
||||
const headerUpdate = findCall('sales_orders', 'update')![0] as Record<string, unknown>
|
||||
expect(headerUpdate).toMatchObject({
|
||||
subtotal: 1700,
|
||||
vat_amount: 330,
|
||||
total: 2030,
|
||||
customer_type_snapshot: 'swedish_business',
|
||||
customer_vat_validated_snapshot: false,
|
||||
})
|
||||
expect(headerUpdate.customer_id).toBeUndefined()
|
||||
expect(headerUpdate.notes).toBeUndefined()
|
||||
expect(findCall('sales_order_items', 'in')).toEqual(['id', [IDS.item2]])
|
||||
const lineUpdate = findCall('sales_order_items', 'update')![0] as Record<string, unknown>
|
||||
expect(lineUpdate).toMatchObject({ quantity: 12, sort_order: 0, line_total: 1200 })
|
||||
expect(lineUpdate).not.toHaveProperty('id')
|
||||
const inserted = findCall('sales_order_items', 'insert')![0] as Record<string, unknown>[]
|
||||
expect(inserted).toHaveLength(1)
|
||||
expect(inserted[0]).toMatchObject({
|
||||
description: 'Resa',
|
||||
sort_order: 1,
|
||||
vat_rate: 6,
|
||||
line_total: 500,
|
||||
company_id: IDS.company,
|
||||
sales_order_id: IDS.order,
|
||||
})
|
||||
expect(inserted[0]).not.toHaveProperty('id')
|
||||
})
|
||||
|
||||
it('maps the quantity-below-invoiced trigger onto SALES_ORDER_QUANTITY_BELOW_INVOICED (race)', async () => {
|
||||
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
|
||||
enqueue({ data: [] }) // pre-check sees nothing invoiced
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: null }) // header update
|
||||
enqueue({ data: null, error: { message: 'SALES_ORDER_QUANTITY_BELOW_INVOICED: line d1 has 4 invoiced' } })
|
||||
|
||||
const result = await updateSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
orderId: IDS.order,
|
||||
input: { items: [{ id: IDS.item1, ...baseLine, quantity: 3 }] },
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_QUANTITY_BELOW_INVOICED' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('createSalesOrder', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('returns CUSTOMER_NOT_FOUND when the customer is not in the company', async () => {
|
||||
enqueue({ data: null })
|
||||
const result = await createSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
userId: IDS.user,
|
||||
input: { customer_id: IDS.customer, items: [baseLine] },
|
||||
})
|
||||
expect(result).toMatchObject({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: IDS.customer } })
|
||||
expect(findCall('sales_orders', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('propagates the VAT gate before any insert', async () => {
|
||||
enqueue({ data: makeOrderCustomer({ customer_type: 'non_eu_business' }) })
|
||||
const result = await createSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
userId: IDS.user,
|
||||
input: { customer_id: IDS.customer, items: [{ ...baseLine, vat_rate: 20 }] },
|
||||
})
|
||||
expect(result).toMatchObject({ ok: false, code: 'INVOICE_CREATE_VAT_RULE_VIOLATION' })
|
||||
expect(findCall('sales_orders', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('inserts header + lines, numbers the order and reloads it', async () => {
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.order } }) // header insert
|
||||
enqueue({ data: null }) // items insert
|
||||
enqueue({ data: 'OR-1' }) // generate_sales_order_number
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', order_number: 'OR-1' }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await createSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
userId: IDS.user,
|
||||
input: {
|
||||
customer_id: IDS.customer,
|
||||
order_date: '2026-09-01',
|
||||
items: [baseLine, { line_type: 'text', description: 'Tack för din order', quantity: 0, unit: '', unit_price: 0 }],
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.order.order_number).toBe('OR-1')
|
||||
expect(findCall('sales_orders', 'insert')![0]).toMatchObject({
|
||||
company_id: IDS.company,
|
||||
user_id: IDS.user,
|
||||
customer_id: IDS.customer,
|
||||
status: 'draft',
|
||||
source_invoice_id: null,
|
||||
order_date: '2026-09-01',
|
||||
currency: 'SEK',
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
// The customer facts the lines were VAT-validated under travel with the order.
|
||||
customer_type_snapshot: 'swedish_business',
|
||||
customer_vat_validated_snapshot: false,
|
||||
})
|
||||
const lines = findCall('sales_order_items', 'insert')![0] as Record<string, unknown>[]
|
||||
expect(lines).toHaveLength(2)
|
||||
expect(lines[0]).toMatchObject({ sales_order_id: IDS.order, company_id: IDS.company, line_type: 'product' })
|
||||
expect(lines[1]).toMatchObject({ line_type: 'text', quantity: 0, line_total: 0 })
|
||||
expect(supabase.rpc).toHaveBeenCalledWith('generate_sales_order_number', {
|
||||
p_company_id: IDS.company,
|
||||
p_order_id: IDS.order,
|
||||
})
|
||||
expect(findCalls('sales_orders', 'eq')).toContainEqual(['id', IDS.order])
|
||||
})
|
||||
|
||||
it('rolls the header back when the line insert fails', async () => {
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.order } })
|
||||
enqueue({ data: null, error: { message: 'insert failed', code: '23502' } })
|
||||
enqueue({ data: null }) // header delete
|
||||
|
||||
const result = await createSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
userId: IDS.user,
|
||||
input: { customer_id: IDS.customer, items: [baseLine] },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect('dbError' in result).toBe(true)
|
||||
expect(findCall('sales_orders', 'delete')).toBeDefined()
|
||||
expect(supabase.rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still returns the order when numbering fails (number assigned on the next write)', async () => {
|
||||
enqueue({ data: makeOrderCustomer() })
|
||||
enqueue({ data: { id: IDS.order } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: null, error: { message: 'counter locked' } }) // rpc fails
|
||||
enqueue({ data: makeSalesOrder({ status: 'draft', order_number: null }) })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await createSalesOrder(sb, {
|
||||
companyId: IDS.company,
|
||||
userId: IDS.user,
|
||||
input: { customer_id: IDS.customer, items: [baseLine] },
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.order.order_number).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasOpenInvoices', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
it('is open as soon as any line carries invoiced quantity (no header count needed)', async () => {
|
||||
enqueue({ data: [invoicedRow(IDS.item1, '1')] })
|
||||
const result = await hasOpenInvoices(sb, IDS.company, IDS.order)
|
||||
expect(result).toEqual({ ok: true, open: true })
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to a header count when no line is invoiced', async () => {
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null, count: 0 })
|
||||
const result = await hasOpenInvoices(sb, IDS.company, IDS.order)
|
||||
expect(result).toEqual({ ok: true, open: false })
|
||||
expect(findCalls('invoices', 'eq')).toContainEqual(['sales_order_id', IDS.order])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { Invoice, InvoiceItem, SalesOrder } from '@/types'
|
||||
import { createSalesOrder } from './write'
|
||||
import { fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
/**
|
||||
* Proforma -> kundorder. The proforma is the closest thing to an offert
|
||||
* the product has today, so this is the "Skapa order" action on it. Copies
|
||||
* header + lines into a new DRAFT order (source_invoice_id back-pointer)
|
||||
* and, like proforma -> invoice, marks the proforma cancelled: the order
|
||||
* now carries the agreement. Only one order per proforma.
|
||||
*
|
||||
* Order lines have no ROT/RUT or periodisering fields and no negative
|
||||
* quantities. A proforma carrying any of those is refused outright
|
||||
* (SALES_ORDER_SOURCE_UNSUPPORTED_LINES) instead of silently losing the
|
||||
* skattereduktion or the accrual on the invoice that the order later
|
||||
* produces.
|
||||
*/
|
||||
export async function convertProformaToSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; userId: string; invoiceId: string },
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { companyId, userId, invoiceId } = params
|
||||
const { data: proforma, error } = await supabase
|
||||
.from('invoices')
|
||||
.select('*, items:invoice_items(*)')
|
||||
.eq('id', invoiceId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle<Invoice & { items: InvoiceItem[] }>()
|
||||
if (error) return failDb(error)
|
||||
if (!proforma) return fail('INVOICE_NOT_FOUND')
|
||||
if (proforma.document_type !== 'proforma') return fail('SALES_ORDER_SOURCE_NOT_PROFORMA')
|
||||
if (proforma.status === 'cancelled') return fail('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
|
||||
|
||||
const { count } = await supabase
|
||||
.from('sales_orders')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('source_invoice_id', invoiceId)
|
||||
if ((count ?? 0) > 0) return fail('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
|
||||
if (!proforma.customer_id) return fail('SALES_ORDER_CUSTOMER_MISSING')
|
||||
|
||||
const sourceItems = [...(proforma.items ?? [])].sort((a, b) => a.sort_order - b.sort_order)
|
||||
const unsupported = sourceItems.filter(
|
||||
(item) =>
|
||||
(item.line_type ?? 'product') === 'product' &&
|
||||
(Boolean(item.deduction_type) ||
|
||||
Boolean(item.accrual_period_start) ||
|
||||
Boolean(item.accrual_period_end) ||
|
||||
Boolean(item.accrual_balance_account) ||
|
||||
item.quantity < 0),
|
||||
)
|
||||
if (unsupported.length > 0) {
|
||||
return fail('SALES_ORDER_SOURCE_UNSUPPORTED_LINES', {
|
||||
lines: unsupported.map((item) => ({
|
||||
invoice_item_id: item.id,
|
||||
deduction_type: item.deduction_type ?? null,
|
||||
accrual: Boolean(item.accrual_period_start || item.accrual_period_end),
|
||||
quantity: item.quantity,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
const items = sourceItems.map((item) => ({
|
||||
line_type: (item.line_type ?? 'product') as 'product' | 'text',
|
||||
description: item.description,
|
||||
quantity: item.line_type === 'text' ? 0 : item.quantity,
|
||||
unit: item.unit ?? 'st',
|
||||
unit_price: item.unit_price,
|
||||
discount_percent: item.discount_percent ?? null,
|
||||
vat_rate: item.vat_rate,
|
||||
article_id: item.article_id ?? null,
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
dimensions: item.dimensions ?? {},
|
||||
}))
|
||||
if (items.length === 0) return fail('SALES_ORDER_NOTHING_TO_INVOICE')
|
||||
|
||||
const created = await createSalesOrder(supabase, {
|
||||
companyId,
|
||||
userId,
|
||||
sourceInvoiceId: invoiceId,
|
||||
input: {
|
||||
customer_id: proforma.customer_id,
|
||||
currency: proforma.currency,
|
||||
your_reference: proforma.your_reference ?? null,
|
||||
our_reference: proforma.our_reference ?? null,
|
||||
notes: proforma.notes ?? null,
|
||||
default_dimensions: proforma.default_dimensions ?? {},
|
||||
items,
|
||||
},
|
||||
})
|
||||
if (!created.ok) return created
|
||||
|
||||
// Compare-and-set so a concurrent convert (to invoice or to order) cannot
|
||||
// both succeed; on a lost race the fresh draft order is removed again.
|
||||
const { data: marked, error: markError } = await supabase
|
||||
.from('invoices')
|
||||
.update({ status: 'cancelled' })
|
||||
.eq('id', invoiceId)
|
||||
.eq('company_id', companyId)
|
||||
.neq('status', 'cancelled')
|
||||
.select('id')
|
||||
if (markError || !marked || marked.length === 0) {
|
||||
await supabase.from('sales_orders').delete().eq('id', created.order.id).eq('company_id', companyId)
|
||||
if (markError) return failDb(markError)
|
||||
return fail('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
|
||||
}
|
||||
|
||||
return created
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { z } from 'zod'
|
||||
import type { Currency, Customer, Invoice, SalesOrder, SalesOrderItem } from '@/types'
|
||||
import type { CreateInvoiceFromSalesOrderSchema } from '@/lib/api/schemas'
|
||||
import { buildInvoiceWriteData, type InvoiceWriteInput } from '@/lib/invoices/build-invoice-write'
|
||||
import { todayIsoStockholm } from '@/lib/dates/iso'
|
||||
import { loadSalesOrder } from './load'
|
||||
import { qtyGreater, roundQty } from './progress'
|
||||
import { codeFromPgError, fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
export type CreateInvoiceFromOrderInput = z.infer<typeof CreateInvoiceFromSalesOrderSchema>
|
||||
|
||||
export interface PickedLine {
|
||||
item: SalesOrderItem
|
||||
quantity: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which order lines (and how much of each) go on the invoice.
|
||||
* Explicit picks win (duplicates for the same line are summed); otherwise
|
||||
* `mode` selects:
|
||||
* remaining = everything not yet invoiced (default)
|
||||
* delivered = delivered but not yet invoiced (delivered_qty - invoiced_qty)
|
||||
* Quantities are rounded to quantity precision so a float remainder such as
|
||||
* 0.5999999999999996 never reaches the DB or the invoice. Text rows are
|
||||
* carried along as text lines when at least one product line is picked, so
|
||||
* the invoice reads like the order.
|
||||
*/
|
||||
export function pickLines(
|
||||
order: SalesOrder,
|
||||
input: Pick<CreateInvoiceFromOrderInput, 'mode' | 'lines'>,
|
||||
): ServiceResult<{ picked: PickedLine[] }> {
|
||||
const items = (order.items ?? []).filter((i) => i.line_type !== 'text')
|
||||
const byId = new Map(items.map((i) => [i.id, i]))
|
||||
const picked: PickedLine[] = []
|
||||
|
||||
if (input.lines && input.lines.length > 0) {
|
||||
const requested = new Map<string, number>()
|
||||
for (const line of input.lines) {
|
||||
requested.set(line.sales_order_item_id, roundQty((requested.get(line.sales_order_item_id) ?? 0) + line.quantity))
|
||||
}
|
||||
for (const [itemId, quantity] of requested) {
|
||||
const item = byId.get(itemId)
|
||||
if (!item) return fail('SALES_ORDER_LINE_NOT_FOUND', { sales_order_item_id: itemId })
|
||||
const remaining = remainingOf(item)
|
||||
if (qtyGreater(quantity, remaining)) {
|
||||
return fail('SALES_ORDER_OVER_INVOICED', {
|
||||
sales_order_item_id: item.id,
|
||||
remaining_qty: remaining,
|
||||
requested_qty: quantity,
|
||||
})
|
||||
}
|
||||
if (quantity > 0) picked.push({ item, quantity })
|
||||
}
|
||||
} else {
|
||||
const mode = input.mode ?? 'remaining'
|
||||
for (const item of items) {
|
||||
const invoiced = roundQty(item.invoiced_qty ?? 0)
|
||||
const remaining = remainingOf(item)
|
||||
const qty =
|
||||
mode === 'delivered'
|
||||
? Math.max(0, Math.min(remaining, roundQty(item.delivered_qty - invoiced)))
|
||||
: remaining
|
||||
if (qty > 0) picked.push({ item, quantity: qty })
|
||||
}
|
||||
}
|
||||
|
||||
if (picked.length === 0) return fail('SALES_ORDER_NOTHING_TO_INVOICE')
|
||||
return { ok: true, picked }
|
||||
}
|
||||
|
||||
function remainingOf(item: SalesOrderItem): number {
|
||||
if (typeof item.remaining_qty === 'number') return roundQty(item.remaining_qty)
|
||||
return Math.max(0, roundQty(item.quantity - roundQty(item.invoiced_qty ?? 0)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Leveransdatum for the invoice (ML 17 kap 24 § p.7; also the FX anchor per
|
||||
* ML 8 kap 21-23 §): the latest per-line delivery date over the lines the
|
||||
* invoice covers, and only when every covered quantity has actually been
|
||||
* delivered (delivered minus already invoiced covers the pick). An advance
|
||||
* invoice for undelivered quantity gets no delivery date.
|
||||
*/
|
||||
export function deliveryDateFor(picked: PickedLine[]): string | null {
|
||||
let latest: string | null = null
|
||||
for (const { item, quantity } of picked) {
|
||||
const undeliveredInvoiceable = roundQty(item.delivered_qty - roundQty(item.invoiced_qty ?? 0))
|
||||
if (qtyGreater(quantity, undeliveredInvoiceable)) return null
|
||||
const date = item.last_delivery_date ?? null
|
||||
if (!date) return null
|
||||
if (!latest || date > latest) latest = date
|
||||
}
|
||||
return latest
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an unnumbered DRAFT kundfaktura from an order.
|
||||
*
|
||||
* Goes through buildInvoiceWriteData() like every other invoice (VAT gating,
|
||||
* totals, currency, revenue-account validation), so booking stays in the
|
||||
* engine when the draft is later sent. Each invoice line carries
|
||||
* sales_order_item_id; the order's invoiced quantity is derived from those
|
||||
* links and the DB trigger refuses over-invoicing even under a race. The
|
||||
* order's completion (confirmed -> completed) is maintained by the DB.
|
||||
*
|
||||
* Refuses when the customer's VAT facts (type, VAT-number validation) no
|
||||
* longer match what the order lines were validated under: a frozen 25 %
|
||||
* line can pass the permitted-set gate for a since-validated EU business
|
||||
* and would otherwise land silently. Re-saving the order re-validates.
|
||||
*/
|
||||
export async function createInvoiceFromSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; userId: string; orderId: string; input: CreateInvoiceFromOrderInput },
|
||||
): Promise<ServiceResult<{ invoice: Invoice; order: SalesOrder }>> {
|
||||
const { companyId, userId, orderId, input } = params
|
||||
const current = await loadSalesOrder(supabase, companyId, orderId)
|
||||
if (!current.ok) return current
|
||||
const order = current.order
|
||||
if (order.status !== 'confirmed') {
|
||||
return fail('SALES_ORDER_INVALID_STATE', { status: order.status, action: 'invoice' })
|
||||
}
|
||||
if (!order.customer_id) return fail('SALES_ORDER_CUSTOMER_MISSING')
|
||||
|
||||
const pickedRes = pickLines(order, input)
|
||||
if (!pickedRes.ok) return pickedRes
|
||||
const { picked } = pickedRes
|
||||
|
||||
// Raw customer row for the builder (the embed on the order is masked).
|
||||
const { data: customer } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('id', order.customer_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle<Customer>()
|
||||
if (!customer) return fail('CUSTOMER_NOT_FOUND', { customerId: order.customer_id })
|
||||
|
||||
if (
|
||||
order.customer_type_snapshot &&
|
||||
(order.customer_type_snapshot !== customer.customer_type ||
|
||||
(order.customer_vat_validated_snapshot ?? false) !== (customer.vat_number_validated ?? false))
|
||||
) {
|
||||
return fail('SALES_ORDER_CUSTOMER_VAT_CHANGED', {
|
||||
snapshot: {
|
||||
customer_type: order.customer_type_snapshot,
|
||||
vat_number_validated: order.customer_vat_validated_snapshot ?? false,
|
||||
},
|
||||
current: {
|
||||
customer_type: customer.customer_type,
|
||||
vat_number_validated: customer.vat_number_validated ?? false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const invoiceDate = input.invoice_date ?? todayIsoStockholm()
|
||||
let dueDate = input.due_date
|
||||
if (!dueDate) {
|
||||
const due = new Date(invoiceDate)
|
||||
due.setDate(due.getDate() + (customer.default_payment_terms ?? 30))
|
||||
dueDate = due.toISOString().slice(0, 10)
|
||||
}
|
||||
const deliveryDate = deliveryDateFor(picked)
|
||||
|
||||
const pickedById = new Map(picked.map((p) => [p.item.id, p]))
|
||||
const items: InvoiceWriteInput['items'] = []
|
||||
for (const line of [...(order.items ?? [])].sort((a, b) => a.sort_order - b.sort_order)) {
|
||||
if (line.line_type === 'text') {
|
||||
items.push({ line_type: 'text', description: line.description, quantity: 0, unit: '', unit_price: 0 })
|
||||
continue
|
||||
}
|
||||
const pick = pickedById.get(line.id)
|
||||
if (!pick) continue
|
||||
items.push({
|
||||
line_type: 'product',
|
||||
description: line.description,
|
||||
quantity: pick.quantity,
|
||||
unit: line.unit,
|
||||
unit_price: line.unit_price,
|
||||
discount_percent: line.discount_percent > 0 ? line.discount_percent : null,
|
||||
vat_rate: line.vat_rate,
|
||||
article_id: line.article_id,
|
||||
revenue_account: line.revenue_account,
|
||||
sales_order_item_id: line.id,
|
||||
dimensions: line.dimensions,
|
||||
})
|
||||
}
|
||||
|
||||
const build = await buildInvoiceWriteData({
|
||||
supabase,
|
||||
companyId,
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input: {
|
||||
customer_id: customer.id,
|
||||
invoice_date: invoiceDate,
|
||||
due_date: dueDate,
|
||||
delivery_date: deliveryDate,
|
||||
currency: order.currency as Currency,
|
||||
your_reference: order.your_reference ?? undefined,
|
||||
our_reference: order.our_reference ?? undefined,
|
||||
notes: order.order_number ? `Kundorder ${order.order_number}` : undefined,
|
||||
default_dimensions: order.default_dimensions ?? {},
|
||||
items,
|
||||
},
|
||||
})
|
||||
if (!build.ok) {
|
||||
if ('dbError' in build) return failDb(build.dbError)
|
||||
return fail(build.code, build.details)
|
||||
}
|
||||
|
||||
const { data: invoice, error: invoiceError } = await supabase
|
||||
.from('invoices')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
invoice_number: null,
|
||||
status: 'draft',
|
||||
sales_order_id: orderId,
|
||||
...build.invoiceFields,
|
||||
})
|
||||
.select()
|
||||
.single<Invoice>()
|
||||
if (invoiceError || !invoice) return failDb(invoiceError ?? new Error('invoice insert returned no row'))
|
||||
|
||||
const { error: itemsError } = await supabase
|
||||
.from('invoice_items')
|
||||
.insert(build.items.map((item) => ({ ...item, invoice_id: invoice.id })))
|
||||
if (itemsError) {
|
||||
// Unnumbered draft: hard delete leaves no F-series gap.
|
||||
await supabase.from('invoice_items').delete().eq('invoice_id', invoice.id)
|
||||
await supabase.from('invoices').delete().eq('id', invoice.id)
|
||||
const code = codeFromPgError(itemsError)
|
||||
return code ? fail(code) : failDb(itemsError)
|
||||
}
|
||||
|
||||
const reloaded = await loadSalesOrder(supabase, companyId, orderId)
|
||||
if (!reloaded.ok) return reloaded
|
||||
return { ok: true, invoice, order: reloaded.order }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* Assign OR-<n> to a sales order via the generate_sales_order_number RPC.
|
||||
* Idempotent (an already numbered order returns its number without
|
||||
* consuming the counter) and concurrency-safe inside the RPC (row lock on
|
||||
* the order + atomic counter on company_settings). Mirrors
|
||||
* lib/articles/ensure-article-number.ts; orders are not verifikationer, so
|
||||
* a gap is harmless.
|
||||
*/
|
||||
export async function ensureSalesOrderNumber(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
orderId: string,
|
||||
): Promise<string> {
|
||||
const { data, error } = await supabase.rpc('generate_sales_order_number', {
|
||||
p_company_id: companyId,
|
||||
p_order_id: orderId,
|
||||
})
|
||||
if (error || !data) {
|
||||
throw new Error(`Failed to assign sales order number: ${error?.message ?? 'no value returned'}`)
|
||||
}
|
||||
return data as string
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Customer, SalesOrderItemInput } from '@/types'
|
||||
import { getVatRules, getPermittedVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { computeLineNet } from '@/lib/invoices/line-amounts'
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
/**
|
||||
* Order-line normalisation + totals.
|
||||
*
|
||||
* Same line math as invoices (computeLineNet: net of the percentage
|
||||
* discount, öre-exact) and the same per-customer VAT gating, so an order
|
||||
* that saves here always converts into an invoice buildInvoiceWriteData()
|
||||
* accepts. Order totals are informational (the order never books); the
|
||||
* invoice recomputes its own totals from the lines it is given.
|
||||
*/
|
||||
export interface SalesOrderLineRow {
|
||||
id?: string
|
||||
sort_order: number
|
||||
line_type: 'product' | 'text'
|
||||
description: string
|
||||
quantity: number
|
||||
unit: string
|
||||
unit_price: number
|
||||
discount_percent: number
|
||||
vat_rate: number
|
||||
line_total: number
|
||||
article_id: string | null
|
||||
revenue_account: string | null
|
||||
dimensions: Record<string, string>
|
||||
}
|
||||
|
||||
export interface SalesOrderTotals {
|
||||
subtotal: number
|
||||
vat_amount: number
|
||||
total: number
|
||||
}
|
||||
|
||||
export type NormalizeLinesResult =
|
||||
| { ok: true; rows: SalesOrderLineRow[]; totals: SalesOrderTotals }
|
||||
| { ok: false; code: string; details?: Record<string, unknown> }
|
||||
|
||||
export function normalizeSalesOrderLines(
|
||||
items: SalesOrderItemInput[],
|
||||
customer: Pick<Customer, 'customer_type' | 'vat_number_validated'>,
|
||||
): NormalizeLinesResult {
|
||||
const vatRules = getVatRules(customer.customer_type, customer.vat_number_validated)
|
||||
const allowed = new Set(
|
||||
getPermittedVatRates(customer.customer_type, customer.vat_number_validated).map((r) => r.rate),
|
||||
)
|
||||
|
||||
const rows: SalesOrderLineRow[] = []
|
||||
let subtotal = 0
|
||||
let vat = 0
|
||||
|
||||
for (let index = 0; index < items.length; index++) {
|
||||
const item = items[index]
|
||||
if (item.line_type === 'text') {
|
||||
rows.push({
|
||||
id: item.id,
|
||||
sort_order: index,
|
||||
line_type: 'text',
|
||||
description: item.description,
|
||||
quantity: 0,
|
||||
unit: '',
|
||||
unit_price: 0,
|
||||
discount_percent: 0,
|
||||
vat_rate: 0,
|
||||
line_total: 0,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
dimensions: {},
|
||||
})
|
||||
continue
|
||||
}
|
||||
const rate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
|
||||
if (!allowed.has(rate)) {
|
||||
// Same envelope the invoice builder answers for a rate the customer
|
||||
// type does not permit (e.g. 25 % to a validated EU business).
|
||||
return {
|
||||
ok: false,
|
||||
code: 'INVOICE_CREATE_VAT_RULE_VIOLATION',
|
||||
details: {
|
||||
attemptedRate: rate,
|
||||
allowedRates: Array.from(allowed),
|
||||
customerType: customer.customer_type,
|
||||
line: index,
|
||||
},
|
||||
}
|
||||
}
|
||||
const discount = item.discount_percent ?? 0
|
||||
const lineTotal = computeLineNet(item.quantity, item.unit_price, discount)
|
||||
const lineVat = roundOre((lineTotal * rate) / 100)
|
||||
subtotal = roundOre(subtotal + lineTotal)
|
||||
vat = roundOre(vat + lineVat)
|
||||
rows.push({
|
||||
id: item.id,
|
||||
sort_order: index,
|
||||
line_type: 'product',
|
||||
description: item.description,
|
||||
quantity: item.quantity,
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
discount_percent: discount,
|
||||
vat_rate: rate,
|
||||
line_total: lineTotal,
|
||||
article_id: item.article_id ?? null,
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
dimensions: item.dimensions ?? {},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
rows,
|
||||
totals: { subtotal, vat_amount: vat, total: roundOre(subtotal + vat) },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { SalesOrder, SalesOrderItem } from '@/types'
|
||||
import { maskEmbeddedCustomer } from '@/lib/customers/protect-personal-number'
|
||||
import { deliveryProgress, invoicingProgress, withInvoicedQuantities } from './progress'
|
||||
import { fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
/**
|
||||
* Invoiced quantity per order line for a set of orders, from the
|
||||
* SECURITY INVOKER RPC (RLS applies). Returns an empty map for no ids.
|
||||
*/
|
||||
export async function fetchInvoicedQuantities(
|
||||
supabase: SupabaseClient,
|
||||
orderIds: string[],
|
||||
): Promise<{ ok: true; byItem: Map<string, number> } | { ok: false; dbError: unknown }> {
|
||||
if (orderIds.length === 0) return { ok: true, byItem: new Map() }
|
||||
const { data, error } = await supabase.rpc('sales_order_invoiced_quantities', {
|
||||
p_order_ids: orderIds,
|
||||
})
|
||||
if (error) return { ok: false, dbError: error }
|
||||
const byItem = new Map<string, number>()
|
||||
for (const row of (data ?? []) as Array<{ sales_order_item_id: string; invoiced_qty: number | string }>) {
|
||||
byItem.set(row.sales_order_item_id, Number(row.invoiced_qty))
|
||||
}
|
||||
return { ok: true, byItem }
|
||||
}
|
||||
|
||||
/**
|
||||
* One order with its customer (masked), its lines in sort order, the
|
||||
* derived invoiced/remaining quantities and both progress axes.
|
||||
*/
|
||||
export async function loadSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
orderId: string,
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { data, error } = await supabase
|
||||
.from('sales_orders')
|
||||
.select('*, customer:customers(*), items:sales_order_items(*)')
|
||||
.eq('id', orderId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (error) return failDb(error)
|
||||
if (!data) return fail('SALES_ORDER_NOT_FOUND')
|
||||
|
||||
const invoiced = await fetchInvoicedQuantities(supabase, [orderId])
|
||||
if (!invoiced.ok) return failDb(invoiced.dbError)
|
||||
|
||||
return { ok: true, order: decorate(maskEmbeddedCustomer(data as SalesOrder), invoiced.byItem) }
|
||||
}
|
||||
|
||||
export function decorate(order: SalesOrder, invoiced: Map<string, number>): SalesOrder {
|
||||
const items = withInvoicedQuantities(
|
||||
[...((order.items ?? []) as SalesOrderItem[])].sort((a, b) => a.sort_order - b.sort_order),
|
||||
invoiced,
|
||||
)
|
||||
return {
|
||||
...order,
|
||||
items,
|
||||
delivery_progress: deliveryProgress(items),
|
||||
invoicing_progress: invoicingProgress(items),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { SalesOrderItem, SalesOrderProgress } from '@/types'
|
||||
|
||||
/**
|
||||
* Quantity arithmetic on order lines.
|
||||
*
|
||||
* Postgres stores quantities as exact numeric; JavaScript does not. A
|
||||
* remaining quantity computed as `7.5 - 6.9` in doubles is 0.5999999999999996,
|
||||
* which the DB then refuses ("0.6 > remaining") or, if sent as-is, lands as
|
||||
* an invoice quantity the customer never ordered. Every derived quantity is
|
||||
* therefore rounded to QTY_DECIMALS before it is compared or persisted, and
|
||||
* comparisons use QTY_EPSILON so 0.1 + 0.2 style drift never decides a case
|
||||
* that the exact numeric would decide the other way.
|
||||
*/
|
||||
export const QTY_DECIMALS = 6
|
||||
const QTY_SCALE = 10 ** QTY_DECIMALS
|
||||
export const QTY_EPSILON = 1 / QTY_SCALE / 2
|
||||
|
||||
export function roundQty(n: number): number {
|
||||
if (n === 0) return 0
|
||||
return Math.round((n + Number.EPSILON) * QTY_SCALE) / QTY_SCALE
|
||||
}
|
||||
|
||||
/** a > b beyond quantity precision. */
|
||||
export function qtyGreater(a: number, b: number): boolean {
|
||||
return a - b > QTY_EPSILON
|
||||
}
|
||||
|
||||
/**
|
||||
* Derived per-axis progress of an order. Delivery and invoicing are
|
||||
* independent: an order is often partially delivered and partially
|
||||
* invoiced at the same time, which is why neither is a header status.
|
||||
*
|
||||
* Only product lines with a positive quantity count; text rows and zero
|
||||
* quantity rows carry no progress.
|
||||
*/
|
||||
function progressOf(items: SalesOrderItem[], pick: (item: SalesOrderItem) => number): SalesOrderProgress {
|
||||
const lines = items.filter((i) => i.line_type !== 'text' && i.quantity > 0)
|
||||
if (lines.length === 0) return 'none'
|
||||
let any = false
|
||||
let all = true
|
||||
for (const line of lines) {
|
||||
const done = pick(line)
|
||||
if (done > 0) any = true
|
||||
if (qtyGreater(line.quantity, done)) all = false
|
||||
}
|
||||
if (all) return 'full'
|
||||
return any ? 'partial' : 'none'
|
||||
}
|
||||
|
||||
export function deliveryProgress(items: SalesOrderItem[]): SalesOrderProgress {
|
||||
return progressOf(items, (i) => i.delivered_qty)
|
||||
}
|
||||
|
||||
export function invoicingProgress(items: SalesOrderItem[]): SalesOrderProgress {
|
||||
return progressOf(items, (i) => i.invoiced_qty ?? 0)
|
||||
}
|
||||
|
||||
/** Attach invoiced_qty / remaining_qty (both rounded to quantity precision) from the RPC rows. */
|
||||
export function withInvoicedQuantities(
|
||||
items: SalesOrderItem[],
|
||||
invoiced: Map<string, number>,
|
||||
): SalesOrderItem[] {
|
||||
return items.map((item) => {
|
||||
const invoicedQty = roundQty(invoiced.get(item.id) ?? 0)
|
||||
return {
|
||||
...item,
|
||||
invoiced_qty: invoicedQty,
|
||||
remaining_qty: Math.max(0, roundQty(item.quantity - invoicedQty)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { z } from 'zod'
|
||||
import type { SalesOrder } from '@/types'
|
||||
import type { RegisterSalesOrderDeliverySchema } from '@/lib/api/schemas'
|
||||
import { todayIsoStockholm } from '@/lib/dates/iso'
|
||||
import { loadSalesOrder } from './load'
|
||||
import { qtyGreater } from './progress'
|
||||
import { codeFromPgError, fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
export type RegisterDeliveryInput = z.infer<typeof RegisterSalesOrderDeliverySchema>
|
||||
|
||||
/**
|
||||
* Register delivered quantities on a confirmed (or already fully invoiced)
|
||||
* order. Quantities are CUMULATIVE (the new delivered_qty), so a retried
|
||||
* request is idempotent and the dialog can show the running total.
|
||||
*
|
||||
* Every line whose delivered quantity increases records the delivery date
|
||||
* as its own last_delivery_date; the header's last_delivery_date is the
|
||||
* latest across lines and is display-only. Invoices created afterwards take
|
||||
* the delivery date from the lines they cover (ML 17 kap 24 § p.7, and the
|
||||
* FX anchor per ML 8 kap 21-23 §), never from the header.
|
||||
*
|
||||
* There is no inventory: delivery is a fact the user records, nothing is
|
||||
* booked.
|
||||
*/
|
||||
export async function registerSalesOrderDelivery(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; orderId: string; input: RegisterDeliveryInput },
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { companyId, orderId, input } = params
|
||||
const current = await loadSalesOrder(supabase, companyId, orderId)
|
||||
if (!current.ok) return current
|
||||
const order = current.order
|
||||
if (order.status !== 'confirmed' && order.status !== 'completed') {
|
||||
return fail('SALES_ORDER_INVALID_STATE', { status: order.status, action: 'deliver' })
|
||||
}
|
||||
|
||||
const items = new Map((order.items ?? []).map((i) => [i.id, i]))
|
||||
const deliveryDate = input.delivery_date ?? todayIsoStockholm()
|
||||
const increased = new Set<string>()
|
||||
for (const line of input.lines) {
|
||||
const item = items.get(line.sales_order_item_id)
|
||||
if (!item) return fail('SALES_ORDER_LINE_NOT_FOUND', { sales_order_item_id: line.sales_order_item_id })
|
||||
if (item.line_type === 'text') continue
|
||||
if (qtyGreater(line.delivered_qty, item.quantity)) {
|
||||
return fail('SALES_ORDER_OVER_DELIVERED', {
|
||||
sales_order_item_id: item.id,
|
||||
quantity: item.quantity,
|
||||
delivered_qty: line.delivered_qty,
|
||||
})
|
||||
}
|
||||
if (qtyGreater(line.delivered_qty, item.delivered_qty)) increased.add(item.id)
|
||||
}
|
||||
|
||||
for (const line of input.lines) {
|
||||
const item = items.get(line.sales_order_item_id)
|
||||
if (!item || item.line_type === 'text') continue
|
||||
// Optimistic predicate on the quantity read above: two concurrent
|
||||
// cumulative registrations (6 and 8 from 0) must not let the later
|
||||
// write regress the earlier one.
|
||||
const { data: updated, error } = await supabase
|
||||
.from('sales_order_items')
|
||||
.update({
|
||||
delivered_qty: line.delivered_qty,
|
||||
last_delivery_date: increased.has(item.id) ? deliveryDate : undefined,
|
||||
})
|
||||
.eq('id', item.id)
|
||||
.eq('company_id', companyId)
|
||||
.eq('delivered_qty', item.delivered_qty)
|
||||
.select('id')
|
||||
if (error) {
|
||||
const code = codeFromPgError(error)
|
||||
return code ? fail(code) : failDb(error)
|
||||
}
|
||||
if (!updated || updated.length === 0) {
|
||||
return fail('SALES_ORDER_INVALID_STATE', {
|
||||
action: 'deliver',
|
||||
sales_order_item_id: item.id,
|
||||
reason: 'delivered quantity changed concurrently',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (increased.size > 0) {
|
||||
const { error } = await supabase
|
||||
.from('sales_orders')
|
||||
.update({ last_delivery_date: deliveryDate })
|
||||
.eq('id', orderId)
|
||||
.eq('company_id', companyId)
|
||||
if (error) return failDb(error)
|
||||
}
|
||||
|
||||
return loadSalesOrder(supabase, companyId, orderId)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { NextResponse } from 'next/server'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { ServiceFailure } from './result'
|
||||
|
||||
type MinimalLog = Parameters<typeof errorResponseFromCode>[1]
|
||||
|
||||
/** Map a service failure onto the canonical error envelope. */
|
||||
export function serviceFailureResponse(
|
||||
failure: ServiceFailure,
|
||||
log: MinimalLog,
|
||||
requestId?: string,
|
||||
): NextResponse {
|
||||
if ('dbError' in failure) return errorResponse(failure.dbError, log, { requestId })
|
||||
return errorResponseFromCode(failure.code, log, { requestId, details: failure.details })
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Shared result shape for the kundorder services. Mirrors
|
||||
* buildInvoiceWriteData(): a domain failure carries a structured-error code
|
||||
* (map via errorResponseFromCode) and an unexpected DB failure carries the
|
||||
* raw error (map via errorResponse), so route handlers and the MCP commit
|
||||
* executor translate identically.
|
||||
*/
|
||||
export type ServiceFailure =
|
||||
| { ok: false; code: string; details?: Record<string, unknown> }
|
||||
| { ok: false; dbError: unknown }
|
||||
|
||||
export type ServiceResult<T> = ({ ok: true } & T) | ServiceFailure
|
||||
|
||||
export function fail(code: string, details?: Record<string, unknown>): ServiceFailure {
|
||||
return details ? { ok: false, code, details } : { ok: false, code }
|
||||
}
|
||||
|
||||
export function failDb(dbError: unknown): ServiceFailure {
|
||||
return { ok: false, dbError }
|
||||
}
|
||||
|
||||
/**
|
||||
* The over-invoice, quantity-floor and delivered-within-ordered guards live
|
||||
* in Postgres (migration 20260902130000). They raise with a stable
|
||||
* SALES_ORDER_* prefix in the message so the service layer can map a race
|
||||
* that slipped past the pre-check onto the same structured code the
|
||||
* pre-check uses.
|
||||
*/
|
||||
export function codeFromPgError(error: unknown): string | null {
|
||||
const message =
|
||||
typeof error === 'object' && error !== null && 'message' in error
|
||||
? String((error as { message: unknown }).message)
|
||||
: ''
|
||||
if (message.includes('SALES_ORDER_OVER_INVOICED')) return 'SALES_ORDER_OVER_INVOICED'
|
||||
if (message.includes('SALES_ORDER_QUANTITY_BELOW_INVOICED')) return 'SALES_ORDER_QUANTITY_BELOW_INVOICED'
|
||||
if (message.includes('sales_order_items_delivered_within_ordered')) return 'SALES_ORDER_OVER_DELIVERED'
|
||||
if (message.includes('SALES_ORDER_ITEM_NOT_FOUND')) return 'SALES_ORDER_LINE_NOT_FOUND'
|
||||
// RESTRICT FKs: a line or order that a (possibly cancelled) invoice still
|
||||
// references cannot be removed; the derived invoiced quantity is 0 for a
|
||||
// cancelled invoice, so the service pre-checks let the delete through and
|
||||
// the FK is the authority.
|
||||
if (message.includes('invoice_items_sales_order_item_id_fkey')) return 'SALES_ORDER_LINE_LOCKED'
|
||||
if (message.includes('invoices_sales_order_id_fkey')) return 'SALES_ORDER_HAS_INVOICES'
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { SalesOrder, SalesOrderStatus } from '@/types'
|
||||
import { loadSalesOrder } from './load'
|
||||
import { hasOpenInvoices } from './write'
|
||||
import { fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
export type SalesOrderTransition = 'confirm' | 'cancel' | 'reopen'
|
||||
|
||||
/**
|
||||
* Header state machine. `completed` is never set here: it is maintained by
|
||||
* the DB (refresh_sales_order_completion) from the derived invoiced
|
||||
* quantities, and flips back to `confirmed` when a linked invoice is
|
||||
* cancelled or credited.
|
||||
*
|
||||
* draft -confirm-> confirmed
|
||||
* draft -cancel--> cancelled
|
||||
* confirmed -cancel--> cancelled (refused while linked invoices exist)
|
||||
* cancelled -reopen--> draft (refused while linked invoices exist)
|
||||
*/
|
||||
const ALLOWED: Record<SalesOrderTransition, { from: SalesOrderStatus[]; to: SalesOrderStatus }> = {
|
||||
confirm: { from: ['draft'], to: 'confirmed' },
|
||||
cancel: { from: ['draft', 'confirmed'], to: 'cancelled' },
|
||||
reopen: { from: ['cancelled'], to: 'draft' },
|
||||
}
|
||||
|
||||
export async function transitionSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; orderId: string; action: SalesOrderTransition },
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { companyId, orderId, action } = params
|
||||
const current = await loadSalesOrder(supabase, companyId, orderId)
|
||||
if (!current.ok) return current
|
||||
const order = current.order
|
||||
const rule = ALLOWED[action]
|
||||
if (!rule.from.includes(order.status)) {
|
||||
return fail('SALES_ORDER_INVALID_STATE', { status: order.status, action })
|
||||
}
|
||||
|
||||
if (action === 'cancel' || action === 'reopen') {
|
||||
const open = await hasOpenInvoices(supabase, companyId, orderId)
|
||||
if (!open.ok) return failDb(open.dbError)
|
||||
if (open.open) return fail('SALES_ORDER_HAS_INVOICES')
|
||||
}
|
||||
if (action === 'confirm' && !order.customer_id) return fail('SALES_ORDER_CUSTOMER_MISSING')
|
||||
|
||||
const now = new Date().toISOString()
|
||||
// Compare-and-set on the status read above so two concurrent transitions
|
||||
// cannot both win. Object literal on purpose (schema guard): undefined
|
||||
// keys are dropped by JSON serialisation, null keys clear the column.
|
||||
const { data: updated, error } = await supabase
|
||||
.from('sales_orders')
|
||||
.update({
|
||||
status: rule.to,
|
||||
confirmed_at: action === 'confirm' ? now : action === 'reopen' ? null : undefined,
|
||||
cancelled_at: action === 'cancel' ? now : action === 'reopen' ? null : undefined,
|
||||
completed_at: action === 'reopen' ? null : undefined,
|
||||
})
|
||||
.eq('id', orderId)
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', order.status)
|
||||
.select('id')
|
||||
if (error) return failDb(error)
|
||||
if (!updated || updated.length === 0) return fail('SALES_ORDER_INVALID_STATE', { status: order.status, action })
|
||||
|
||||
if (action === 'confirm') {
|
||||
// Hand-linked invoice lines may already cover the order: let the DB
|
||||
// evaluate completion right away instead of waiting for the next line
|
||||
// change. Best effort; the triggers keep it honest afterwards.
|
||||
await supabase.rpc('refresh_sales_order_completion', { p_order_id: orderId })
|
||||
}
|
||||
|
||||
return loadSalesOrder(supabase, companyId, orderId)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { z } from 'zod'
|
||||
import type { Customer, SalesOrder, SalesOrderItem } from '@/types'
|
||||
import type { CreateSalesOrderSchema, UpdateSalesOrderSchema } from '@/lib/api/schemas'
|
||||
import { normalizeSalesOrderLines, type SalesOrderLineRow } from './lines'
|
||||
import { todayIsoStockholm } from '@/lib/dates/iso'
|
||||
import { ensureSalesOrderNumber } from './ensure-order-number'
|
||||
import { fetchInvoicedQuantities, loadSalesOrder } from './load'
|
||||
import { qtyGreater } from './progress'
|
||||
import { codeFromPgError, fail, failDb, type ServiceResult } from './result'
|
||||
|
||||
export type CreateSalesOrderInput = z.infer<typeof CreateSalesOrderSchema>
|
||||
export type UpdateSalesOrderInput = z.infer<typeof UpdateSalesOrderSchema>
|
||||
|
||||
const EDITABLE_STATUSES = new Set(['draft', 'confirmed'])
|
||||
|
||||
async function loadCustomer(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
customerId: string,
|
||||
): Promise<{ ok: true; customer: Customer } | { ok: false; code: string; details?: Record<string, unknown> }> {
|
||||
const { data } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('id', customerId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle<Customer>()
|
||||
if (!data) return { ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId } }
|
||||
return { ok: true, customer: data }
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a draft order with its lines. Number allocated at creation (orders
|
||||
* are not verifikationer; gaps are irrelevant). A failed line insert rolls
|
||||
* the header back so no empty order survives. The customer facts the lines
|
||||
* were VAT-validated under are stored on the order; invoicing refuses when
|
||||
* they have changed since (see create-invoice-from-order.ts).
|
||||
*/
|
||||
export async function createSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; userId: string; input: CreateSalesOrderInput; sourceInvoiceId?: string | null },
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { companyId, userId, input } = params
|
||||
const customerRes = await loadCustomer(supabase, companyId, input.customer_id)
|
||||
if (!customerRes.ok) return fail(customerRes.code, customerRes.details)
|
||||
const customer = customerRes.customer
|
||||
|
||||
const lines = normalizeSalesOrderLines(input.items, customer)
|
||||
if (!lines.ok) return fail(lines.code, lines.details)
|
||||
|
||||
const { data: header, error: headerError } = await supabase
|
||||
.from('sales_orders')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
user_id: userId,
|
||||
customer_id: input.customer_id,
|
||||
customer_type_snapshot: customer.customer_type,
|
||||
customer_vat_validated_snapshot: customer.vat_number_validated ?? false,
|
||||
status: 'draft',
|
||||
source_invoice_id: params.sourceInvoiceId ?? null,
|
||||
order_date: input.order_date ?? todayIsoStockholm(),
|
||||
requested_delivery_date: input.requested_delivery_date ?? null,
|
||||
currency: input.currency ?? 'SEK',
|
||||
your_reference: input.your_reference ?? null,
|
||||
our_reference: input.our_reference ?? null,
|
||||
notes: input.notes ?? null,
|
||||
default_dimensions: input.default_dimensions ?? {},
|
||||
subtotal: lines.totals.subtotal,
|
||||
vat_amount: lines.totals.vat_amount,
|
||||
total: lines.totals.total,
|
||||
})
|
||||
.select('id')
|
||||
.single<{ id: string }>()
|
||||
if (headerError || !header) return failDb(headerError ?? new Error('sales order insert returned no row'))
|
||||
|
||||
const { error: itemsError } = await supabase
|
||||
.from('sales_order_items')
|
||||
.insert(lines.rows.map((row) => toInsertRow(row, companyId, header.id)))
|
||||
if (itemsError) {
|
||||
await supabase.from('sales_orders').delete().eq('id', header.id)
|
||||
return failDb(itemsError)
|
||||
}
|
||||
|
||||
// Non-fatal: an unnumbered order is still usable and gets numbered on the
|
||||
// next write (the RPC is idempotent).
|
||||
try {
|
||||
await ensureSalesOrderNumber(supabase, companyId, header.id)
|
||||
} catch {
|
||||
// reported through the order's null order_number
|
||||
}
|
||||
|
||||
return loadSalesOrder(supabase, companyId, header.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Full replace of header + lines while draft or confirmed.
|
||||
*
|
||||
* Lines are matched by id so a confirmed order keeps delivered/invoiced
|
||||
* history on the lines that survive. A line that has been delivered or
|
||||
* invoiced cannot be dropped (SALES_ORDER_LINE_LOCKED) and cannot go below
|
||||
* its delivered quantity (SALES_ORDER_OVER_DELIVERED); the DB trigger
|
||||
* additionally refuses lowering below the invoiced quantity. Once invoices
|
||||
* exist, customer and currency are frozen (SALES_ORDER_HAS_INVOICES): a
|
||||
* second partial invoice must go to the same customer in the same currency
|
||||
* as the first. Every save re-validates the lines against the customer's
|
||||
* current VAT rules and refreshes the stored snapshot.
|
||||
*/
|
||||
export async function updateSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
params: { companyId: string; orderId: string; input: UpdateSalesOrderInput },
|
||||
): Promise<ServiceResult<{ order: SalesOrder }>> {
|
||||
const { companyId, orderId, input } = params
|
||||
const current = await loadSalesOrder(supabase, companyId, orderId)
|
||||
if (!current.ok) return current
|
||||
const order = current.order
|
||||
if (!EDITABLE_STATUSES.has(order.status)) return fail('SALES_ORDER_NOT_EDITABLE', { status: order.status })
|
||||
|
||||
const customerChanged = input.customer_id !== undefined && input.customer_id !== order.customer_id
|
||||
const currencyChanged = input.currency !== undefined && input.currency !== order.currency
|
||||
if (customerChanged || currencyChanged) {
|
||||
const open = await hasOpenInvoices(supabase, companyId, orderId)
|
||||
if (!open.ok) return failDb(open.dbError)
|
||||
if (open.open) return fail('SALES_ORDER_HAS_INVOICES', { field: customerChanged ? 'customer_id' : 'currency' })
|
||||
}
|
||||
|
||||
const customerId = input.customer_id ?? order.customer_id
|
||||
if (!customerId) return fail('SALES_ORDER_CUSTOMER_MISSING')
|
||||
const customerRes = await loadCustomer(supabase, companyId, customerId)
|
||||
if (!customerRes.ok) return fail(customerRes.code, customerRes.details)
|
||||
const customer = customerRes.customer
|
||||
|
||||
const existing = new Map((order.items ?? []).map((i) => [i.id, i]))
|
||||
const lineInputs =
|
||||
input.items ??
|
||||
(order.items ?? []).map((i) => ({
|
||||
id: i.id,
|
||||
line_type: i.line_type,
|
||||
description: i.description,
|
||||
quantity: i.quantity,
|
||||
unit: i.unit,
|
||||
unit_price: i.unit_price,
|
||||
discount_percent: i.discount_percent,
|
||||
vat_rate: i.vat_rate,
|
||||
article_id: i.article_id,
|
||||
revenue_account: i.revenue_account,
|
||||
dimensions: i.dimensions,
|
||||
}))
|
||||
// Always re-validate against the customer's CURRENT VAT rules, even for a
|
||||
// header-only save: a stored rate the customer may no longer carry is
|
||||
// refused (INVOICE_CREATE_VAT_RULE_VIOLATION) and the snapshot below is
|
||||
// only refreshed once the lines pass.
|
||||
const lines = normalizeSalesOrderLines(lineInputs, customer)
|
||||
if (!lines.ok) return fail(lines.code, lines.details)
|
||||
const rows: SalesOrderLineRow[] | null = input.items ? lines.rows : null
|
||||
const totals = lines.totals
|
||||
|
||||
if (rows) {
|
||||
const incomingIds = new Set(rows.map((r) => r.id).filter((id): id is string => Boolean(id)))
|
||||
for (const id of incomingIds) {
|
||||
if (!existing.has(id)) return fail('SALES_ORDER_LINE_NOT_FOUND', { sales_order_item_id: id })
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (!row.id) continue
|
||||
const prev = existing.get(row.id) as SalesOrderItem
|
||||
if (qtyGreater(prev.delivered_qty, row.quantity)) {
|
||||
return fail('SALES_ORDER_OVER_DELIVERED', { sales_order_item_id: row.id, delivered_qty: prev.delivered_qty })
|
||||
}
|
||||
if (qtyGreater(prev.invoiced_qty ?? 0, row.quantity)) {
|
||||
return fail('SALES_ORDER_QUANTITY_BELOW_INVOICED', { sales_order_item_id: row.id, invoiced_qty: prev.invoiced_qty })
|
||||
}
|
||||
}
|
||||
for (const prev of existing.values()) {
|
||||
if (incomingIds.has(prev.id)) continue
|
||||
if (prev.delivered_qty > 0 || (prev.invoiced_qty ?? 0) > 0) {
|
||||
return fail('SALES_ORDER_LINE_LOCKED', { sales_order_item_id: prev.id })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Object literal on purpose (schema guard): undefined keys are dropped by
|
||||
// JSON serialisation, so an omitted field leaves the column untouched.
|
||||
const { error: headerError } = await supabase
|
||||
.from('sales_orders')
|
||||
.update({
|
||||
customer_id: input.customer_id,
|
||||
customer_type_snapshot: customer.customer_type,
|
||||
customer_vat_validated_snapshot: customer.vat_number_validated ?? false,
|
||||
order_date: input.order_date,
|
||||
requested_delivery_date: input.requested_delivery_date,
|
||||
currency: input.currency,
|
||||
your_reference: input.your_reference,
|
||||
our_reference: input.our_reference,
|
||||
notes: input.notes,
|
||||
default_dimensions: input.default_dimensions,
|
||||
subtotal: totals.subtotal,
|
||||
vat_amount: totals.vat_amount,
|
||||
total: totals.total,
|
||||
})
|
||||
.eq('id', orderId)
|
||||
.eq('company_id', companyId)
|
||||
if (headerError) return failDb(headerError)
|
||||
|
||||
if (rows) {
|
||||
const keep = new Set(rows.map((r) => r.id).filter(Boolean))
|
||||
const toDelete = [...existing.keys()].filter((id) => !keep.has(id))
|
||||
if (toDelete.length > 0) {
|
||||
const { error } = await supabase.from('sales_order_items').delete().in('id', toDelete).eq('company_id', companyId)
|
||||
if (error) return mapPg(error)
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (!row.id) continue
|
||||
const { error } = await supabase
|
||||
.from('sales_order_items')
|
||||
.update({
|
||||
sort_order: row.sort_order,
|
||||
line_type: row.line_type,
|
||||
description: row.description,
|
||||
quantity: row.quantity,
|
||||
unit: row.unit,
|
||||
unit_price: row.unit_price,
|
||||
discount_percent: row.discount_percent,
|
||||
vat_rate: row.vat_rate,
|
||||
line_total: row.line_total,
|
||||
article_id: row.article_id,
|
||||
revenue_account: row.revenue_account,
|
||||
dimensions: row.dimensions,
|
||||
})
|
||||
.eq('id', row.id)
|
||||
.eq('company_id', companyId)
|
||||
if (error) return mapPg(error)
|
||||
}
|
||||
const inserts = rows.filter((r) => !r.id).map((r) => toInsertRow(r, companyId, orderId))
|
||||
if (inserts.length > 0) {
|
||||
const { error } = await supabase.from('sales_order_items').insert(inserts)
|
||||
if (error) return mapPg(error)
|
||||
}
|
||||
}
|
||||
|
||||
return loadSalesOrder(supabase, companyId, orderId)
|
||||
}
|
||||
|
||||
function toInsertRow(row: SalesOrderLineRow, companyId: string, orderId: string) {
|
||||
return {
|
||||
company_id: companyId,
|
||||
sales_order_id: orderId,
|
||||
sort_order: row.sort_order,
|
||||
line_type: row.line_type,
|
||||
description: row.description,
|
||||
quantity: row.quantity,
|
||||
unit: row.unit,
|
||||
unit_price: row.unit_price,
|
||||
discount_percent: row.discount_percent,
|
||||
vat_rate: row.vat_rate,
|
||||
line_total: row.line_total,
|
||||
article_id: row.article_id,
|
||||
revenue_account: row.revenue_account,
|
||||
dimensions: row.dimensions,
|
||||
}
|
||||
}
|
||||
|
||||
function mapPg(error: unknown): ServiceResult<never> {
|
||||
const code = codeFromPgError(error)
|
||||
return code ? fail(code) : failDb(error)
|
||||
}
|
||||
|
||||
/** Progress-aware existence check reused by transitions and delivery. */
|
||||
export async function hasOpenInvoices(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
orderId: string,
|
||||
): Promise<{ ok: true; open: boolean } | { ok: false; dbError: unknown }> {
|
||||
const invoiced = await fetchInvoicedQuantities(supabase, [orderId])
|
||||
if (!invoiced.ok) return invoiced
|
||||
for (const qty of invoiced.byItem.values()) {
|
||||
if (qty > 0) return { ok: true, open: true }
|
||||
}
|
||||
// Zero-quantity links (e.g. a draft with a 0 line) still tie the invoice
|
||||
// to the order; count header links too.
|
||||
const { count, error } = await supabase
|
||||
.from('invoices')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('sales_order_id', orderId)
|
||||
.not('status', 'in', '("cancelled","credited")')
|
||||
if (error) return { ok: false, dbError: error }
|
||||
return { ok: true, open: (count ?? 0) > 0 }
|
||||
}
|
||||
Reference in New Issue
Block a user