feat(sales-orders): kundorder with partial delivery and partial invoicing (#2166)

* feat(sales-orders): kundorder with partial delivery and partial invoicing

Adds sales orders (kundorder) as their own non-ledger document between
agreement and invoice, for companies that deliver or invoice in parts.

Schema (20260902130000): sales_orders + sales_order_items with RLS via
user_company_ids(), OR-<n> numbering RPC (membership-gated, no anon
execute), company_settings.sales_orders_enabled UI gate, and back-links
invoices.sales_order_id / invoice_items.sales_order_item_id. The invoiced
quantity per order line is DERIVED from the linked invoice lines on
non-cancelled, non-credited invoices and enforced by a BEFORE trigger, so
no counter can drift and a credited invoice frees its quantity. Header
status is draft / confirmed / completed / cancelled; completion is kept
by DB triggers from the same derived quantity. Delivery and invoicing
progress are derived per line, never stored as status.

Service + API: lib/sales-orders (create/update with id-preserving line
replace, transitions with compare-and-set, cumulative delivery
registration, invoice-from-order through buildInvoiceWriteData so
booking stays in the engine, proforma -> order conversion), routes under
/api/sales-orders and /api/invoices/[id]/convert-to-order, structured
SALES_ORDER_* error codes, archive classification of the new tables.
The invoice editor round-trips sales_order_item_id so a draft edit
cannot drop the link; GET /api/invoices gains ?sales_order_id=.

UI: /sales-orders list, create/edit form reusing the invoice line
conventions, detail with deliver and create-invoice dialogs and linked
invoices; nav row behind the settings toggle; the webshop row is
relabelled webshop_orders; "Skapa order" on proformas.

MCP (20260902141000/141001): list/get reads plus four staged writes
(create, transition, register delivery, create invoice from order) whose
executors call the lib services; op types added to the pending
operations CHECK.

Tests: route tests for every route (401/400/404/happy), service unit
tests, executor and tool tests, and tests/pg/sales-orders.pg.test.ts
(16 cases, green on staging) covering RLS, numbering guards, the
over-invoice trigger incl. release on cancel/credit and cross-company
refusal, the quantity floor, and completion maintenance.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RQW7mXvbAPgjUHq7dSEamr

* fix(sales-orders): harden kundorder after skeptic and security review

Resolves every finding from the PR #2166 review pass in one batch.

Order link integrity: replaceInvoiceItems now refuses a line set that
drops an existing sales_order_item_id (INVOICE_UPDATE_DROPS_ORDER_LINK),
closing the MCP update_invoice header-only edit and the v1 PATCH path
that severed the link and freed the quantity for double invoicing. The
update_invoice re-fetch, gnubok_get_invoice and the v1 item projection
now carry sales_order_item_id so well-behaved clients round-trip it.

Quantity math: derived remaining/invoiced quantities are rounded to six
decimals and compared with an epsilon (roundQty, qtyGreater) so a float
remainder such as 0.5999999999999996 can neither refuse the final partial
invoice nor land as an invoice quantity; duplicate explicit picks are
summed before validation.

Leveransdatum: per-line last_delivery_date (migration 20260902160000);
an invoice takes the latest date over the lines it covers and only when
the covered quantity was delivered, never the header date and never for
an advance invoice (ML 17 kap 24 p.7, FX anchor per ML 8 kap 21-23).

VAT drift: the order stores the customer type and VAT-validation flag its
lines were priced under; invoicing refuses with
SALES_ORDER_CUSTOMER_VAT_CHANGED when they differ, and re-saving the
order re-validates the lines. Customer and currency are frozen once
invoices exist.

Tenant and role gates: composite FK (sales_order_id, company_id) ties a
line to its parent's company (Superagent P2); aa_enforce_company_writer_role
on both tables so a viewer cannot write through the browser client.

Proforma -> order refuses proformas with ROT/RUT, periodisering or
negative-quantity lines instead of dropping those fields. RESTRICT FK
errors on delete map to SALES_ORDER_LINE_LOCKED / SALES_ORDER_HAS_INVOICES.

Also: schema-guard literal payloads in lib/sales-orders (ceiling +2 with
reason), regenerated skills/accounted-api (sales_order_item_id on invoice
items), pg tests for the composite FK, the viewer gate and the new
columns, unit tests for every changed path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW

* fix(sales-orders): resolve CodeRabbit round on PR #2166

Quick wins from the review, all in one pass:

- replaceInvoiceItems fails closed when the invoice_items snapshot cannot
  be read (it is both the restore source and the input to the kundorder
  link guard); the guard branch is explicit in both PATCH routes.
- Cumulative delivery registration carries an optimistic predicate on the
  quantity it read, so two concurrent registrations cannot regress each
  other; DELETE of an order keeps its allowed status in the predicate and
  answers a conflict when zero rows match.
- Business dates (order date, delivery date, invoice date) default to the
  Europe/Stockholm calendar day (todayIsoStockholm), never UTC: the
  delivery date is also the Riksbanken rate anchor.
- The invoice-from-order executor treats an event emit failure as
  non-blocking: the draft already exists.
- sales_order_items are archived through their parent with the order
  currency denormalised, like invoice_items.
- Proforma "Skapa order" tolerates a 2xx without a parsable body; the
  settings toggle refreshes the server-rendered nav.
- List route doc states that q matches the order number (customer names
  are matched client-side).

Declined (out of scope for this PR): moving header + line writes and the
delivery loop into transactional RPCs (same PostgREST pattern as the
invoice PATCH path, tracked as a follow-up), the MCP approval handler's
error message shape (pre-existing code outside this change), and the
docstring-coverage warning (no repo convention).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW

* fix(sales-orders): move hardening migration off a colliding version; archive contract; ceiling

- 20260902160000_sales_orders_hardening.sql collided with main's
  20260902160000_parties_substrate.sql after the third sync; renamed to
  20260902180000 and made idempotent (DROP ... IF EXISTS before each
  ADD CONSTRAINT) so a preview branch that applied it under the old
  version replays it cleanly. Staging's schema_migrations row renamed.
- sales_order_items goes back to a direct archive dump: the coverage
  contract (tests/pg/full-archive-coverage.pg.test.ts) requires it for a
  table with its own company_id; the currency lives on the parent order
  one file over, joined by sales_order_id.
- Scanner ceiling re-baselined after merging main (parties phase 1): 397.
- v1 PATCH test queues a real empty invoice_items snapshot now that
  replaceInvoiceItems fails closed on an unreadable one.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW

* fix(sales-orders): drop the composite FK before its unique index on replay

The idempotent guard in 20260902180000_sales_orders_hardening.sql dropped
the unique (id, company_id) before the FK that depends on its index, so
the preview branch replay (which had applied the file under its former
version) failed with SQLSTATE 2BP01. Order swapped; replay verified on
staging.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-09-02 18:14:49 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent c40e63e3f7
commit c0818bb2d2
80 changed files with 11247 additions and 32 deletions
@@ -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()
})
})
+97
View File
@@ -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 }
}
+165
View File
@@ -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 } })
})
})
+201
View File
@@ -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' })
})
})
+71
View File
@@ -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' })
})
})
+512
View File
@@ -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])
})
})
+110
View File
@@ -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 }
}
+24
View File
@@ -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
}
+116
View File
@@ -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) },
}
}
+62
View File
@@ -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),
}
}
+71
View File
@@ -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)),
}
})
}
+94
View File
@@ -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)
}
+15
View File
@@ -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 })
}
+45
View File
@@ -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
}
+73
View File
@@ -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)
}
+287
View File
@@ -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 }
}