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
+3
View File
@@ -1496,6 +1496,9 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
[2026-09-02] parties phase 0, golden set stays out of git: the labelling sample is prod voucher text with person names (salary, expense claims) and the repo is public, so the draw SQL is versioned but the rows and labels live in gitignored dev_docs/parties/golden/.
[2026-09-02] parties substrate: customers and suppliers keep their tables and gain party_id; parties dedupe on normalised org number only, never on name at insert time. A name merge is a recorded human decision because the July measurement showed a majority of generic keys still map to one real vendor, so an automatic name merge would fuse unrelated suppliers.
[2026-09-02] MCP eager-auth flag (`auth=required`) on the claude.ai connector links instead of reverting lazy auth: claude.ai's two-step Add-custom-connector dialog probes the URL without credentials and pre-fills Authentication "None" when the lazy handshake answers 200, which blocks the sign-in later; per Anthropic's docs a 401 is the only answer it reads as OAuth. The flag lives in the URL, so the links we control (Settings, onboarding checklist, both docs pages, website) get OAuth detected while the bare URL keeps lazy auth for Claude Code, the plugin, Cursor and ChatGPT, and existing connector records stay untouched. Rejected: keying eager auth off `client=claude-connector` (documented as telemetry-only) and sniffing the probe's user agent (fragile, undocumented).
[2026-09-02] Kundorder (sales orders) ship as their own tables, not as invoices.document_type = 'order': orders have a delivery axis invoices lack, and an order row inside invoices would leak into every AR/VAT/reminder surface that filters on status instead of document_type. Invoiced quantity per order line is DERIVED from invoice_items.sales_order_item_id (sum over non-cancelled, non-credited invoices) and enforced by a BEFORE trigger, never stored: a counter cannot drift and a credited invoice frees the quantity by itself. Header status is four-state (draft, confirmed, completed, cancelled) with completion maintained by DB triggers; delivery and invoicing progress are derived per line. Offert is out of scope because no quote entity exists (only six dead QUOTE_* error codes); proforma -> order reuses the proforma -> invoice convert precedent. Nav key `sales_orders` is repointed to kundorder and the webshop row renamed `webshop_orders`.
[2026-09-02] Kundorder hardening after the skeptic pass (PR #2166): (a) an invoice created from an order refuses to invoice when the customer's type or VAT-number validation differs from the snapshot the order lines were priced under (SALES_ORDER_CUSTOMER_VAT_CHANGED); re-saving the order re-validates, chosen over silently re-deriving rates because a rate change is a pricing decision the user must see. (b) replaceInvoiceItems refuses a line set that drops an existing sales_order_item_id link (INVOICE_UPDATE_DROPS_ORDER_LINK) instead of guessing which new line maps to which order line; this closes the MCP update_invoice / v1 PATCH path that would otherwise free the quantity for double invoicing. (c) Derived quantities are rounded to 6 decimals (roundQty) and compared with an epsilon because Postgres numeric is exact and JS doubles are not. (d) Invoice delivery_date comes from per-line last_delivery_date over the covered lines, only when the covered quantity was delivered; an advance invoice gets none. (e) Kept ON DELETE RESTRICT on invoices.sales_order_id and invoice_items.sales_order_item_id despite the company-cascade ordering hazard (a company hard delete would hit the RESTRICT before invoices cascade): no shipped route hard-deletes companies, transactions.document_id already carries the same RESTRICT-under-cascade shape, and SET NULL would let an order deletion silently erase invoice provenance. (f) Kept sales_orders.user_id NOT NULL ON DELETE CASCADE, matching invoices; the prod user-deletion recipe repoints authorship first. (g) Proforma -> order refuses proformas with ROT/RUT, periodisering or negative-quantity lines rather than dropping those fields.
[2026-09-02] Kundorder MCP tools: only gnubok_list_sales_orders sits in the default tools/list catalog; gnubok_get_sales_order and the four staged writes (create, transition, register delivery, create invoice from order) are catalogVisibility 'search'. The payload-size ceiling (60K tokens, payload-size.bench.test.ts) had ~900 tokens of headroom and the six tools need ~4200 (~2500 trimmed); the test forbids bumping the ceiling and demoting unrelated reads is out of the feature's scope. Same footing as the mileage and skattekonto write families; promoting the writes later means demoting other reads first.
[2026-09-02] Agent-triggerable bank sync shipped (v1 POST /bank-connections/{id}/sync + MCP gnubok_sync_bank), lifting the 2026-09-01 deferral: Emil chose to close every open F2 item in one PR. The cost worry is bounded structurally instead of by policy: the window is never caller-controlled (gap-aware 7 to 90 days, same helper as the cron), a connection synced within 15 minutes answers BANK_SYNC_COOLDOWN with next_allowed_at (MCP returns it in-band as synced=false so agents read on instead of retrying), and failures are throttled per process by attempt time. The web Synka-nu route is left untouched rather than refactored onto the shared runner: it carries UI-only behaviour (caller-chosen days_back up to 365, SIE sweep stamping) and a regression there would hit every user for a code-sharing win.
[2026-09-02] Bank-sync cooldown is a durable lease column (bank_connections.sync_lease_until, migration 20260902150000) claimed with one conditional UPDATE, not a process-local attempt map: the security scan on PR #2165 showed the map is bypassed by a second serverless instance or a cold start, so two agent calls could each bill Enable Banking. A column add was chosen over reusing extension_data because PostgREST cannot express an atomic conditional upsert there; the nightly cron deliberately ignores the lease.
[2026-09-02] Grok links carry auth=required like the claude.ai link (#2159), decided from a live test: on the lazy URL Grok's connector dialog listed all 150+ tools and never opened the sign-in, so it reads the 200 probe as an authless server exactly as claude.ai does. The flag lives in one helper (mcpServerUrl / sideDoorServerUrl in lib/onboarding/checklist.ts) so the settings row, the onboarding side door and the deep link cannot drift; ChatGPT stays lazy because its developer mode honours the 401 on the first protected call.
+76 -1
View File
@@ -57,6 +57,7 @@ import {
Pencil,
Copy,
MoreHorizontal,
ClipboardList,
} from 'lucide-react'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
@@ -82,7 +83,7 @@ import {
} from '@/components/ui/dialog'
import type { Invoice, InvoiceItem, InvoiceStatus, InvoiceReminder, InvoiceDocumentType } from '@/types'
import type { InvoiceWithRelations } from '@/components/invoices/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { getErrorMessage as getUserErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { useBranding } from '@/lib/branding/brand-context'
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
@@ -211,6 +212,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
const [showSendDialog, setShowSendDialog] = useState(false)
const [sendDialogMode, setSendDialogMode] = useState<'email' | 'manual'>('email')
const [isConverting, setIsConverting] = useState(false)
const [isCreatingOrder, setIsCreatingOrder] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const [isUpdating, setIsUpdating] = useState(false)
const [isDownloading, setIsDownloading] = useState(false)
@@ -663,6 +665,55 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
setIsConverting(false)
}
// Proforma -> draft kundorder (sibling of convertToInvoice). The proforma is
// cancelled by the service; the user lands on the new order.
async function convertToOrder() {
if (!invoice) return
setIsCreatingOrder(true)
try {
const response = await fetch(`/api/invoices/${invoice.id}/convert-to-order`, {
method: 'POST',
})
const data = await response.json().catch(() => null)
if (!response.ok) {
toast({
title: t('create_order_failed_title'),
description: getUserErrorMessage(data, {
locale: locale as ErrorLocale,
statusCode: response.status,
}),
variant: 'destructive',
})
setIsCreatingOrder(false)
return
}
toast({
title: t('order_created_toast_title'),
description: data?.data?.order_number
? t('order_created_toast_description', { number: data.data.order_number })
: undefined,
})
const salesOrderId: string | undefined = data?.sales_order_id ?? data?.data?.id
if (salesOrderId) {
router.push(`/sales-orders/${salesOrderId}`)
} else {
// 2xx without a parsable body: the order exists, so refresh instead
// of turning the success into a failure toast.
router.refresh()
setIsCreatingOrder(false)
}
} catch (error) {
// Network failure (offline, aborted): the structured envelope never
// arrived, so map the raw error the same way the convert action does.
toast({
title: t('create_order_failed_title'),
description: getUserErrorMessage(error, { locale: locale as ErrorLocale }),
variant: 'destructive',
})
setIsCreatingOrder(false)
}
}
/**
* Fetch and save one specific document, then say truthfully which one it was.
*
@@ -1472,6 +1523,23 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
{t('convert_to_invoice')}
</Button>
)}
{isProforma && invoice.status !== 'cancelled' && (
<Button
variant="outline"
onClick={convertToOrder}
disabled={isCreatingOrder || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{isCreatingOrder ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : !canWrite ? (
<Lock className="mr-2 h-4 w-4" />
) : (
<ClipboardList className="mr-2 h-4 w-4" />
)}
{t('create_order')}
</Button>
)}
{isUnnumberedDraft && (
<Button
onClick={openFinalizeDialog}
@@ -1884,6 +1952,13 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
</Link>
</DefRow>
)}
{invoice.sales_order_id && (
<DefRow label={t('def_sales_order')}>
<Link href={`/sales-orders/${invoice.sales_order_id}`} className="hover:underline">
{t('open_sales_order')}
</Link>
</DefRow>
)}
</DetailSection>
</div>
+3
View File
@@ -400,6 +400,8 @@ export default async function DashboardLayout({
// mechanism as paysSalaries: UI gate only, never load-bearing for
// correctness (dimensions plan §2).
const dimensionsEnabled = settings?.dimensions_enabled ?? false
// Kundorder visibility: same UI-only gate as dimensionsEnabled.
const salesOrdersEnabled = settings?.sales_orders_enabled ?? false
// Körjournal visibility: the settings toggle is the normal way in, existing
// trips force the row on so already-created data stays reachable.
const hasMileage = (settings?.mileage_enabled ?? false) || hasMileageTrips
@@ -586,6 +588,7 @@ export default async function DashboardLayout({
entityType={entityType}
paysSalaries={paysSalaries}
dimensionsEnabled={dimensionsEnabled}
salesOrdersEnabled={salesOrdersEnabled}
hasWebshop={hasWebshop}
hasMileage={hasMileage}
isSandbox={isSandbox}
@@ -0,0 +1,77 @@
'use client'
import { use, useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { ArrowLeft } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
import SalesOrderForm from '@/components/sales-orders/SalesOrderForm'
import type { SalesOrder } from '@/types'
/**
* Edit an existing kundorder (draft or confirmed). Loads the order with its
* lines and hands it to the same form used for creation; line ids ride along
* so delivered/invoiced history survives the replace.
*/
export default function EditSalesOrderPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const t = useTranslations('sales_order_form')
const router = useRouter()
const { toast } = useToast()
const [order, setOrder] = useState<SalesOrder | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
let cancelled = false
fetch(`/api/sales-orders/${id}`)
.then(async (res) => {
if (!res.ok) throw new Error('load failed')
const { data } = await res.json()
return data as SalesOrder
})
.then((data) => {
if (cancelled) return
if (data.status !== 'draft' && data.status !== 'confirmed') {
toast({ title: t('not_editable'), variant: 'destructive' })
router.replace(`/sales-orders/${id}`)
return
}
setOrder(data)
})
.catch(() => {
if (cancelled) return
toast({ title: t('load_failed_title'), variant: 'destructive' })
router.replace('/sales-orders')
})
.finally(() => {
if (!cancelled) setIsLoading(false)
})
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
if (isLoading) return <DetailPageSkeleton />
if (!order) return null
return (
<div className="space-y-8">
<div>
<Link
href={`/sales-orders/${id}`}
className="mb-6 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
{t('back_to_order')}
</Link>
<h1 data-ph-mask="" className="font-display text-2xl leading-8 tracking-tight">
{t('title_edit', { number: order.order_number ?? '' })}
</h1>
</div>
<SalesOrderForm mode="edit" initial={order} />
</div>
)
}
+499
View File
@@ -0,0 +1,499 @@
'use client'
import { use, useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { ArrowLeft, Check, ClipboardList, Lock, Pencil, ReceiptText, Truck } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { DetailSection, DefRow, DefEmpty } from '@/components/ui/detail-section'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
import { useToast } from '@/components/ui/use-toast'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import RegisterDeliveryDialog from '@/components/sales-orders/RegisterDeliveryDialog'
import CreateInvoiceDialog from '@/components/sales-orders/CreateInvoiceDialog'
import {
DELIVERY_LABEL_KEY,
INVOICING_LABEL_KEY,
STATUS_BADGE_VARIANT,
STATUS_LABEL_KEY,
formatQty,
} from '@/components/sales-orders/labels'
import type { Invoice, InvoiceStatus, SalesOrder, SalesOrderItem } from '@/types'
type Transition = 'confirm' | 'cancel' | 'reopen'
const TRANSITION_COPY: Record<
Transition,
{ title: string; description: string; label: string; toast: string; destructive: boolean }
> = {
confirm: {
title: 'confirm_dialog_title',
description: 'confirm_dialog_description',
label: 'confirm_dialog_label',
toast: 'confirmed_toast',
destructive: false,
},
cancel: {
title: 'cancel_dialog_title',
description: 'cancel_dialog_description',
label: 'cancel_dialog_label',
toast: 'cancelled_toast',
destructive: true,
},
reopen: {
title: 'reopen_dialog_title',
description: 'reopen_dialog_description',
label: 'reopen_dialog_label',
toast: 'reopened_toast',
destructive: false,
},
}
function isTextLine(item: SalesOrderItem): boolean {
return item.line_type === 'text'
}
const INVOICE_STATUS_LABEL_KEY: Record<InvoiceStatus, string> = {
draft: 'invoice_status_draft',
sent: 'invoice_status_sent',
paid: 'invoice_status_paid',
partially_paid: 'invoice_status_partially_paid',
overdue: 'invoice_status_overdue',
cancelled: 'invoice_status_cancelled',
credited: 'invoice_status_credited',
}
// Chips mark exceptions: a draft, an overdue or a cancelled invoice deviates
// from the paid-in-time path; the rest render as muted text.
const INVOICE_STATUS_BADGE: Partial<Record<InvoiceStatus, 'outline' | 'warning' | 'destructive'>> = {
draft: 'outline',
overdue: 'warning',
cancelled: 'destructive',
}
export default function SalesOrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const t = useTranslations('sales_order_detail')
const tList = useTranslations('sales_orders')
const tCommon = useTranslations('common')
const errorLocale = useLocale() as ErrorLocale
const router = useRouter()
const { toast } = useToast()
const { canWrite } = useCanWrite()
const { dialogProps: deleteDialogProps, confirm: confirmDelete } = useDestructiveConfirm()
const [order, setOrder] = useState<SalesOrder | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [pendingTransition, setPendingTransition] = useState<Transition | null>(null)
const [isDeliveryOpen, setIsDeliveryOpen] = useState(false)
const [isInvoiceOpen, setIsInvoiceOpen] = useState(false)
// Invoices created from this order (GET /api/invoices?sales_order_id=).
const [invoices, setInvoices] = useState<Invoice[]>([])
const fetchOrder = useCallback(async () => {
try {
const res = await fetch(`/api/sales-orders/${id}`)
if (!res.ok) throw new Error('load failed')
const { data } = await res.json()
setOrder(data as SalesOrder)
} catch {
toast({ title: t('load_failed_title'), variant: 'destructive' })
router.push('/sales-orders')
} finally {
setIsLoading(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
const fetchInvoices = useCallback(async () => {
try {
const res = await fetch(`/api/invoices?sales_order_id=${encodeURIComponent(id)}&limit=200`)
const json = await res.json().catch(() => null)
if (!res.ok) throw Object.assign(new Error('load failed'), { body: json, status: res.status })
setInvoices((json?.data ?? []) as Invoice[])
} catch (err) {
const e = err as { body?: unknown; status?: number }
toast({
title: t('invoices_load_failed_title'),
description: getErrorMessage(e.body ?? err, { locale: errorLocale, statusCode: e.status }),
variant: 'destructive',
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
useEffect(() => {
void fetchOrder()
void fetchInvoices()
}, [fetchOrder, fetchInvoices])
async function runTransition(action: Transition) {
if (!order) return
const res = await fetch(`/api/sales-orders/${order.id}/transition`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action }),
})
const json = await res.json().catch(() => null)
if (!res.ok) {
toast({
title: t('transition_failed_title'),
description: getErrorMessage(json, { locale: errorLocale, statusCode: res.status }),
variant: 'destructive',
})
return
}
setOrder(json.data as SalesOrder)
toast({ title: t(TRANSITION_COPY[action].toast) })
setPendingTransition(null)
}
async function handleDelete() {
if (!order) return
const number = order.order_number ?? ''
await confirmDelete(
{
title: t('delete_confirm_title', { number }),
description: t('delete_confirm_description'),
confirmLabel: t('delete_confirm_label'),
variant: 'destructive',
},
async () => {
const res = await fetch(`/api/sales-orders/${order.id}`, { method: 'DELETE' })
const json = await res.json().catch(() => null)
if (!res.ok) {
toast({
title: t('delete_failed_title'),
description: getErrorMessage(json, { locale: errorLocale, statusCode: res.status }),
variant: 'destructive',
})
throw new Error('delete failed')
}
toast({ title: t('deleted_toast') })
router.push('/sales-orders')
},
)
}
if (isLoading) return <DetailPageSkeleton />
if (!order) return null
const status = order.status
const number = order.order_number ?? ''
const badgeVariant = STATUS_BADGE_VARIANT[status]
const canEdit = status === 'draft' || status === 'confirmed'
const canConfirm = status === 'draft'
const canDeliver = status === 'confirmed' || status === 'completed'
const canInvoice = status === 'confirmed'
const canCancel = status === 'draft' || status === 'confirmed'
const canReopen = status === 'cancelled'
const canDelete = status === 'draft' || status === 'cancelled'
const items = [...(order.items ?? [])].sort((a, b) => a.sort_order - b.sort_order)
const lockTitle = !canWrite ? t('viewer_disabled_tooltip') : undefined
const pending = pendingTransition ? TRANSITION_COPY[pendingTransition] : null
return (
<div className="space-y-8 stagger-enter">
<div>
<Link
href="/sales-orders"
className="mb-6 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
{t('back')}
</Link>
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-3">
<h1 data-ph-mask="" className="font-display text-2xl leading-8 tracking-tight">
{number ? t('title', { number }) : t('title_unnumbered')}
</h1>
{badgeVariant ? (
<Badge variant={badgeVariant}>{tList(STATUS_LABEL_KEY[status])}</Badge>
) : (
<span className="text-sm text-muted-foreground">{tList(STATUS_LABEL_KEY[status])}</span>
)}
</div>
<p className="mt-1 text-sm text-muted-foreground" data-ph-mask="">
{[order.customer?.name, formatDate(order.order_date)].filter(Boolean).join(' · ')}
</p>
</div>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
{canEdit && (
<Button variant="outline" asChild={canWrite} disabled={!canWrite} title={lockTitle}>
{canWrite ? (
<Link href={`/sales-orders/${order.id}/edit`}>
<Pencil className="mr-2 h-4 w-4" />
{t('action_edit')}
</Link>
) : (
<span>
<Lock className="mr-2 h-4 w-4" />
{t('action_edit')}
</span>
)}
</Button>
)}
{canDeliver && (
<Button
variant={canInvoice ? 'outline' : 'default'}
onClick={() => setIsDeliveryOpen(true)}
disabled={!canWrite}
title={lockTitle}
>
{canWrite ? <Truck className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{t('action_register_delivery')}
</Button>
)}
{canInvoice && (
<Button onClick={() => setIsInvoiceOpen(true)} disabled={!canWrite} title={lockTitle}>
{canWrite ? <ReceiptText className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{t('action_create_invoice')}
</Button>
)}
{canConfirm && (
<Button onClick={() => setPendingTransition('confirm')} disabled={!canWrite} title={lockTitle}>
{canWrite ? <Check className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{t('action_confirm')}
</Button>
)}
{canReopen && (
<Button onClick={() => setPendingTransition('reopen')} disabled={!canWrite} title={lockTitle}>
{canWrite ? <ClipboardList className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
{t('action_reopen')}
</Button>
)}
</div>
</div>
</div>
<DetailSection kicker={t('section_details')}>
<DefRow label={t('def_customer')}>
{order.customer ? (
<Link href={`/customers/${order.customer.id}`} className="hover:underline">
{order.customer.name}
</Link>
) : (
<DefEmpty />
)}
</DefRow>
<DefRow label={t('def_order_date')}>
<span className="tabular-nums">{formatDate(order.order_date)}</span>
</DefRow>
<DefRow label={t('def_requested_delivery_date')}>
{order.requested_delivery_date ? (
<span className="tabular-nums">{formatDate(order.requested_delivery_date)}</span>
) : (
<DefEmpty />
)}
</DefRow>
{order.last_delivery_date && (
<DefRow label={t('def_last_delivery_date')}>
<span className="tabular-nums">{formatDate(order.last_delivery_date)}</span>
</DefRow>
)}
<DefRow label={t('def_delivery')}>
<span className="text-muted-foreground">
{tList(DELIVERY_LABEL_KEY[order.delivery_progress ?? 'none'])}
</span>
</DefRow>
<DefRow label={t('def_invoicing')}>
<span className="text-muted-foreground">
{tList(INVOICING_LABEL_KEY[order.invoicing_progress ?? 'none'])}
</span>
</DefRow>
<DefRow label={t('def_currency')}>{order.currency}</DefRow>
{order.your_reference && <DefRow label={t('def_your_reference')}>{order.your_reference}</DefRow>}
{order.our_reference && <DefRow label={t('def_our_reference')}>{order.our_reference}</DefRow>}
{order.source_invoice_id && (
<DefRow label={t('def_source_invoice')}>
<Link href={`/invoices/${order.source_invoice_id}`} className="hover:underline">
{t('source_proforma')}
</Link>
</DefRow>
)}
{order.notes && (
<DefRow label={t('def_notes')}>
<span className="whitespace-pre-wrap">{order.notes}</span>
</DefRow>
)}
</DetailSection>
<DetailSection kicker={t('section_lines')}>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'pl-0')}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_quantity')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_delivered')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_invoiced')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_remaining')}</th>
<th className={cn(TH_CLASS, 'hidden text-right md:table-cell')}>{t('th_unit_price')}</th>
<th className={cn(TH_CLASS, 'hidden text-right md:table-cell')}>{t('th_discount')}</th>
<th className={cn(TH_CLASS, 'hidden text-right md:table-cell')}>{t('th_vat')}</th>
<th className={cn(TH_CLASS, 'pr-0 text-right')}>{t('th_amount')}</th>
</tr>
</thead>
<tbody>
{items.map((item) =>
isTextLine(item) ? (
<tr key={item.id}>
<td colSpan={9} className={cn(TD_CLASS, 'pl-0 pr-0 text-muted-foreground')}>
{item.description || ' '}
</td>
</tr>
) : (
<tr key={item.id}>
<td className={cn(TD_CLASS, 'pl-0')}>{item.description}</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
{formatQty(item.quantity)} {item.unit}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums text-muted-foreground')}>
{formatQty(item.delivered_qty)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums text-muted-foreground')}>
{formatQty(item.invoiced_qty ?? 0)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
{formatQty(item.remaining_qty ?? Math.max(0, item.quantity - (item.invoiced_qty ?? 0)))}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums md:table-cell')}>
{formatCurrency(item.unit_price, order.currency)}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums text-muted-foreground md:table-cell')}>
{item.discount_percent > 0 ? `${formatQty(item.discount_percent)} %` : ''}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums text-muted-foreground md:table-cell')}>
{formatQty(item.vat_rate)} %
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap pr-0 text-right tabular-nums')}>
{formatCurrency(item.line_total, order.currency)}
</td>
</tr>
),
)}
</tbody>
</table>
</div>
<div className="mt-6 ml-auto w-full max-w-xs space-y-1 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">{t('subtotal')}</span>
<span className="tabular-nums">{formatCurrency(order.subtotal, order.currency)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('vat')}</span>
<span className="tabular-nums">{formatCurrency(order.vat_amount, order.currency)}</span>
</div>
<div className="flex justify-between border-t border-border pt-2">
<span>{t('total')}</span>
<span className="font-display text-xl tabular-nums">{formatCurrency(order.total, order.currency)}</span>
</div>
</div>
</DetailSection>
{invoices.length > 0 && (
<DetailSection kicker={t('section_invoices')}>
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'pl-0')}>{t('th_invoice_number')}</th>
<th className={TH_CLASS}>{t('th_invoice_status')}</th>
<th className={cn(TH_CLASS, 'pr-0 text-right')}>{t('th_invoice_total')}</th>
</tr>
</thead>
<tbody>
{invoices.map((invoice) => {
const variant = INVOICE_STATUS_BADGE[invoice.status]
const label = t(INVOICE_STATUS_LABEL_KEY[invoice.status] ?? 'invoice_status_draft')
return (
<tr key={invoice.id} className="transition-colors duration-150 hover:bg-secondary/35">
<td className={cn(TD_CLASS, 'pl-0 tabular-nums')}>
<Link href={`/invoices/${invoice.id}`} className="hover:underline">
{invoice.invoice_number ?? t('invoice_draft_label')}
</Link>
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>
{variant ? (
<Badge variant={variant} className="font-normal">{label}</Badge>
) : (
<span className="text-muted-foreground">{label}</span>
)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap pr-0 text-right tabular-nums')}>
{formatCurrency(invoice.total, invoice.currency)}
</td>
</tr>
)
})}
</tbody>
</table>
</DetailSection>
)}
{(canCancel || canDelete) && canWrite && (
<div className="flex flex-wrap items-center justify-end gap-1">
{canCancel && (
<Button
variant="ghost"
size="sm"
onClick={() => setPendingTransition('cancel')}
className="min-h-10 text-muted-foreground hover:text-destructive"
>
{t('action_cancel')}
</Button>
)}
{canDelete && (
<Button
variant="ghost"
size="sm"
onClick={handleDelete}
className="min-h-10 text-muted-foreground hover:text-destructive"
>
{t('action_delete')}
</Button>
)}
</div>
)}
{pending && pendingTransition && (
<ConfirmDialog
open
onOpenChange={(open) => !open && setPendingTransition(null)}
title={t(pending.title, { number })}
description={t(pending.description)}
confirmLabel={t(pending.label)}
cancelLabel={tCommon('cancel')}
destructive={pending.destructive}
onConfirm={() => runTransition(pendingTransition)}
/>
)}
<RegisterDeliveryDialog
open={isDeliveryOpen}
onOpenChange={setIsDeliveryOpen}
order={order}
onRegistered={setOrder}
/>
<CreateInvoiceDialog
open={isInvoiceOpen}
onOpenChange={setIsInvoiceOpen}
order={order}
onCreated={(next) => {
setOrder(next)
void fetchInvoices()
}}
/>
<DestructiveConfirmDialog {...deleteDialogProps} />
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
'use client'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { ArrowLeft } from 'lucide-react'
import SalesOrderForm from '@/components/sales-orders/SalesOrderForm'
export default function NewSalesOrderPage() {
const t = useTranslations('sales_order_form')
return (
<div className="space-y-8">
<div>
<Link
href="/sales-orders"
className="mb-6 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
{t('back')}
</Link>
<h1 className="font-display text-2xl leading-8 tracking-tight">{t('title_create')}</h1>
</div>
<SalesOrderForm mode="create" />
</div>
)
}
+283
View File
@@ -0,0 +1,283 @@
'use client'
import { Suspense, useCallback, useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { ClipboardList, Lock, Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { EmptyState } from '@/components/ui/empty-state'
import { ToolbarSearch } from '@/components/ui/toolbar-search'
import { ContextPicker } from '@/components/common/ContextPicker'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { useToast } from '@/components/ui/use-toast'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import {
DELIVERY_LABEL_KEY,
INVOICING_LABEL_KEY,
STATUS_BADGE_VARIANT,
STATUS_LABEL_KEY,
} from '@/components/sales-orders/labels'
import type { SalesOrder, SalesOrderStatus } from '@/types'
const ALL = 'all'
const STATUSES: SalesOrderStatus[] = ['draft', 'confirmed', 'completed', 'cancelled']
const INITIAL_VISIBLE_ROWS = 100
function isStatus(value: string | null): value is SalesOrderStatus {
return !!value && (STATUSES as string[]).includes(value)
}
function SalesOrdersPageInner() {
const t = useTranslations('sales_orders')
const tCommon = useTranslations('common')
const errorLocale = useLocale() as ErrorLocale
const { canWrite } = useCanWrite()
const { toast } = useToast()
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const statusParam = searchParams.get('status')
const statusFilter: SalesOrderStatus | typeof ALL = isStatus(statusParam) ? statusParam : ALL
const [orders, setOrders] = useState<SalesOrder[]>([])
const [isLoading, setIsLoading] = useState(true)
const [searchTerm, setSearchTerm] = useState('')
const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE_ROWS)
const updateStatus = useCallback(
(next: string) => {
setVisibleCount(INITIAL_VISIBLE_ROWS)
const params = new URLSearchParams(searchParams.toString())
if (next === ALL) params.delete('status')
else params.set('status', next)
const query = params.toString()
router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false })
},
[searchParams, router, pathname],
)
useEffect(() => {
let cancelled = false
setIsLoading(true)
const query = statusFilter === ALL ? '' : `?status=${statusFilter}`
fetch(`/api/sales-orders${query}`)
.then(async (res) => {
const json = await res.json().catch(() => null)
if (!res.ok) throw Object.assign(new Error('load failed'), { body: json, status: res.status })
return (json?.data ?? []) as SalesOrder[]
})
.then((data) => {
if (!cancelled) setOrders(data)
})
.catch((err) => {
if (cancelled) return
toast({
title: t('load_failed_title'),
description: getErrorMessage(err.body ?? err, { locale: errorLocale, statusCode: err.status }),
variant: 'destructive',
})
})
.finally(() => {
if (!cancelled) setIsLoading(false)
})
return () => {
cancelled = true
}
// toast/t are stable enough; the fetch keys on the status filter only.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [statusFilter])
const filtered = useMemo(() => {
const term = searchTerm.trim().toLowerCase()
if (!term) return orders
return orders.filter(
(o) =>
(o.order_number ?? '').toLowerCase().includes(term) ||
(o.customer?.name ?? '').toLowerCase().includes(term),
)
}, [orders, searchTerm])
const visible = filtered.slice(0, visibleCount)
const statusItems = [
{ id: ALL, label: t('status_all') },
...STATUSES.map((s) => ({ id: s, label: t(STATUS_LABEL_KEY[s]) })),
]
return (
<div className="space-y-8">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h1 className="font-display text-2xl leading-8 tracking-tight">{t('title')}</h1>
<Button asChild={canWrite} disabled={!canWrite} title={!canWrite ? t('viewer_disabled_tooltip') : undefined}>
{canWrite ? (
<Link href="/sales-orders/new">
<Plus className="mr-2 h-4 w-4" />
{t('new_order')}
</Link>
) : (
<span>
<Lock className="mr-2 h-4 w-4" />
{t('new_order')}
</span>
)}
</Button>
</div>
<div className="flex flex-wrap items-center gap-2">
<ContextPicker
value={statusFilter}
onChange={updateStatus}
ariaLabel={t('status_picker_aria')}
triggerLabel={statusFilter === ALL ? t('status_all') : t(STATUS_LABEL_KEY[statusFilter])}
items={statusItems}
/>
<ToolbarSearch
containerClassName="min-w-[190px]"
placeholder={t('search_placeholder')}
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value)
setVisibleCount(INITIAL_VISIBLE_ROWS)
}}
/>
</div>
{isLoading ? (
<div className="space-y-3">
{[1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
) : filtered.length === 0 ? (
searchTerm ? (
<EmptyState
icon={ClipboardList}
title={t('no_search_results_title')}
description={<span data-ph-mask="">{t('no_search_results_description', { term: searchTerm })}</span>}
/>
) : statusFilter !== ALL ? (
<EmptyState
icon={ClipboardList}
title={t('no_search_results_title')}
description={t('no_status_results_description')}
/>
) : (
<EmptyState
icon={ClipboardList}
title={t('empty_title')}
description={t('empty_description')}
actionLabel={canWrite ? t('empty_action') : undefined}
actionHref={canWrite ? '/sales-orders/new' : undefined}
/>
)
) : (
<>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={TH_CLASS}>{t('col_number')}</th>
<th className={cn(TH_CLASS, 'w-full')}>{t('col_customer')}</th>
<th className={cn(TH_CLASS, 'hidden md:table-cell')}>{t('col_date')}</th>
<th className={TH_CLASS}>{t('col_status')}</th>
<th className={cn(TH_CLASS, 'hidden lg:table-cell')}>{t('col_delivery')}</th>
<th className={cn(TH_CLASS, 'hidden lg:table-cell')}>{t('col_invoicing')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('col_total')}</th>
</tr>
</thead>
<tbody className="stagger-enter">
{visible.map((order) => {
const badgeVariant = STATUS_BADGE_VARIANT[order.status]
return (
<tr
key={order.id}
className="group cursor-pointer transition-colors duration-150 hover:bg-secondary/35"
onClick={() => router.push(`/sales-orders/${order.id}`)}
>
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>
{order.order_number || '-'}
</td>
<td className={cn(TD_CLASS, 'max-w-0 w-full')}>
<Link
href={`/sales-orders/${order.id}`}
className="block truncate hover:underline"
onClick={(e) => e.stopPropagation()}
>
{order.customer?.name || '-'}
</Link>
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap tabular-nums text-muted-foreground md:table-cell')}>
{formatDate(order.order_date)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>
{badgeVariant ? (
<Badge variant={badgeVariant} className="font-normal">
{t(STATUS_LABEL_KEY[order.status])}
</Badge>
) : (
<span className="text-muted-foreground">{t(STATUS_LABEL_KEY[order.status])}</span>
)}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-muted-foreground lg:table-cell')}>
{t(DELIVERY_LABEL_KEY[order.delivery_progress ?? 'none'])}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-muted-foreground lg:table-cell')}>
{t(INVOICING_LABEL_KEY[order.invoicing_progress ?? 'none'])}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
{formatCurrency(order.total, order.currency)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
<p className="px-1 text-xs text-muted-foreground tabular-nums">
{t('count_footer', { count: filtered.length })}
</p>
{visibleCount < filtered.length && (
<div className="flex justify-center">
<Button
type="button"
variant="outline"
onClick={() => setVisibleCount((count) => count + INITIAL_VISIBLE_ROWS)}
>
{tCommon('load_more')}
</Button>
</div>
)}
</>
)}
</div>
)
}
export default function SalesOrdersPage() {
return (
<Suspense
fallback={
<div className="space-y-8">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<Skeleton className="h-9 w-40" />
<Skeleton className="h-10 w-32" />
</div>
<div className="space-y-3">
{[1, 2, 3, 4].map((i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
</div>
}
>
<SalesOrdersPageInner />
</Suspense>
)
}
@@ -175,6 +175,29 @@ describe('PATCH /api/invoices/[id]', () => {
expect(emitSpy).not.toHaveBeenCalled()
})
it('returns 409 INVOICE_UPDATE_DROPS_ORDER_LINK when the new lines drop a kundorder link', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
error: null,
}) // existing
enqueue({ data: makeCustomer({ id: 'customer-1', customer_type: 'swedish_business' }), error: null }) // customer
enqueue({ data: { vat_registered: true }, error: null }) // settings
enqueue({ data: [{ id: 'inv-1' }], error: null }) // header update matched
enqueue({
// snapshot: the stored line is linked to an order line; VALID_BODY carries no sales_order_item_id
data: [{ id: 'item-old-1', invoice_id: 'inv-1', sales_order_item_id: 'd1000000-0000-4000-8000-000000000001' }],
error: null,
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch('inv-1'))
expect(status).toBe(409)
expect(body.error.code).toBe('INVOICE_UPDATE_DROPS_ORDER_LINK')
// The guard fires before the delete: from() was called for existing,
// customer, settings, update and snapshot only, never for delete/insert.
expect(mockSupabase.from).toHaveBeenCalledTimes(5)
})
it('returns 409 when the draft is sent/finalized concurrently (0-row update)', async () => {
enqueue({
data: { id: 'inv-1', status: 'draft', invoice_number: null, journal_entry_id: null, is_self_billed: false },
@@ -0,0 +1,330 @@
/**
* POST /api/invoices/[id]/convert-to-order: proforma -> draft kundorder.
*
* Queue order: invoices select (proforma + items), sales_orders head count
* (already converted?), then createSalesOrder (customers select,
* sales_orders insert, sales_order_items insert, generate number rpc,
* sales_orders select, invoiced rpc), then the invoices compare-and-set
* update that marks the proforma cancelled.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
makeInvoice,
} from '@/tests/helpers'
import { IDS, makeOrderCustomer, makeSalesOrder } from '@/lib/sales-orders/__tests__/fixtures'
import type { SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../route'
const params = createMockRouteParams({ id: IDS.invoice })
function post() {
return POST(createMockRequest(`/api/invoices/${IDS.invoice}/convert-to-order`, { method: 'POST' }), params)
}
function makeProforma(overrides: Record<string, unknown> = {}) {
return {
...makeInvoice({
id: IDS.invoice,
customer_id: IDS.customer,
document_type: 'proforma',
status: 'sent',
invoice_number: 'P-2026001',
your_reference: 'Anna',
notes: 'Enligt offert',
}),
items: [
{
id: 'e2000000-0000-4000-8000-000000000002',
sort_order: 1,
line_type: 'text',
description: 'Tack för förtroendet',
quantity: 0,
unit: null,
unit_price: 0,
vat_rate: 0,
},
{
id: 'e2000000-0000-4000-8000-000000000001',
sort_order: 0,
line_type: 'product',
description: 'Konsulttimme',
quantity: 10,
unit: 'h',
unit_price: 100,
discount_percent: null,
vat_rate: 25,
article_id: null,
revenue_account: '3011',
dimensions: { project: 'P1' },
},
] as Record<string, unknown>[],
...overrides,
}
}
describe('POST /api/invoices/[id]/convert-to-order', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const { status } = await parseJsonResponse(await post())
expect(status).toBe(401)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const { status } = await parseJsonResponse(await post())
expect(status).toBe(403)
})
it('returns 404 when the invoice is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(404)
expect(body.error.code).toBe('INVOICE_NOT_FOUND')
})
it('returns 400 SALES_ORDER_SOURCE_NOT_PROFORMA for a real invoice', async () => {
enqueue({ data: makeProforma({ document_type: 'invoice' }) })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(400)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_NOT_PROFORMA')
expect(findCall('sales_orders', 'insert')).toBeUndefined()
})
it('returns 409 SALES_ORDER_SOURCE_ALREADY_CONVERTED for a cancelled proforma', async () => {
enqueue({ data: makeProforma({ status: 'cancelled' }) })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
})
it('returns 409 SALES_ORDER_SOURCE_ALREADY_CONVERTED when an order already points at the proforma', async () => {
enqueue({ data: makeProforma() })
enqueue({ data: null, count: 1 })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
expect(findCalls('sales_orders', 'eq')).toContainEqual(['source_invoice_id', IDS.invoice])
})
it('returns 409 SALES_ORDER_CUSTOMER_MISSING for a proforma without customer', async () => {
enqueue({ data: makeProforma({ customer_id: null }) })
enqueue({ data: null, count: 0 })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_CUSTOMER_MISSING')
})
it('returns 400 SALES_ORDER_SOURCE_UNSUPPORTED_LINES for a ROT line (order lines carry no skattereduktion)', async () => {
const proforma = makeProforma()
proforma.items[1] = {
...proforma.items[1],
deduction_type: 'rot',
labor_hours: 8,
work_type: 'bygg',
}
enqueue({ data: proforma })
enqueue({ data: null, count: 0 })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { lines: Record<string, unknown>[] } } }>(
await post(),
)
expect(status).toBe(400)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_UNSUPPORTED_LINES')
expect(body.error.details.lines).toEqual([
{
invoice_item_id: 'e2000000-0000-4000-8000-000000000001',
deduction_type: 'rot',
accrual: false,
quantity: 10,
},
])
// Refused after the already-converted count, before the customer load and any insert.
expect(findCalls('sales_orders', 'eq')).toContainEqual(['source_invoice_id', IDS.invoice])
expect(findCall('customers', 'select')).toBeUndefined()
expect(findCall('sales_orders', 'insert')).toBeUndefined()
expect(findCall('invoices', 'update')).toBeUndefined()
})
it('returns 400 SALES_ORDER_SOURCE_UNSUPPORTED_LINES for a negative-quantity line', async () => {
const proforma = makeProforma()
proforma.items.push({
...proforma.items[1],
id: 'e2000000-0000-4000-8000-000000000003',
sort_order: 2,
description: 'Rabatt',
quantity: -1,
unit_price: 200,
})
enqueue({ data: proforma })
enqueue({ data: null, count: 0 })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { lines: Record<string, unknown>[] } } }>(
await post(),
)
expect(status).toBe(400)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_UNSUPPORTED_LINES')
expect(body.error.details.lines).toEqual([
{
invoice_item_id: 'e2000000-0000-4000-8000-000000000003',
deduction_type: null,
accrual: false,
quantity: -1,
},
])
expect(findCall('sales_orders', 'insert')).toBeUndefined()
})
it('returns 400 SALES_ORDER_SOURCE_UNSUPPORTED_LINES for a periodised line', async () => {
const proforma = makeProforma()
proforma.items[1] = {
...proforma.items[1],
accrual_period_start: '2026-09-01',
accrual_period_end: '2027-08-31',
accrual_balance_account: '2990',
}
enqueue({ data: proforma })
enqueue({ data: null, count: 0 })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: { lines: Record<string, unknown>[] } } }>(
await post(),
)
expect(status).toBe(400)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_UNSUPPORTED_LINES')
expect(body.error.details.lines[0]).toMatchObject({ deduction_type: null, accrual: true })
expect(findCall('sales_orders', 'insert')).toBeUndefined()
})
it('does not treat a text row as unsupported (text rows have no deduction or quantity)', async () => {
// Same happy path as below, with the text row carrying a stray negative
// quantity: text rows are copied as quantity 0 and never gate the convert.
const proforma = makeProforma()
proforma.items[0] = { ...proforma.items[0], quantity: -1 }
enqueue({ data: proforma })
enqueue({ data: null, count: 0 })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.order } })
enqueue({ data: null })
enqueue({ data: 'OR-1' })
enqueue({ data: makeSalesOrder({ source_invoice_id: IDS.invoice, order_number: 'OR-1' }) })
enqueue({ data: [] })
enqueue({ data: [{ id: IDS.invoice }] })
const { status } = await parseJsonResponse(await post())
expect(status).toBe(201)
const lines = findCall('sales_order_items', 'insert')![0] as Record<string, unknown>[]
expect(lines[1]).toMatchObject({ line_type: 'text', quantity: 0 })
})
it('creates a draft order from the proforma, cancels the proforma and answers 201 with sales_order_id', async () => {
enqueue({ data: makeProforma() })
enqueue({ data: null, count: 0 })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.order } }) // sales_orders insert
enqueue({ data: null }) // sales_order_items insert
enqueue({ data: 'OR-1' }) // generate_sales_order_number
enqueue({ data: makeSalesOrder({ source_invoice_id: IDS.invoice, order_number: 'OR-1' }) })
enqueue({ data: [] })
enqueue({ data: [{ id: IDS.invoice }] }) // proforma CAS update
const { status, body } = await parseJsonResponse<{ data: SalesOrder; sales_order_id: string }>(await post())
expect(status).toBe(201)
expect(body.sales_order_id).toBe(IDS.order)
expect(body.data.id).toBe(IDS.order)
expect(body.data.source_invoice_id).toBe(IDS.invoice)
expect(body.data.status).toBe('draft')
expect(findCall('sales_orders', 'insert')![0]).toMatchObject({
customer_id: IDS.customer,
source_invoice_id: IDS.invoice,
currency: 'SEK',
your_reference: 'Anna',
notes: 'Enligt offert',
subtotal: 1000,
vat_amount: 250,
total: 1250,
})
// Lines copied in proforma sort order: product first, text row second.
const lines = findCall('sales_order_items', 'insert')![0] as Record<string, unknown>[]
expect(lines).toHaveLength(2)
expect(lines[0]).toMatchObject({
sort_order: 0,
line_type: 'product',
description: 'Konsulttimme',
quantity: 10,
unit: 'h',
revenue_account: '3011',
dimensions: { project: 'P1' },
line_total: 1000,
})
expect(lines[1]).toMatchObject({ sort_order: 1, line_type: 'text', quantity: 0, line_total: 0 })
expect(findCall('invoices', 'update')![0]).toEqual({ status: 'cancelled' })
expect(findCall('invoices', 'neq')).toEqual(['status', 'cancelled'])
expect(findCall('sales_orders', 'delete')).toBeUndefined()
})
it('removes the fresh order and answers 409 when the proforma was converted concurrently', async () => {
enqueue({ data: makeProforma() })
enqueue({ data: null, count: 0 })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.order } })
enqueue({ data: null })
enqueue({ data: 'OR-1' })
enqueue({ data: makeSalesOrder({ source_invoice_id: IDS.invoice }) })
enqueue({ data: [] })
enqueue({ data: [] }) // CAS update matched nothing
enqueue({ data: null }) // order delete
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_SOURCE_ALREADY_CONVERTED')
expect(findCall('sales_orders', 'delete')).toBeDefined()
expect(findCalls('sales_orders', 'eq')).toContainEqual(['id', IDS.order])
})
})
@@ -0,0 +1,23 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { convertProformaToSalesOrder } from '@/lib/sales-orders/convert-proforma'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
ensureInitialized()
/**
* POST /api/invoices/[id]/convert-to-order: proforma -> draft kundorder.
* Sibling of /convert (proforma -> invoice): copies the lines into a new
* order and marks the proforma cancelled.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'invoice.convert_to_order',
async (_request, { supabase, user, companyId, log, requestId }, { params }) => {
const { id } = await params
const result = await convertProformaToSalesOrder(supabase, { companyId, userId: user.id, invoiceId: id })
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order, sales_order_id: result.order.id }, { status: 201 })
},
{ requireWrite: true },
)
+3
View File
@@ -189,6 +189,9 @@ export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
// nothing else.
const replaced = await replaceInvoiceItems(supabase, id, build.items)
if (!replaced.ok) {
if (replaced.stage === 'guard') {
return errorResponseFromCode(replaced.code, ctxLog, { requestId })
}
ctxLog.error(`invoice items ${replaced.stage} failed on update`, replaced.error, { invoiceId: id })
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
requestId,
+5
View File
@@ -35,6 +35,11 @@ export const GET = withRouteContext(
if (status) {
query = query.eq('status', status)
}
// Kundorder detail: the invoices created from one order.
const salesOrderId = searchParams.get('sales_order_id')
if (salesOrderId && /^[0-9a-f-]{36}$/i.test(salesOrderId)) {
query = query.eq('sales_order_id', salesOrderId)
}
const { data, error, count } = await query
@@ -0,0 +1,51 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { CreateInvoiceFromSalesOrderSchema } from '@/lib/api/schemas'
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
ensureInitialized()
/**
* POST /api/sales-orders/[id]/create-invoice: create an unnumbered DRAFT
* kundfaktura for the picked (or remaining / delivered) order lines. The
* user reviews and sends it through the normal invoice flow, which books
* it. Partial invoicing is the point: call again for the rest.
*/
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'sales_order.create_invoice',
async (request, { supabase, user, companyId, log, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, CreateInvoiceFromSalesOrderSchema, {
log,
operation: 'sales_order.create_invoice',
})
if (!validation.success) return validation.response
const result = await createInvoiceFromSalesOrder(supabase, {
companyId,
userId: user.id,
orderId: id,
input: validation.data,
})
if (!result.ok) return serviceFailureResponse(result, log, requestId)
try {
await eventBus.emit({
type: 'invoice.created',
payload: { invoice: result.invoice, userId: user.id, companyId },
})
} catch {
// Non-critical
}
return NextResponse.json(
{ data: { invoice: result.invoice, order: result.order }, invoice_id: result.invoice.id },
{ status: 201 },
)
},
{ requireWrite: true },
)
@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { RegisterSalesOrderDeliverySchema } from '@/lib/api/schemas'
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
ensureInitialized()
/** POST /api/sales-orders/[id]/deliver: register cumulative delivered quantities. */
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'sales_order.deliver',
async (request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, RegisterSalesOrderDeliverySchema, { log, operation: 'sales_order.deliver' })
if (!validation.success) return validation.response
const result = await registerSalesOrderDelivery(supabase, { companyId, orderId: id, input: validation.data })
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order })
},
{ requireWrite: true },
)
+89
View File
@@ -0,0 +1,89 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { UpdateSalesOrderSchema } from '@/lib/api/schemas'
import { loadSalesOrder } from '@/lib/sales-orders/load'
import { hasOpenInvoices, updateSalesOrder } from '@/lib/sales-orders/write'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
import { codeFromPgError } from '@/lib/sales-orders/result'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
ensureInitialized()
type Ctx = { params: Promise<{ id: string }> }
/** GET /api/sales-orders/[id]: one order with lines + derived quantities. */
export const GET = withRouteContext<Ctx>(
'sales_order.get',
async (_request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
const result = await loadSalesOrder(supabase, companyId, id)
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order })
},
)
/** PATCH /api/sales-orders/[id]: edit header and/or replace lines (draft or confirmed). */
export const PATCH = withRouteContext<Ctx>(
'sales_order.update',
async (request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, UpdateSalesOrderSchema, { log, operation: 'sales_order.update' })
if (!validation.success) return validation.response
const result = await updateSalesOrder(supabase, { companyId, orderId: id, input: validation.data })
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order })
},
{ requireWrite: true },
)
/**
* DELETE /api/sales-orders/[id]: hard delete a draft or cancelled order
* that no invoice was created from. Orders never book and carry no
* sequence obligation, so nothing is lost; the RESTRICT FKs make a linked
* order undeletable at the DB level regardless.
*/
export const DELETE = withRouteContext<Ctx>(
'sales_order.delete',
async (_request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
const current = await loadSalesOrder(supabase, companyId, id)
if (!current.ok) return serviceFailureResponse(current, log, requestId)
if (current.order.status !== 'draft' && current.order.status !== 'cancelled') {
return errorResponseFromCode('SALES_ORDER_INVALID_STATE', log, {
requestId,
details: { status: current.order.status, action: 'delete' },
})
}
const open = await hasOpenInvoices(supabase, companyId, id)
if (!open.ok) return errorResponse(open.dbError, log, { requestId })
if (open.open) return errorResponseFromCode('SALES_ORDER_HAS_INVOICES', log, { requestId })
// Status in the predicate: a concurrent confirm between the read above
// and this delete must not remove a confirmed order.
const { data: deleted, error } = await supabase
.from('sales_orders')
.delete()
.eq('id', id)
.eq('company_id', companyId)
.in('status', ['draft', 'cancelled'])
.select('id')
if (!error && (!deleted || deleted.length === 0)) {
return errorResponseFromCode('SALES_ORDER_INVALID_STATE', log, {
requestId,
details: { action: 'delete', reason: 'status changed concurrently' },
})
}
if (error) {
// A makulerad (cancelled) invoice still references the order: the
// RESTRICT FK is the authority, surfaced as the structured code.
const code = codeFromPgError(error)
if (code) return errorResponseFromCode(code, log, { requestId })
return errorResponse(error, log, { requestId })
}
return NextResponse.json({ data: { id, deleted: true } })
},
{ requireWrite: true },
)
@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { SalesOrderTransitionSchema } from '@/lib/api/schemas'
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
ensureInitialized()
/** POST /api/sales-orders/[id]/transition: confirm | cancel | reopen. */
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
'sales_order.transition',
async (request, { supabase, companyId, log, requestId }, { params }) => {
const { id } = await params
const validation = await validateBody(request, SalesOrderTransitionSchema, { log, operation: 'sales_order.transition' })
if (!validation.success) return validation.response
const result = await transitionSalesOrder(supabase, { companyId, orderId: id, action: validation.data.action })
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order })
},
{ requireWrite: true },
)
@@ -0,0 +1,208 @@
/**
* POST /api/sales-orders/[id]/create-invoice: unnumbered draft kundfaktura
* from an order, with the invoice builder mocked.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
import { eventBus } from '@/lib/events'
import { IDS, invoicedRow, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem } from '@/lib/sales-orders/__tests__/fixtures'
import type { Invoice, SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const mockBuildInvoiceWriteData = vi.fn()
vi.mock('@/lib/invoices/build-invoice-write', () => ({
buildInvoiceWriteData: (...args: unknown[]) => mockBuildInvoiceWriteData(...args),
}))
import { POST } from '../[id]/create-invoice/route'
const params = createMockRouteParams({ id: IDS.order })
function post(body: unknown = {}) {
return POST(createMockRequest(`/api/sales-orders/${IDS.order}/create-invoice`, { method: 'POST', body }), params)
}
const okBuild = {
ok: true,
invoiceFields: {
customer_id: IDS.customer,
invoice_date: '2026-09-02',
due_date: '2026-10-02',
currency: 'SEK',
subtotal: 1000,
vat_amount: 250,
total: 1250,
},
items: [
{
sort_order: 0,
line_type: 'product',
description: 'Konsulttimme',
quantity: 10,
unit: 'h',
unit_price: 100,
line_total: 1000,
vat_rate: 25,
vat_amount: 250,
sales_order_item_id: IDS.item1,
},
],
}
const confirmed = () =>
makeSalesOrder({
status: 'confirmed',
confirmed_at: '2026-09-01T10:00:00Z',
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10 })],
})
describe('POST /api/sales-orders/[id]/create-invoice', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
eventBus.clear()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
mockBuildInvoiceWriteData.mockResolvedValue(okBuild)
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const { status } = await parseJsonResponse(await post())
expect(status).toBe(401)
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
})
it('returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const { status } = await parseJsonResponse(await post())
expect(status).toBe(403)
})
it('returns 400 for a picked line with quantity 0', async () => {
const { status } = await parseJsonResponse(
await post({ lines: [{ sales_order_item_id: IDS.item1, quantity: 0 }] }),
)
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for an unknown mode', async () => {
const { status } = await parseJsonResponse(await post({ mode: 'everything' }))
expect(status).toBe(400)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
})
it('returns 409 SALES_ORDER_INVALID_STATE for a draft order', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
})
it('returns 409 SALES_ORDER_OVER_INVOICED for a pick above the remaining quantity', async () => {
enqueue({ data: confirmed() })
enqueue({ data: [invoicedRow(IDS.item1, 7)] })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await post({ lines: [{ sales_order_item_id: IDS.item1, quantity: 4 }] }),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_OVER_INVOICED')
expect(body.error.details).toMatchObject({ remaining_qty: 3, requested_qty: 4 })
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
})
it('returns 409 SALES_ORDER_NOTHING_TO_INVOICE when everything is invoiced', async () => {
enqueue({ data: confirmed() })
enqueue({ data: [invoicedRow(IDS.item1, 10)] })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_NOTHING_TO_INVOICE')
})
it('creates the draft, links it to the order and answers 201 with invoice_id', async () => {
const emitted: string[] = []
eventBus.on('invoice.created', async () => {
emitted.push('invoice.created')
})
enqueue({ data: confirmed() })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft', invoice_number: null, sales_order_id: IDS.order } })
enqueue({ data: null }) // invoice_items insert
enqueue({ data: confirmed() }) // reload
enqueue({ data: [invoicedRow(IDS.item1, 10)] })
const { status, body } = await parseJsonResponse<{
data: { invoice: Invoice; order: SalesOrder }
invoice_id: string
}>(await post({ invoice_date: '2026-09-02' }))
expect(status).toBe(201)
expect(body.invoice_id).toBe(IDS.invoice)
expect(body.data.invoice.id).toBe(IDS.invoice)
expect(body.data.order.invoicing_progress).toBe('full')
expect(mockBuildInvoiceWriteData).toHaveBeenCalledWith(expect.objectContaining({ documentType: 'invoice' }))
const invoiceInsert = findCall('invoices', 'insert')![0] as Record<string, unknown>
expect(invoiceInsert).toMatchObject({ sales_order_id: IDS.order, invoice_number: null, status: 'draft' })
const itemRows = findCall('invoice_items', 'insert')![0] as Record<string, unknown>[]
expect(itemRows[0]).toMatchObject({ invoice_id: IDS.invoice, sales_order_item_id: IDS.item1 })
expect(emitted).toEqual(['invoice.created'])
})
it('rolls the draft back and answers 409 when the over-invoice trigger fires', async () => {
enqueue({ data: confirmed() })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null, error: { message: 'SALES_ORDER_OVER_INVOICED: exceeds ordered', code: 'P0001' } })
enqueue({ data: null })
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_OVER_INVOICED')
expect(findCall('invoices', 'delete')).toBeDefined()
})
})
@@ -0,0 +1,159 @@
/**
* POST /api/sales-orders/[id]/deliver (cumulative delivered quantities).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
import { IDS, makeSalesOrder, makeSalesOrderItem } from '@/lib/sales-orders/__tests__/fixtures'
import type { SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../[id]/deliver/route'
const params = createMockRouteParams({ id: IDS.order })
function post(body: unknown) {
return POST(createMockRequest(`/api/sales-orders/${IDS.order}/deliver`, { method: 'POST', body }), params)
}
const confirmed = (delivered = 0) =>
makeSalesOrder({
status: 'confirmed',
confirmed_at: '2026-09-01T10:00:00Z',
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: delivered })],
})
describe('POST /api/sales-orders/[id]/deliver', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const { status } = await parseJsonResponse(
await post({ lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] }),
)
expect(status).toBe(401)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for an empty lines array', async () => {
const { status } = await parseJsonResponse(await post({ lines: [] }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for a negative delivered quantity', async () => {
const { status } = await parseJsonResponse(
await post({ lines: [{ sales_order_item_id: IDS.item1, delivered_qty: -1 }] }),
)
expect(status).toBe(400)
})
it('returns 400 for a malformed delivery_date', async () => {
const { status } = await parseJsonResponse(
await post({ delivery_date: '02/09/2026', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] }),
)
expect(status).toBe(400)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await post({ lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] }),
)
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
})
it('returns 409 SALES_ORDER_INVALID_STATE for a draft order', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await post({ lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 1 }] }),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
})
it('returns 400 SALES_ORDER_OVER_DELIVERED when delivering more than ordered', async () => {
enqueue({ data: confirmed() })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await post({ lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 11 }] }),
)
expect(status).toBe(400)
expect(body.error.code).toBe('SALES_ORDER_OVER_DELIVERED')
expect(body.error.details).toMatchObject({ quantity: 10, delivered_qty: 11 })
expect(findCall('sales_order_items', 'update')).toBeUndefined()
})
it('returns 409 SALES_ORDER_INVALID_STATE when the line moved concurrently (update matched zero rows)', async () => {
enqueue({ data: confirmed(0) })
enqueue({ data: [] })
enqueue({ data: [] }) // line update: optimistic predicate on delivered_qty did not match
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await post({ delivery_date: '2026-09-02', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 6 }] }),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
expect(body.error.details).toMatchObject({ action: 'deliver', sales_order_item_id: IDS.item1 })
expect(findCall('sales_orders', 'update')).toBeUndefined()
})
it('registers the delivery and answers with the reloaded order', async () => {
enqueue({ data: confirmed(0) })
enqueue({ data: [] })
enqueue({ data: [{ id: IDS.item1 }] }) // line update (optimistic write matched the row)
enqueue({ data: null }) // last_delivery_date update
enqueue({ data: { ...confirmed(6), last_delivery_date: '2026-09-02' } })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ data: SalesOrder }>(
await post({ delivery_date: '2026-09-02', lines: [{ sales_order_item_id: IDS.item1, delivered_qty: 6 }] }),
)
expect(status).toBe(200)
expect(body.data.last_delivery_date).toBe('2026-09-02')
expect(body.data.delivery_progress).toBe('partial')
expect(body.data.items?.[0].delivered_qty).toBe(6)
// The increased line gets the delivery date as its own last_delivery_date.
expect(findCall('sales_order_items', 'update')![0]).toEqual({
delivered_qty: 6,
last_delivery_date: '2026-09-02',
})
expect(findCall('sales_orders', 'update')![0]).toEqual({ last_delivery_date: '2026-09-02' })
})
})
@@ -0,0 +1,306 @@
/**
* GET/PATCH/DELETE /api/sales-orders/[id].
*
* Queue order for loadSalesOrder: sales_orders select, then the
* sales_order_invoiced_quantities RPC.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
import { IDS, invoicedRow, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem } from '@/lib/sales-orders/__tests__/fixtures'
import type { SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, PATCH, DELETE } from '../[id]/route'
const params = createMockRouteParams({ id: IDS.order })
const url = `/api/sales-orders/${IDS.order}`
function unauthenticated() {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('GET /api/sales-orders/[id]', () => {
it('returns 401 when not authenticated', async () => {
unauthenticated()
const { status } = await parseJsonResponse(await GET(createMockRequest(url), params))
expect(status).toBe(401)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await GET(createMockRequest(url), params),
)
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
expect(supabase.rpc).not.toHaveBeenCalled()
})
it('returns the order with sorted lines, derived quantities and a masked customer', async () => {
enqueue({
data: makeSalesOrder({
customer: makeOrderCustomer({ customer_type: 'individual', personal_number: '199001011234' }),
items: [
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 5 }),
makeSalesOrderItem({ id: IDS.item1, sort_order: 0, quantity: 10, delivered_qty: 3 }),
],
}),
})
enqueue({ data: [invoicedRow(IDS.item1, '2')] })
const { status, body } = await parseJsonResponse<{ data: SalesOrder }>(await GET(createMockRequest(url), params))
expect(status).toBe(200)
expect(body.data.id).toBe(IDS.order)
expect(body.data.items?.map((i) => i.id)).toEqual([IDS.item1, IDS.item2])
expect(body.data.items?.[0]).toMatchObject({ invoiced_qty: 2, remaining_qty: 8 })
expect(body.data.items?.[1]).toMatchObject({ invoiced_qty: 0, remaining_qty: 5 })
expect(body.data.delivery_progress).toBe('partial')
expect(body.data.invoicing_progress).toBe('partial')
// The embedded customer never carries the raw personnummer out.
expect(body.data.customer?.personal_number).not.toBe('199001011234')
expect(findCalls('sales_orders', 'eq')).toContainEqual(['id', IDS.order])
expect(findCalls('sales_orders', 'eq')).toContainEqual(['company_id', IDS.company])
})
})
describe('PATCH /api/sales-orders/[id]', () => {
function patch(body: unknown) {
return PATCH(createMockRequest(url, { method: 'PATCH', body }), params)
}
it('returns 401 when not authenticated', async () => {
unauthenticated()
const { status } = await parseJsonResponse(await patch({ notes: 'x' }))
expect(status).toBe(401)
})
it('returns 400 for an empty items array', async () => {
const { status } = await parseJsonResponse(await patch({ items: [] }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for an unsupported currency', async () => {
const { status } = await parseJsonResponse(await patch({ currency: 'CHF' }))
expect(status).toBe(400)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch({ notes: 'x' }))
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
})
it('returns 409 SALES_ORDER_NOT_EDITABLE for a completed order', async () => {
enqueue({ data: makeSalesOrder({ status: 'completed' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await patch({ notes: 'x' }))
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_NOT_EDITABLE')
})
it('returns 409 SALES_ORDER_LINE_LOCKED when an invoiced line is dropped', async () => {
enqueue({ data: makeSalesOrder({ status: 'confirmed', items: [makeSalesOrderItem({ id: IDS.item1 })] }) })
enqueue({ data: [invoicedRow(IDS.item1, 2)] })
enqueue({ data: makeOrderCustomer() })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await patch({ items: [{ description: 'Ny rad', quantity: 1, unit: 'st', unit_price: 10, vat_rate: 25 }] }),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_LINE_LOCKED')
expect(body.error.details).toMatchObject({ sales_order_item_id: IDS.item1 })
})
it('updates the header and answers with the reloaded order', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: null }) // header update
enqueue({ data: makeSalesOrder({ status: 'draft', notes: 'Ring innan leverans' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ data: SalesOrder }>(
await patch({ notes: 'Ring innan leverans' }),
)
expect(status).toBe(200)
expect(body.data.notes).toBe('Ring innan leverans')
expect(body.data.delivery_progress).toBe('none')
expect(findCall('sales_orders', 'update')![0]).toMatchObject({ notes: 'Ring innan leverans' })
})
})
describe('DELETE /api/sales-orders/[id]', () => {
function del() {
return DELETE(createMockRequest(url, { method: 'DELETE' }), params)
}
it('returns 401 when not authenticated', async () => {
unauthenticated()
const { status } = await parseJsonResponse(await del())
expect(status).toBe(401)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
expect(findCall('sales_orders', 'delete')).toBeUndefined()
})
it('returns 409 for a confirmed order', async () => {
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await del(),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
expect(body.error.details).toMatchObject({ status: 'confirmed', action: 'delete' })
expect(findCall('sales_orders', 'delete')).toBeUndefined()
})
it('returns 409 SALES_ORDER_HAS_INVOICES when an invoice is linked', async () => {
enqueue({ data: makeSalesOrder({ status: 'cancelled' }) })
enqueue({ data: [] })
enqueue({ data: [] }) // hasOpenInvoices rpc
enqueue({ data: null, count: 1 }) // header-linked invoice
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_HAS_INVOICES')
expect(findCall('sales_orders', 'delete')).toBeUndefined()
})
it('maps the RESTRICT FK on delete onto 409 SALES_ORDER_HAS_INVOICES (makulerad invoice still linked)', async () => {
// A cancelled invoice carries 0 invoiced quantity and is excluded from
// the header count, so the pre-checks let the delete through and the FK
// is the authority.
enqueue({ data: makeSalesOrder({ status: 'cancelled' }) })
enqueue({ data: [] })
enqueue({ data: [] }) // hasOpenInvoices rpc
enqueue({ data: null, count: 0 }) // no non-cancelled invoice
enqueue({
data: null,
error: {
code: '23503',
message:
'update or delete on table "sales_orders" violates foreign key constraint "invoices_sales_order_id_fkey" on table "invoices"',
},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_HAS_INVOICES')
expect(findCall('sales_orders', 'delete')).toBeDefined()
})
it('maps the line-level RESTRICT FK on delete onto 409 SALES_ORDER_LINE_LOCKED', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
enqueue({ data: [] })
enqueue({ data: null, count: 0 })
enqueue({
data: null,
error: {
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"',
},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_LINE_LOCKED')
})
it('hard-deletes a draft with no invoices', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
enqueue({ data: [] })
enqueue({ data: null, count: 0 })
enqueue({ data: [{ id: IDS.order }] }) // delete (status-guarded, one row matched)
const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(await del())
expect(status).toBe(200)
expect(body.data).toEqual({ id: IDS.order, deleted: true })
expect(findCall('sales_orders', 'delete')).toBeDefined()
const eqs = findCalls('sales_orders', 'eq')
expect(eqs).toContainEqual(['id', IDS.order])
expect(eqs).toContainEqual(['company_id', IDS.company])
// Status in the delete predicate: a concurrent confirm must not be deleted.
expect(findCall('sales_orders', 'in')).toEqual(['status', ['draft', 'cancelled']])
// The first sales_orders select is loadSalesOrder's projection; the delete chain's is ['id'].
expect(findCalls('sales_orders', 'select')).toContainEqual(['id'])
})
it('returns 409 SALES_ORDER_INVALID_STATE when the delete matches zero rows (confirmed concurrently)', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
enqueue({ data: [] }) // hasOpenInvoices rpc
enqueue({ data: null, count: 0 }) // no linked invoice
enqueue({ data: [] }) // delete: the status predicate no longer matches
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await del(),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
expect(body.error.details).toMatchObject({ action: 'delete', reason: 'status changed concurrently' })
expect(findCall('sales_orders', 'delete')).toBeDefined()
})
it('treats a null delete result as the same conflict', async () => {
enqueue({ data: makeSalesOrder({ status: 'cancelled' }) })
enqueue({ data: [] })
enqueue({ data: [] })
enqueue({ data: null, count: 0 })
enqueue({ data: null }) // delete
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await del())
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
})
})
@@ -0,0 +1,199 @@
/**
* GET/POST /api/sales-orders (kundorder list + create), through the real
* withRouteContext wrapper with its auth/company/write dependencies mocked.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import { IDS, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem, invoicedRow } from '@/lib/sales-orders/__tests__/fixtures'
import type { SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, POST } from '../route'
const noParams = { params: Promise.resolve({}) }
const validLine = { description: 'Konsulttimme', quantity: 10, unit: 'h', unit_price: 100, vat_rate: 25 }
function unauthenticated() {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
describe('GET /api/sales-orders', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
unauthenticated()
const { status } = await parseJsonResponse(await GET(createMockRequest('/api/sales-orders'), noParams))
expect(status).toBe(401)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for an unknown status filter', async () => {
const request = createMockRequest('/api/sales-orders', { searchParams: { status: 'shipped' } })
const { status } = await parseJsonResponse(await GET(request, noParams))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('lists orders decorated with invoiced quantities and progress', async () => {
enqueue({
data: [
makeSalesOrder({ items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 10 })] }),
makeSalesOrder({ id: 'a1000000-0000-4000-8000-000000000002', status: 'confirmed', items: [] }),
],
})
enqueue({ data: [invoicedRow(IDS.item1, '4')] })
const request = createMockRequest('/api/sales-orders', { searchParams: { status: 'draft', q: 'OR-1' } })
const { status, body } = await parseJsonResponse<{ data: SalesOrder[] }>(await GET(request, noParams))
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
expect(body.data[0].items?.[0]).toMatchObject({ invoiced_qty: 4, remaining_qty: 6 })
expect(body.data[0].delivery_progress).toBe('full')
expect(body.data[0].invoicing_progress).toBe('partial')
expect(body.data[1].delivery_progress).toBe('none')
expect(findCalls('sales_orders', 'eq')).toContainEqual(['company_id', IDS.company])
expect(findCalls('sales_orders', 'eq')).toContainEqual(['status', 'draft'])
expect(findCall('sales_orders', 'ilike')).toEqual(['order_number', '%OR-1%'])
expect(supabase.rpc).toHaveBeenCalledWith('sales_order_invoiced_quantities', { p_order_ids: [IDS.order, 'a1000000-0000-4000-8000-000000000002'] })
})
it('returns an empty list without calling the RPC when there are no orders', async () => {
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await GET(createMockRequest('/api/sales-orders'), noParams),
)
expect(status).toBe(200)
expect(body.data).toEqual([])
expect(supabase.rpc).not.toHaveBeenCalled()
})
})
describe('POST /api/sales-orders', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
function post(body: unknown) {
return POST(createMockRequest('/api/sales-orders', { method: 'POST', body }), noParams)
}
it('returns 401 when not authenticated', async () => {
unauthenticated()
const { status } = await parseJsonResponse(await post({ customer_id: IDS.customer, items: [validLine] }))
expect(status).toBe(401)
})
it('returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const { status } = await parseJsonResponse(await post({ customer_id: IDS.customer, items: [validLine] }))
expect(status).toBe(403)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 when items are missing', async () => {
const { status } = await parseJsonResponse(await post({ customer_id: IDS.customer }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 when customer_id is not a uuid', async () => {
const { status } = await parseJsonResponse(await post({ customer_id: 'kund-1', items: [validLine] }))
expect(status).toBe(400)
})
it('returns 400 for a product line with an empty description', async () => {
const { status } = await parseJsonResponse(
await post({ customer_id: IDS.customer, items: [{ ...validLine, description: ' ' }] }),
)
expect(status).toBe(400)
})
it('returns 404 when the customer does not exist in the company', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await post({ customer_id: IDS.customer, items: [validLine] }),
)
expect(status).toBe(404)
expect(body.error.code).toBe('CUSTOMER_NOT_FOUND')
})
it('returns 400 INVOICE_CREATE_VAT_RULE_VIOLATION for a rate the customer type forbids', async () => {
enqueue({ data: makeOrderCustomer({ customer_type: 'non_eu_business' }) })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await post({ customer_id: IDS.customer, items: [{ ...validLine, vat_rate: 20 }] }),
)
expect(status).toBe(400)
expect(body.error.code).toBe('INVOICE_CREATE_VAT_RULE_VIOLATION')
expect(findCall('sales_orders', 'insert')).toBeUndefined()
})
it('creates a draft order and answers 201 with the loaded order', async () => {
enqueue({ data: makeOrderCustomer() }) // customer lookup
enqueue({ data: { id: IDS.order } }) // header insert
enqueue({ data: null }) // lines insert
enqueue({ data: 'OR-1' }) // generate_sales_order_number
enqueue({ data: makeSalesOrder({ order_number: 'OR-1' }) }) // reload
enqueue({ data: [] }) // invoiced quantities
const { status, body } = await parseJsonResponse<{ data: SalesOrder }>(
await post({
customer_id: IDS.customer,
order_date: '2026-09-01',
items: [validLine, { line_type: 'text', description: 'Leverans v.36', quantity: 0, unit: '', unit_price: 0 }],
}),
)
expect(status).toBe(201)
expect(body.data.id).toBe(IDS.order)
expect(body.data.order_number).toBe('OR-1')
expect(body.data.status).toBe('draft')
expect(body.data.delivery_progress).toBe('none')
expect(body.data.invoicing_progress).toBe('none')
expect(findCall('sales_orders', 'insert')![0]).toMatchObject({
company_id: IDS.company,
user_id: IDS.user,
customer_id: IDS.customer,
status: 'draft',
subtotal: 1000,
vat_amount: 250,
total: 1250,
})
const lines = findCall('sales_order_items', 'insert')![0] as unknown[]
expect(lines).toHaveLength(2)
})
})
@@ -0,0 +1,126 @@
/**
* POST /api/sales-orders/[id]/transition (confirm | cancel | reopen).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
createMockRouteParams,
parseJsonResponse,
} from '@/tests/helpers'
import { IDS, invoicedRow, makeSalesOrder } from '@/lib/sales-orders/__tests__/fixtures'
import type { SalesOrder } from '@/types'
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { POST } from '../[id]/transition/route'
const params = createMockRouteParams({ id: IDS.order })
function post(body: unknown) {
return POST(createMockRequest(`/api/sales-orders/${IDS.order}/transition`, { method: 'POST', body }), params)
}
describe('POST /api/sales-orders/[id]/transition', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: IDS.user }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const { status } = await parseJsonResponse(await post({ action: 'confirm' }))
expect(status).toBe(401)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const { status } = await parseJsonResponse(await post({ action: 'confirm' }))
expect(status).toBe(403)
})
it('returns 400 for an unknown action', async () => {
const { status } = await parseJsonResponse(await post({ action: 'ship' }))
expect(status).toBe(400)
expect(supabase.from).not.toHaveBeenCalled()
})
it('returns 400 for a missing body', async () => {
const { status } = await parseJsonResponse(await post({}))
expect(status).toBe(400)
})
it('returns 404 when the order is missing', async () => {
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post({ action: 'confirm' }))
expect(status).toBe(404)
expect(body.error.code).toBe('SALES_ORDER_NOT_FOUND')
})
it('returns 409 SALES_ORDER_INVALID_STATE for confirm on a confirmed order', async () => {
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ error: { code: string; details: Record<string, unknown> } }>(
await post({ action: 'confirm' }),
)
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_INVALID_STATE')
expect(body.error.details).toMatchObject({ status: 'confirmed', action: 'confirm' })
})
it('returns 409 SALES_ORDER_HAS_INVOICES for cancel with a linked invoice', async () => {
enqueue({ data: makeSalesOrder({ status: 'confirmed' }) })
enqueue({ data: [invoicedRow(IDS.item1, 1)] })
enqueue({ data: [invoicedRow(IDS.item1, 1)] })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await post({ action: 'cancel' }))
expect(status).toBe(409)
expect(body.error.code).toBe('SALES_ORDER_HAS_INVOICES')
expect(findCall('sales_orders', 'update')).toBeUndefined()
})
it('confirms a draft and answers with the reloaded order', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
enqueue({ data: [{ id: IDS.order }] }) // CAS update
enqueue({ data: null }) // refresh_sales_order_completion
enqueue({ data: makeSalesOrder({ status: 'confirmed', confirmed_at: '2026-09-02T10:00:00Z' }) })
enqueue({ data: [] })
const { status, body } = await parseJsonResponse<{ data: SalesOrder }>(await post({ action: 'confirm' }))
expect(status).toBe(200)
expect(body.data.status).toBe('confirmed')
expect(body.data.confirmed_at).toBe('2026-09-02T10:00:00Z')
expect(body.data.delivery_progress).toBe('none')
expect(findCall('sales_orders', 'update')![0]).toMatchObject({ status: 'confirmed' })
expect(supabase.rpc).toHaveBeenCalledWith('refresh_sales_order_completion', { p_order_id: IDS.order })
})
})
+62
View File
@@ -0,0 +1,62 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody, validateQuery } from '@/lib/api/validate'
import { CreateSalesOrderSchema, SalesOrderListQuerySchema } from '@/lib/api/schemas'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { maskEmbeddedCustomer } from '@/lib/customers/protect-personal-number'
import { decorate, fetchInvoicedQuantities } from '@/lib/sales-orders/load'
import { createSalesOrder } from '@/lib/sales-orders/write'
import { serviceFailureResponse } from '@/lib/sales-orders/respond'
import { errorResponse } from '@/lib/errors/get-structured-error'
import type { SalesOrder } from '@/types'
ensureInitialized()
/**
* GET /api/sales-orders: the company's kundorder with customer, lines and
* the derived delivery/invoicing progress. Filters: status, customer_id, q
* (order number; the list page matches customer names client-side over the
* embedded customer).
*/
export const GET = withRouteContext('sales_order.list', async (request, { supabase, companyId, log, requestId }) => {
const query = validateQuery(request, SalesOrderListQuerySchema)
if (!query.success) return query.response
const { status, customer_id, q } = query.data
let orders: SalesOrder[]
try {
orders = await fetchAllRows<SalesOrder>(({ from, to }) => {
let qb = supabase
.from('sales_orders')
.select('*, customer:customers(id, name, customer_number, customer_type), items:sales_order_items(*)')
.eq('company_id', companyId)
if (status) qb = qb.eq('status', status)
if (customer_id) qb = qb.eq('customer_id', customer_id)
if (q) qb = qb.ilike('order_number', `%${q}%`)
return qb.order('order_date', { ascending: false }).order('created_at', { ascending: false }).range(from, to)
})
} catch (err) {
return errorResponse(err, log, { requestId })
}
const invoiced = await fetchInvoicedQuantities(supabase, orders.map((o) => o.id))
if (!invoiced.ok) return errorResponse(invoiced.dbError, log, { requestId })
const data = orders.map((o) => decorate(maskEmbeddedCustomer(o), invoiced.byItem))
return NextResponse.json({ data })
})
/** POST /api/sales-orders: create a draft order with lines. */
export const POST = withRouteContext(
'sales_order.create',
async (request, { supabase, user, companyId, log, requestId }) => {
const validation = await validateBody(request, CreateSalesOrderSchema, { log, operation: 'sales_order.create' })
if (!validation.success) return validation.response
const result = await createSalesOrder(supabase, { companyId, userId: user.id, input: validation.data })
if (!result.ok) return serviceFailureResponse(result, log, requestId)
return NextResponse.json({ data: result.order }, { status: 201 })
},
{ requireWrite: true },
)
@@ -252,7 +252,10 @@ describe('PATCH /api/v1/companies/:companyId/invoices/:id', () => {
error: null,
},
company_settings: { data: { vat_registered: true }, error: null },
invoice_items: { data: null, error: null },
// replaceInvoiceItems snapshots the current rows before deleting and
// refuses (fails closed) when the snapshot is unreadable, so the
// mock must answer with a real (empty) row set.
invoice_items: { data: [], error: null },
},
captures,
),
@@ -464,6 +464,9 @@ export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string
// cookie route and the update_invoice commit executor).
const replaced = await replaceInvoiceItems(ctx.supabase, invoiceId, build.items)
if (!replaced.ok) {
if (replaced.stage === 'guard') {
return v1ErrorResponseFromCode(replaced.code, ctx.log, { requestId: ctx.requestId })
}
ctx.log.error(`invoice items ${replaced.stage} failed on v1 update`, replaced.error, {
invoiceId,
companyId: ctx.companyId,
+15 -2
View File
@@ -50,6 +50,7 @@ import {
FolderArchive,
ShoppingCart,
Car,
ClipboardList,
} from 'lucide-react'
import { getBranding } from '@/lib/branding/service'
import { BrandHomeLink } from '@/components/branding/BrandHomeLink'
@@ -88,6 +89,10 @@ interface DashboardNavProps {
// switched on. Drives visibility of the Kostnadsställen & projekt row:
// same mechanism as paysSalaries: fetched by the dashboard layout.
dimensionsEnabled?: boolean
// Whether kundorder (company_settings.sales_orders_enabled) is switched on.
// Drives visibility of the Kundorder row: same mechanism as
// dimensionsEnabled, fetched by the dashboard layout.
salesOrdersEnabled?: boolean
// Whether the company has a webshop hooked up (active WooCommerce/Shopify
// connection, or existing webshop_orders rows). Drives visibility of the
// Order row: same mechanism as paysSalaries, fetched by the layout.
@@ -117,6 +122,7 @@ type NavLabelKey =
| 'invoice_inbox'
| 'invoices'
| 'sales_orders'
| 'webshop_orders'
| 'customers'
| 'articles'
| 'supplier_invoices'
@@ -183,6 +189,10 @@ interface NavItem {
// company_settings.dimensions_enabled (UI-visibility gate only; the pages
// and APIs work regardless, dimensions plan §2).
requiresDimensions?: boolean
// Kundorder surfaces: visible only when the company has opted in via
// company_settings.sales_orders_enabled (UI-visibility gate only; the
// pages and APIs work regardless).
requiresSalesOrders?: boolean
// Webshop surfaces: visible only when the company has an active
// WooCommerce/Shopify connection or already-imported order rows.
// UI-visibility gate only; the page and APIs work regardless.
@@ -225,12 +235,14 @@ const navItems: NavItem[] = [
{ href: '/transactions', labelKey: 'transactions', icon: ArrowLeftRight, group: 'arbeta' },
{ href: '/reconciliation', labelKey: 'reconciliation', icon: Scale, group: 'arbeta' },
{ href: '/pending', labelKey: 'review', icon: ClipboardCheck, group: 'arbeta' },
// Kundorder: opt-in via the bookkeeping settings toggle (UI gate only).
{ href: '/sales-orders', labelKey: 'sales_orders', icon: ClipboardList, group: 'arbeta', requiresSalesOrders: true },
{ href: '/invoices', labelKey: 'invoices', icon: ReceiptText, group: 'arbeta' },
// Webshop orders: visible only for companies that actually have a webshop
// hooked up (active WooCommerce/Shopify connection or existing order rows).
// Deliberately NOT capability-gated: a company whose entitlement lapsed
// must still reach its already-imported orders (accounting underlag).
{ href: '/orders', labelKey: 'sales_orders', icon: ShoppingCart, group: 'arbeta', requiresWebshop: true, betaBadge: true },
{ href: '/orders', labelKey: 'webshop_orders', icon: ShoppingCart, group: 'arbeta', requiresWebshop: true, betaBadge: true },
{ href: '/supplier-invoices', labelKey: 'supplier_invoices', icon: Wallet, group: 'arbeta' },
{ href: '/salary', labelKey: 'salary', icon: HandCoins, group: 'arbeta', employerOnly: true },
// Körjournal: hidden by default (most companies have no car); shows when
@@ -329,7 +341,7 @@ const groupLabelKey: Record<Exclude<GroupKey, 'top'>, string> = {
skatt: 'group_tax',
}
export default function DashboardNav({ companyName: _companyName, entityType, paysSalaries = false, dimensionsEnabled = false, hasWebshop = false, hasMileage = false, isSandbox = false, extensionNavItems = [], userName = null, userEmail = null, initialUiState }: DashboardNavProps) {
export default function DashboardNav({ companyName: _companyName, entityType, paysSalaries = false, dimensionsEnabled = false, salesOrdersEnabled = false, hasWebshop = false, hasMileage = false, isSandbox = false, extensionNavItems = [], userName = null, userEmail = null, initialUiState }: DashboardNavProps) {
const pathname = usePathname()
const router = useRouter()
const supabase = useRealtimeSupabase()
@@ -572,6 +584,7 @@ export default function DashboardNav({ companyName: _companyName, entityType, pa
// Dimension surfaces are hidden until the company opts in via the
// bookkeeping settings toggle (company_settings.dimensions_enabled).
if (item.requiresDimensions && !dimensionsEnabled) return false
if (item.requiresSalesOrders && !salesOrdersEnabled) return false
// Webshop surfaces are hidden until a store is connected (or order rows
// already exist from a since-disconnected store).
if (item.requiresWebshop && !hasWebshop) return false
+7
View File
@@ -270,6 +270,10 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
vat_rate: z.number().min(0).max(25),
// Article linkage (artikelregister). Optional: free-text lines omit them.
article_id: z.string().nullable().optional(),
// Kundorder line link: an invoice created from a sales order carries it
// per item; the draft editor replaces items wholesale on save, so the
// field must round-trip or the order line becomes re-invoiceable.
sales_order_item_id: z.string().nullable().optional(),
revenue_account: z
.string()
.regex(INVOICE_POSTING_ACCOUNT_REGEX, t('posting_account_invalid'))
@@ -559,6 +563,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
discount_percent: hasLineDiscount(item.discount_percent) ? item.discount_percent : null,
vat_rate: item.vat_rate ?? 25,
article_id: item.article_id ?? null,
sales_order_item_id: item.sales_order_item_id ?? null,
revenue_account: item.revenue_account ?? null,
deduction_type: item.deduction_type ?? null,
labor_hours: item.labor_hours ?? null,
@@ -836,6 +841,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
discount_percent: null,
vat_rate: vatRegistered ? vatRatePlan.defaultRate : 0,
article_id: null,
sales_order_item_id: null,
revenue_account: null,
deduction_type: null,
labor_hours: null,
@@ -891,6 +897,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
discount_percent: null,
vat_rate: 0,
article_id: null,
sales_order_item_id: null,
revenue_account: null,
deduction_type: null,
labor_hours: null,
@@ -0,0 +1,241 @@
'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { ToastAction } from '@/components/ui/toast'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { cn } from '@/lib/utils'
import { formatQty } from '@/components/sales-orders/labels'
import type { SalesOrder, SalesOrderItem } from '@/types'
interface CreateInvoiceDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
order: SalesOrder
onCreated: (order: SalesOrder, invoiceId: string) => void
}
function productLines(order: SalesOrder): SalesOrderItem[] {
return [...(order.items ?? [])]
.filter((i) => (i.line_type ?? 'product') === 'product')
.sort((a, b) => a.sort_order - b.sort_order)
}
function remainingOf(item: SalesOrderItem): number {
return Math.max(0, item.remaining_qty ?? item.quantity - (item.invoiced_qty ?? 0))
}
function deliveredNotInvoicedOf(item: SalesOrderItem): number {
return Math.max(0, Math.min(remainingOf(item), (item.delivered_qty ?? 0) - (item.invoiced_qty ?? 0)))
}
function parseQty(value: string | undefined): number {
const n = parseFloat((value ?? '').replace(',', '.'))
return Number.isFinite(n) && n > 0 ? n : 0
}
/**
* Creates a DRAFT kundfaktura from the order for the picked quantities.
* Prefilled with what remains; the two shortcuts reseed the picks (all
* remaining / delivered but not yet invoiced). The explicit line picks are
* what is sent, so what the user sees is exactly what gets invoiced.
*/
export default function CreateInvoiceDialog({
open,
onOpenChange,
order,
onCreated,
}: CreateInvoiceDialogProps) {
const t = useTranslations('sales_order_detail')
const tCommon = useTranslations('common')
const errorLocale = useLocale() as ErrorLocale
const router = useRouter()
const { toast } = useToast()
const [quantities, setQuantities] = useState<Record<string, string>>({})
const [invoiceDate, setInvoiceDate] = useState('')
const [dueDate, setDueDate] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const lines = productLines(order)
function seed(mode: 'remaining' | 'delivered') {
const next: Record<string, string> = {}
for (const item of productLines(order)) {
const qty = mode === 'remaining' ? remainingOf(item) : deliveredNotInvoicedOf(item)
next[item.id] = qty > 0 ? String(qty) : ''
}
setQuantities(next)
}
useEffect(() => {
if (!open) return
setInvoiceDate('')
setDueDate('')
const next: Record<string, string> = {}
for (const item of productLines(order)) {
const qty = remainingOf(item)
next[item.id] = qty > 0 ? String(qty) : ''
}
setQuantities(next)
}, [open, order])
const picked = lines
.map((item) => ({ sales_order_item_id: item.id, quantity: parseQty(quantities[item.id]) }))
.filter((l) => l.quantity > 0)
async function handleSubmit() {
if (picked.length === 0) {
toast({ title: t('invoice_nothing_selected'), variant: 'destructive' })
return
}
setIsSubmitting(true)
try {
const response = await fetch(`/api/sales-orders/${order.id}/create-invoice`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
lines: picked,
...(invoiceDate ? { invoice_date: invoiceDate } : {}),
...(dueDate ? { due_date: dueDate } : {}),
}),
})
const json = await response.json().catch(() => null)
if (!response.ok) {
toast({
title: t('invoice_failed_title'),
description: getErrorMessage(json, { locale: errorLocale, statusCode: response.status }),
variant: 'destructive',
})
return
}
const invoiceId: string = json.invoice_id
toast({
title: t('invoice_created_title'),
description: t('invoice_created_description'),
action: (
<ToastAction altText={t('open_invoice')} onClick={() => router.push(`/invoices/${invoiceId}`)}>
{t('open_invoice')}
</ToastAction>
),
})
onCreated(json.data.order as SalesOrder, invoiceId)
onOpenChange(false)
} catch (err) {
toast({
title: t('invoice_failed_title'),
description: getErrorMessage(err, { locale: errorLocale }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(v) => !isSubmitting && onOpenChange(v)}>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>{t('invoice_dialog_title')}</DialogTitle>
<DialogDescription>{t('invoice_dialog_description')}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => seed('remaining')}>
{t('mode_remaining')}
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => seed('delivered')}>
{t('mode_delivered')}
</Button>
</div>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'pl-0')}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_remaining_qty')}</th>
<th className={cn(TH_CLASS, 'pr-0 text-right')}>{t('th_invoice_qty')}</th>
</tr>
</thead>
<tbody>
{lines.map((item) => (
<tr key={item.id}>
<td className={cn(TD_CLASS, 'pl-0')}>
<span className="block truncate">{item.description}</span>
</td>
<td className={cn(TD_CLASS, 'text-right tabular-nums text-muted-foreground')}>
{formatQty(remainingOf(item))} {item.unit}
</td>
<td className={cn(TD_CLASS, 'pr-0 text-right')}>
<Input
type="number"
inputMode="decimal"
step="any"
min={0}
value={quantities[item.id] ?? ''}
onChange={(e) =>
setQuantities((prev) => ({ ...prev, [item.id]: e.target.value }))
}
aria-label={`${t('th_invoice_qty')}: ${item.description}`}
className="ml-auto h-8 w-24 text-right tabular-nums"
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="so-invoice-date">{t('invoice_date_label')}</Label>
<Input
id="so-invoice-date"
type="date"
value={invoiceDate}
onChange={(e) => setInvoiceDate(e.target.value)}
className="tabular-nums"
/>
</div>
<div className="space-y-2">
<Label htmlFor="so-due-date">{t('due_date_label')}</Label>
<Input
id="so-due-date"
type="date"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
className="tabular-nums"
/>
</div>
</div>
</div>
<DialogFooter>
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
{tCommon('cancel')}
</Button>
<Button type="button" onClick={handleSubmit} disabled={isSubmitting || picked.length === 0}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('invoice_submit')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,186 @@
'use client'
import { useEffect, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { cn } from '@/lib/utils'
import { formatQty, todayIso } from '@/components/sales-orders/labels'
import type { SalesOrder, SalesOrderItem } from '@/types'
interface RegisterDeliveryDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
order: SalesOrder
onRegistered: (order: SalesOrder) => void
}
function productLines(order: SalesOrder): SalesOrderItem[] {
return [...(order.items ?? [])]
.filter((i) => (i.line_type ?? 'product') === 'product')
.sort((a, b) => a.sort_order - b.sort_order)
}
/**
* Registers CUMULATIVE delivered quantities per line (what the user sees is
* what is stored; a retry is idempotent). Prefilled with the current
* delivered_qty so the dialog doubles as the correction surface.
*/
export default function RegisterDeliveryDialog({
open,
onOpenChange,
order,
onRegistered,
}: RegisterDeliveryDialogProps) {
const t = useTranslations('sales_order_detail')
const tCommon = useTranslations('common')
const errorLocale = useLocale() as ErrorLocale
const { toast } = useToast()
const [deliveryDate, setDeliveryDate] = useState<string>(todayIso())
const [quantities, setQuantities] = useState<Record<string, string>>({})
const [isSubmitting, setIsSubmitting] = useState(false)
// Re-seed from the order every time the dialog opens: the order may have
// changed since the last registration.
useEffect(() => {
if (!open) return
setDeliveryDate(todayIso())
const seed: Record<string, string> = {}
for (const item of productLines(order)) seed[item.id] = String(item.delivered_qty ?? 0)
setQuantities(seed)
}, [open, order])
const lines = productLines(order)
function deliverAll() {
const next: Record<string, string> = {}
for (const item of lines) next[item.id] = String(item.quantity)
setQuantities(next)
}
async function handleSubmit() {
setIsSubmitting(true)
try {
const response = await fetch(`/api/sales-orders/${order.id}/deliver`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
delivery_date: deliveryDate || undefined,
lines: lines.map((item) => ({
sales_order_item_id: item.id,
delivered_qty: Math.max(0, parseFloat((quantities[item.id] ?? '0').replace(',', '.')) || 0),
})),
}),
})
const json = await response.json().catch(() => null)
if (!response.ok) {
toast({
title: t('delivery_failed_title'),
description: getErrorMessage(json, { locale: errorLocale, statusCode: response.status }),
variant: 'destructive',
})
return
}
toast({ title: t('delivery_success') })
onRegistered(json.data as SalesOrder)
onOpenChange(false)
} catch (err) {
toast({
title: t('delivery_failed_title'),
description: getErrorMessage(err, { locale: errorLocale }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(v) => !isSubmitting && onOpenChange(v)}>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>{t('delivery_dialog_title')}</DialogTitle>
<DialogDescription>{t('delivery_dialog_description')}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="max-w-xs space-y-2">
<Label htmlFor="so-delivery-date">{t('delivery_date_label')}</Label>
<Input
id="so-delivery-date"
type="date"
value={deliveryDate}
onChange={(e) => setDeliveryDate(e.target.value)}
className="tabular-nums"
/>
</div>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'pl-0')}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_ordered')}</th>
<th className={cn(TH_CLASS, 'pr-0 text-right')}>{t('th_delivered_qty')}</th>
</tr>
</thead>
<tbody>
{lines.map((item) => (
<tr key={item.id}>
<td className={cn(TD_CLASS, 'pl-0')}>
<span className="block truncate">{item.description}</span>
</td>
<td className={cn(TD_CLASS, 'text-right tabular-nums text-muted-foreground')}>
{formatQty(item.quantity)} {item.unit}
</td>
<td className={cn(TD_CLASS, 'pr-0 text-right')}>
<Input
type="number"
inputMode="decimal"
step="any"
min={0}
value={quantities[item.id] ?? ''}
onChange={(e) =>
setQuantities((prev) => ({ ...prev, [item.id]: e.target.value }))
}
aria-label={`${t('th_delivered_qty')}: ${item.description}`}
className="ml-auto h-8 w-24 text-right tabular-nums"
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
<Button type="button" variant="ghost" size="sm" onClick={deliverAll} className="text-muted-foreground">
{t('deliver_all')}
</Button>
</div>
<DialogFooter>
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
{tCommon('cancel')}
</Button>
<Button type="button" onClick={handleSubmit} disabled={isSubmitting || lines.length === 0}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('delivery_submit')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+615
View File
@@ -0,0 +1,615 @@
'use client'
import { useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { Loader2, Plus, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { DetailSection } from '@/components/ui/detail-section'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { useToast } from '@/components/ui/use-toast'
import ArticleCombobox from '@/components/invoices/ArticleCombobox'
import { resolveLineVatRates, FALLBACK_VAT_RATE } from '@/components/invoices/line-vat-rates'
import { useArticles, useCustomers } from '@/lib/reference-data/hooks'
import { sortArticles } from '@/lib/articles/sort'
import { computeLineNet } from '@/lib/invoices/line-amounts'
import { roundOre } from '@/lib/money'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { cn, formatCurrency } from '@/lib/utils'
import { formatQty, todayIso } from '@/components/sales-orders/labels'
import type { Article, SalesOrder, SalesOrderItem, SalesOrderItemInput } from '@/types'
// The invoice editor's currency set (CurrencySchema in lib/api/schemas.ts).
const CURRENCIES = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'] as const
// Dense-row cell controls: same vocabulary as the invoice editor's line grid
// (rounded-sm leaves inside the table surface, hairline-free until focus).
const CELL_INPUT_CLASS =
'h-8 rounded-sm border border-transparent bg-transparent px-2 py-1 text-[13px] transition-colors duration-150 hover:bg-secondary/40 focus-visible:bg-background focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring placeholder:text-muted-foreground/60'
const CELL_SELECT_TRIGGER_CLASS =
'h-8 w-auto gap-1 rounded-sm border-transparent bg-transparent px-2 py-1 text-[13px] shadow-none hover:bg-secondary/40 tabular-nums'
interface LineState {
key: string
id?: string
line_type: 'product' | 'text'
description: string
// Numeric fields are held as strings so the inputs stay controlled while
// the user types ("1." or "" are valid intermediate states).
quantity: string
unit: string
unit_price: string
discount_percent: string
vat_rate: number
article_id: string | null
revenue_account: string | null
// Edit mode: what has already been invoiced on this line (read-only hint).
invoiced_qty?: number
}
interface SalesOrderFormProps {
mode: 'create' | 'edit'
initial?: SalesOrder
}
let keyCounter = 0
function nextKey(): string {
keyCounter += 1
return `line-${keyCounter}`
}
function parseNumber(value: string): number {
const n = parseFloat(value.replace(',', '.'))
return Number.isFinite(n) ? n : 0
}
function lineFromItem(item: SalesOrderItem): LineState {
return {
key: nextKey(),
id: item.id,
line_type: item.line_type ?? 'product',
description: item.description,
quantity: String(item.quantity),
unit: item.unit,
unit_price: String(item.unit_price),
discount_percent: item.discount_percent > 0 ? String(item.discount_percent) : '',
vat_rate: item.vat_rate,
article_id: item.article_id,
revenue_account: item.revenue_account,
invoiced_qty: item.invoiced_qty,
}
}
function blankProductLine(vatRate: number): LineState {
return {
key: nextKey(),
line_type: 'product',
description: '',
quantity: '1',
unit: 'st',
unit_price: '',
discount_percent: '',
vat_rate: vatRate,
article_id: null,
revenue_account: null,
}
}
function blankTextLine(): LineState {
return {
key: nextKey(),
line_type: 'text',
description: '',
quantity: '0',
unit: '',
unit_price: '0',
discount_percent: '',
vat_rate: 0,
article_id: null,
revenue_account: null,
}
}
/**
* Create/edit form for a kundorder. A lighter sibling of the invoice editor:
* same customer picker, same article prefill and per-line VAT plan, same
* line math (computeLineNet), minus everything invoice-only (ROT/RUT,
* periodisering, payment links). POST on create, PATCH on edit; existing
* line ids ride along on edit so delivered/invoiced history survives.
*/
export default function SalesOrderForm({ mode, initial }: SalesOrderFormProps) {
const t = useTranslations('sales_order_form')
const tCommon = useTranslations('common')
const errorLocale = useLocale() as ErrorLocale
const router = useRouter()
const { toast } = useToast()
const { customers, isLoading: customersLoading } = useCustomers()
const { articles: articleRows } = useArticles()
const articles = useMemo(
() => sortArticles(articleRows.filter((a) => a.active !== false)),
[articleRows],
)
const [customerId, setCustomerId] = useState<string>(initial?.customer_id ?? '')
const [orderDate, setOrderDate] = useState<string>(initial?.order_date ?? todayIso())
const [requestedDeliveryDate, setRequestedDeliveryDate] = useState<string>(
initial?.requested_delivery_date ?? '',
)
const [currency, setCurrency] = useState<string>(initial?.currency ?? 'SEK')
const [yourReference, setYourReference] = useState<string>(initial?.your_reference ?? '')
const [ourReference, setOurReference] = useState<string>(initial?.our_reference ?? '')
const [notes, setNotes] = useState<string>(initial?.notes ?? '')
const [lines, setLines] = useState<LineState[]>(() => {
const items = [...(initial?.items ?? [])].sort((a, b) => a.sort_order - b.sort_order)
return items.length > 0 ? items.map(lineFromItem) : [blankProductLine(FALLBACK_VAT_RATE)]
})
const [errors, setErrors] = useState<{ customer?: string; lines?: string }>({})
const [isSubmitting, setIsSubmitting] = useState(false)
const selectedCustomer = useMemo(
() => customers.find((c) => c.id === customerId) ?? null,
[customers, customerId],
)
// The lawful VAT set for the picked customer (0% first for a foreign
// business); before a customer is picked, the domestic set.
const vatPlan = useMemo(() => resolveLineVatRates(selectedCustomer), [selectedCustomer])
const vatOptions = vatPlan.options.length > 0
? vatPlan.options
: resolveLineVatRates({ customer_type: 'swedish_business', vat_number_validated: false }).options
function updateLine(key: string, patch: Partial<LineState>) {
setLines((prev) => prev.map((l) => (l.key === key ? { ...l, ...patch } : l)))
}
function removeLine(key: string) {
setLines((prev) => (prev.length > 1 ? prev.filter((l) => l.key !== key) : prev))
}
function applyArticle(key: string, value: string) {
if (value === 'none') {
updateLine(key, { article_id: null, revenue_account: null })
return
}
const article = articles.find((a) => a.id === value) as Article | undefined
if (!article) return
const rateAllowed = vatOptions.some((o) => o.rate === article.vat_rate)
updateLine(key, {
article_id: article.id,
description: article.name,
unit: article.unit,
unit_price: String(article.price_excl_vat),
vat_rate: rateAllowed ? article.vat_rate : vatPlan.defaultRate,
revenue_account: article.revenue_account,
})
}
function handleCustomerChange(nextId: string) {
const previousDefault = vatPlan.defaultRate
setCustomerId(nextId)
const nextCustomer = customers.find((c) => c.id === nextId) ?? null
const nextDefault = resolveLineVatRates(nextCustomer).defaultRate
// Only lines still on the previous default follow the customer switch;
// an explicitly chosen rate is left alone (same rule as the invoice editor).
if (nextDefault !== previousDefault) {
setLines((prev) =>
prev.map((l) =>
l.line_type === 'product' && l.vat_rate === previousDefault
? { ...l, vat_rate: nextDefault }
: l,
),
)
}
}
// Client-side totals, same öre-exact formulas as the server.
const totals = useMemo(() => {
let subtotal = 0
let vat = 0
for (const l of lines) {
if (l.line_type === 'text') continue
const net = computeLineNet(
parseNumber(l.quantity),
parseNumber(l.unit_price),
l.discount_percent ? parseNumber(l.discount_percent) : null,
)
subtotal = roundOre(subtotal + net)
vat = roundOre(vat + roundOre((net * l.vat_rate) / 100))
}
return { subtotal, vat, total: roundOre(subtotal + vat) }
}, [lines])
function lineNet(l: LineState): number {
if (l.line_type === 'text') return 0
return computeLineNet(
parseNumber(l.quantity),
parseNumber(l.unit_price),
l.discount_percent ? parseNumber(l.discount_percent) : null,
)
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const nextErrors: { customer?: string; lines?: string } = {}
if (!customerId) nextErrors.customer = t('validation_customer_required')
const productLines = lines.filter((l) => l.line_type === 'product')
if (productLines.length === 0 || productLines.some((l) => !l.description.trim())) {
nextErrors.lines = t('validation_lines_required')
}
setErrors(nextErrors)
if (nextErrors.customer || nextErrors.lines) return
const items: SalesOrderItemInput[] = lines.map((l) => ({
...(l.id ? { id: l.id } : {}),
line_type: l.line_type,
description: l.description,
quantity: l.line_type === 'text' ? 0 : parseNumber(l.quantity),
unit: l.line_type === 'text' ? '' : l.unit,
unit_price: l.line_type === 'text' ? 0 : parseNumber(l.unit_price),
discount_percent:
l.line_type === 'text' || !l.discount_percent ? null : parseNumber(l.discount_percent),
vat_rate: l.line_type === 'text' ? 0 : l.vat_rate,
article_id: l.article_id,
revenue_account: l.revenue_account,
}))
const body = {
customer_id: customerId,
order_date: orderDate,
requested_delivery_date: requestedDeliveryDate || null,
currency,
your_reference: yourReference.trim() || null,
our_reference: ourReference.trim() || null,
notes: notes.trim() || null,
items,
}
setIsSubmitting(true)
try {
const url = mode === 'edit' && initial ? `/api/sales-orders/${initial.id}` : '/api/sales-orders'
const response = await fetch(url, {
method: mode === 'edit' ? 'PATCH' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const json = await response.json().catch(() => null)
if (!response.ok) {
toast({
title: mode === 'edit' ? t('update_failed_title') : t('create_failed_title'),
description: getErrorMessage(json, { locale: errorLocale, statusCode: response.status }),
variant: 'destructive',
})
return
}
const order = json?.data as SalesOrder
toast({
title:
mode === 'edit'
? t('updated_title')
: t('created_title', { number: order.order_number ?? '' }),
})
router.push(`/sales-orders/${order.id}`)
} catch (err) {
toast({
title: mode === 'edit' ? t('update_failed_title') : t('create_failed_title'),
description: getErrorMessage(err, { locale: errorLocale }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-8" noValidate>
<DetailSection kicker={t('section_customer')}>
<div className="max-w-md">
<Select value={customerId} onValueChange={handleCustomerChange}>
<SelectTrigger className="h-12 font-display text-base" aria-required="true" aria-invalid={errors.customer ? true : undefined}>
<SelectValue placeholder={t('select_customer_placeholder')} />
</SelectTrigger>
<SelectContent>
{customers.length === 0 && (
<div className="px-3 py-2 text-[13px] text-muted-foreground">
{customersLoading ? t('loading_customers') : t('no_customers_yet')}
</div>
)}
{customers.map((customer) => (
<SelectItem key={customer.id} value={customer.id}>
{customer.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.customer && <p className="mt-2 text-sm text-destructive">{errors.customer}</p>}
</div>
</DetailSection>
<DetailSection kicker={t('section_details')}>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="so-order-date">{t('order_date_label')}</Label>
<Input
id="so-order-date"
type="date"
value={orderDate}
onChange={(e) => setOrderDate(e.target.value)}
className="tabular-nums"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="so-delivery-date">{t('requested_delivery_date_label')}</Label>
<Input
id="so-delivery-date"
type="date"
value={requestedDeliveryDate}
onChange={(e) => setRequestedDeliveryDate(e.target.value)}
className="tabular-nums"
/>
</div>
<div className="space-y-2">
<Label htmlFor="so-currency">{t('currency_label')}</Label>
<Select value={currency} onValueChange={setCurrency}>
<SelectTrigger id="so-currency">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CURRENCIES.map((code) => (
<SelectItem key={code} value={code}>
{code}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="so-your-ref">{t('your_reference_label')}</Label>
<Input
id="so-your-ref"
value={yourReference}
onChange={(e) => setYourReference(e.target.value)}
maxLength={200}
/>
</div>
<div className="space-y-2">
<Label htmlFor="so-our-ref">{t('our_reference_label')}</Label>
<Input
id="so-our-ref"
value={ourReference}
onChange={(e) => setOurReference(e.target.value)}
maxLength={200}
/>
</div>
<div className="space-y-2 sm:col-span-2 lg:col-span-3">
<Label htmlFor="so-notes">{t('notes_label')}</Label>
<Textarea
id="so-notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
maxLength={4000}
/>
</div>
</div>
</DetailSection>
<DetailSection kicker={t('section_lines')}>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'pl-0')}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_quantity')}</th>
<th className={TH_CLASS}>{t('th_unit')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_unit_price')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_discount')}</th>
<th className={TH_CLASS}>{t('th_vat')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_amount')}</th>
<th className={cn(TH_CLASS, 'pr-0')}>
<span className="sr-only">{t('remove_row')}</span>
</th>
</tr>
</thead>
<tbody>
{lines.map((line) => {
const isText = line.line_type === 'text'
return (
<tr key={line.key} className="align-top">
<td className={cn(TD_CLASS, 'pl-0')}>
{isText ? (
<Input
value={line.description}
onChange={(e) => updateLine(line.key, { description: e.target.value })}
placeholder={t('text_row_placeholder')}
aria-label={t('th_description')}
className={cn(CELL_INPUT_CLASS, 'w-full min-w-[16rem] text-muted-foreground')}
maxLength={2000}
/>
) : (
<div className="min-w-[16rem] space-y-1">
<Input
value={line.description}
onChange={(e) => updateLine(line.key, { description: e.target.value })}
placeholder={t('description_placeholder')}
aria-label={t('th_description')}
className={cn(CELL_INPUT_CLASS, 'w-full')}
maxLength={2000}
/>
{articles.length > 0 && (
<div className="max-w-xs">
<ArticleCombobox
value={line.article_id}
articles={articles}
onChange={(v) => applyArticle(line.key, v)}
freeTextLabel={t('article_free_text')}
placeholder={t('article_placeholder')}
emptyLabel={t('article_search_empty')}
ariaLabel={t('article_label')}
/>
</div>
)}
{typeof line.invoiced_qty === 'number' && line.invoiced_qty > 0 && (
<p className="px-2 text-xs text-muted-foreground tabular-nums">
{t('invoiced_hint', { qty: formatQty(line.invoiced_qty) })}
</p>
)}
</div>
)}
</td>
<td className={cn(TD_CLASS, 'text-right')}>
{!isText && (
<Input
type="number"
inputMode="decimal"
step="any"
min={0}
value={line.quantity}
onChange={(e) => updateLine(line.key, { quantity: e.target.value })}
aria-label={t('th_quantity')}
className={cn(CELL_INPUT_CLASS, 'w-20 text-right tabular-nums')}
/>
)}
</td>
<td className={TD_CLASS}>
{!isText && (
<Input
value={line.unit}
onChange={(e) => updateLine(line.key, { unit: e.target.value })}
aria-label={t('th_unit')}
className={cn(CELL_INPUT_CLASS, 'w-16')}
maxLength={32}
/>
)}
</td>
<td className={cn(TD_CLASS, 'text-right')}>
{!isText && (
<Input
type="number"
inputMode="decimal"
step="any"
value={line.unit_price}
onChange={(e) => updateLine(line.key, { unit_price: e.target.value })}
aria-label={t('th_unit_price')}
className={cn(CELL_INPUT_CLASS, 'w-28 text-right tabular-nums')}
/>
)}
</td>
<td className={cn(TD_CLASS, 'text-right')}>
{!isText && (
<Input
type="number"
inputMode="decimal"
step="any"
min={0}
max={100}
value={line.discount_percent}
onChange={(e) => updateLine(line.key, { discount_percent: e.target.value })}
aria-label={t('th_discount')}
className={cn(CELL_INPUT_CLASS, 'w-20 text-right tabular-nums')}
/>
)}
</td>
<td className={TD_CLASS}>
{!isText && (
<Select
value={String(line.vat_rate)}
onValueChange={(v) => updateLine(line.key, { vat_rate: Number(v) })}
disabled={vatPlan.isPickerLocked}
>
<SelectTrigger className={CELL_SELECT_TRIGGER_CLASS} aria-label={t('th_vat')}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{vatOptions.map((opt) => (
<SelectItem key={opt.rate} value={String(opt.rate)}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
{!isText && formatCurrency(lineNet(line), currency)}
</td>
<td className={cn(TD_CLASS, 'pr-0 text-right')}>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeLine(line.key)}
disabled={lines.length <= 1}
aria-label={t('remove_row')}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
{errors.lines && <p className="mt-2 text-sm text-destructive">{errors.lines}</p>}
<div className="mt-4 flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setLines((prev) => [...prev, blankProductLine(vatPlan.defaultRate)])}
>
<Plus className="mr-2 h-4 w-4" />
{t('add_row')}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setLines((prev) => [...prev, blankTextLine()])}
className="text-muted-foreground"
>
{t('add_text_row')}
</Button>
</div>
<div className="mt-6 ml-auto w-full max-w-xs space-y-1 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">{t('subtotal')}</span>
<span className="tabular-nums">{formatCurrency(totals.subtotal, currency)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('vat')}</span>
<span className="tabular-nums">{formatCurrency(totals.vat, currency)}</span>
</div>
<div className="flex justify-between border-t border-border pt-2">
<span>{t('total')}</span>
<span className="font-display text-xl tabular-nums">{formatCurrency(totals.total, currency)}</span>
</div>
</div>
</DetailSection>
<div className="flex flex-wrap items-center justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()} disabled={isSubmitting}>
{tCommon('cancel')}
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{mode === 'edit' ? t('submit_edit') : t('submit_create')}
</Button>
</div>
</form>
)
}
+47
View File
@@ -0,0 +1,47 @@
import type { SalesOrderProgress, SalesOrderStatus } from '@/types'
/**
* Presentation maps for kundorder status and progress. Chips mark exceptions
* (design.md convention 5): a draft and a cancelled order deviate from the
* normal flow and get a Badge; confirmed and completed render as muted text.
*/
export const STATUS_LABEL_KEY: Record<SalesOrderStatus, string> = {
draft: 'status_draft',
confirmed: 'status_confirmed',
completed: 'status_completed',
cancelled: 'status_cancelled',
}
export const STATUS_BADGE_VARIANT: Partial<
Record<SalesOrderStatus, 'outline' | 'destructive'>
> = {
draft: 'outline',
cancelled: 'destructive',
}
export const DELIVERY_LABEL_KEY: Record<SalesOrderProgress, string> = {
none: 'delivery_none',
partial: 'delivery_partial',
full: 'delivery_full',
}
export const INVOICING_LABEL_KEY: Record<SalesOrderProgress, string> = {
none: 'invoicing_none',
partial: 'invoicing_partial',
full: 'invoicing_full',
}
/** Today as an ISO calendar date in the browser's local timezone. */
export function todayIso(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
/** Renders a quantity without trailing zeros (2 -> "2", 2.5 -> "2,5" via toLocaleString). */
export function formatQty(n: number | null | undefined): string {
if (n == null || Number.isNaN(n)) return '0'
return n.toLocaleString('sv-SE', { maximumFractionDigits: 3 })
}
+102
View File
@@ -0,0 +1,102 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import { ExternalLink } from 'lucide-react'
import { Switch } from '@/components/ui/switch'
import { useToast } from '@/components/ui/use-toast'
import {
SettingsRow,
SettingsRowEnd,
} from '@/components/settings/SettingsRows'
import { useSettings } from '@/components/settings/useSettings'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { cn } from '@/lib/utils'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
/**
* Company-level toggle for Kundorder (sales orders). Persists
* company_settings.sales_orders_enabled through the standard settings PUT:
* the flag gates UI visibility only (the nav row), never correctness. Orders
* created via API/MCP work regardless, and the /sales-orders pages stay
* reachable by URL, so turning this off never hides existing orders.
*/
export function SalesOrdersToggle() {
const t = useTranslations('sales_orders')
const errorLocale = useLocale() as ErrorLocale
const { settings, updateSettings } = useSettings()
const { canWrite } = useCanWrite()
const { toast } = useToast()
const router = useRouter()
const [isSaving, setIsSaving] = useState(false)
const enabled = settings?.sales_orders_enabled ?? false
async function handleChange(next: boolean) {
setIsSaving(true)
try {
const res = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sales_orders_enabled: next }),
})
const json = await res.json().catch(() => null)
if (!res.ok) {
toast({
title: t('settings_save_failed_title'),
description: getErrorMessage(json, { locale: errorLocale }),
variant: 'destructive',
})
return
}
updateSettings({ sales_orders_enabled: next })
// The nav row is gated by the server-rendered dashboard layout, so the
// SWR patch alone leaves the Kundorder row hidden until a reload.
router.refresh()
} catch (err) {
// A rejected fetch (offline, DNS failure, aborted request) never reaches
// the !res.ok arm above, and the switch is controlled by the settings
// context, so it simply stays where it was: without this toast the click
// looks like a dead control rather than a save that did not happen.
toast({
title: t('settings_save_failed_title'),
description: getErrorMessage(err, { locale: errorLocale }),
variant: 'destructive',
})
} finally {
setIsSaving(false)
}
}
const locked = isSaving || !canWrite
return (
<SettingsRow label={t('settings_heading')} help={t('settings_toggle_help')}>
<Switch
id="sales-orders-enabled"
checked={enabled}
onCheckedChange={(next) => void handleChange(next)}
disabled={locked}
/>
<label
htmlFor="sales-orders-enabled"
className={cn('text-sm', locked ? 'text-muted-foreground' : 'cursor-pointer')}
>
{t('settings_toggle_label')}
</label>
{enabled && (
<SettingsRowEnd>
<Link
href="/sales-orders"
className="inline-flex items-center gap-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('settings_open_page')}
</Link>
</SettingsRowEnd>
)}
</SettingsRow>
)
}
@@ -14,6 +14,7 @@ import { VoucherSeriesPerCashAccountForm } from '@/components/settings/VoucherSe
import { applyDefaultSeriesToMap } from '@/lib/bookkeeping/voucher-series-resolver'
import { DimensionsToggle } from '@/components/settings/DimensionsToggle'
import { MileageToggle } from '@/components/settings/MileageToggle'
import { SalesOrdersToggle } from '@/components/settings/SalesOrdersToggle'
import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm'
import {
SettingsGroup,
@@ -189,6 +190,7 @@ export function BookkeepingSettingsContent() {
</SettingsRow>
<DimensionsToggle />
<MileageToggle />
<SalesOrdersToggle />
</SettingsGroup>
<SettingsGroup>
@@ -0,0 +1,401 @@
/**
* Unit tests for the kundorder (sales order) MCP tools: registration,
* scope/risk/catalog wiring, the staging-time refusals, and the dry-run
* previews. The lib/sales-orders loaders are mocked; the commit executors
* are covered in lib/pending-operations/__tests__/sales-order-executors.test.ts.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, makeCustomer } from '@/tests/helpers'
import type { SalesOrder, SalesOrderItem } from '@/types'
vi.mock('@/lib/sales-orders/load', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/sales-orders/load')>()),
loadSalesOrder: vi.fn(),
fetchInvoicedQuantities: vi.fn(),
}))
vi.mock('@/lib/sales-orders/write', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/sales-orders/write')>()),
hasOpenInvoices: vi.fn(),
}))
import { loadSalesOrder, fetchInvoicedQuantities } from '@/lib/sales-orders/load'
import { hasOpenInvoices } from '@/lib/sales-orders/write'
import { tools, isDefaultCatalogTool } from '../server'
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
import { OPERATION_RISK_TIERS } from '@/lib/pending-operations/risk-tiers'
const byName = (name: string) => tools.find((t) => t.name === name)!
const ORDER_ID = '00000000-0000-4000-8000-0000000000aa'
const CUSTOMER_ID = '00000000-0000-4000-8000-0000000000bb'
const ITEM_ID = '00000000-0000-4000-8000-0000000000cc'
const TEXT_ID = '00000000-0000-4000-8000-0000000000ce'
function makeItem(overrides: Partial<SalesOrderItem> = {}): SalesOrderItem {
return {
id: ITEM_ID,
company_id: 'company-1',
sales_order_id: ORDER_ID,
sort_order: 0,
line_type: 'product',
description: 'Konsulttimmar',
quantity: 10,
delivered_qty: 0,
unit: 'tim',
unit_price: 100,
discount_percent: 0,
vat_rate: 25,
line_total: 1000,
article_id: null,
revenue_account: null,
dimensions: {},
created_at: '2026-09-01T00:00:00Z',
updated_at: '2026-09-01T00:00:00Z',
invoiced_qty: 0,
remaining_qty: 10,
...overrides,
}
}
function makeOrder(overrides: Partial<SalesOrder> = {}): SalesOrder {
return {
id: ORDER_ID,
company_id: 'company-1',
user_id: 'user-1',
customer_id: CUSTOMER_ID,
order_number: 'OR-7',
status: 'confirmed',
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: '2026-09-01T00:00:00Z',
completed_at: null,
cancelled_at: null,
created_at: '2026-09-01T00:00:00Z',
updated_at: '2026-09-01T00:00:00Z',
customer: makeCustomer({ id: CUSTOMER_ID, name: 'Testbrand AB', default_payment_terms: 30 }),
items: [makeItem()],
delivery_progress: 'none',
invoicing_progress: 'none',
...overrides,
}
}
const WRITE_TOOLS = [
'gnubok_create_sales_order',
'gnubok_transition_sales_order',
'gnubok_register_sales_order_delivery',
'gnubok_create_invoice_from_sales_order',
]
const READ_TOOLS = ['gnubok_list_sales_orders', 'gnubok_get_sales_order']
beforeEach(() => {
vi.clearAllMocks()
})
describe('sales order tools: registration', () => {
it('registers all six tools with strict input schemas', () => {
for (const name of [...READ_TOOLS, ...WRITE_TOOLS]) {
const tool = byName(name)
expect(tool, name).toBeDefined()
expect((tool.inputSchema as { additionalProperties?: boolean }).additionalProperties, name).toBe(false)
}
})
it('keeps the list read in the default catalog and the rest search-only (tools/list budget)', () => {
expect(isDefaultCatalogTool(byName('gnubok_list_sales_orders'))).toBe(true)
expect(isDefaultCatalogTool(byName('gnubok_get_sales_order'))).toBe(false)
for (const name of WRITE_TOOLS) expect(isDefaultCatalogTool(byName(name)), name).toBe(false)
})
it('maps reads to invoices:read and writes to invoices:write', () => {
for (const name of READ_TOOLS) expect(TOOL_SCOPE_MAP[name], name).toBe('invoices:read')
for (const name of WRITE_TOOLS) expect(TOOL_SCOPE_MAP[name], name).toBe('invoices:write')
})
it('every write stages (staged output schema + prose) and carries the expected risk tier', () => {
for (const name of WRITE_TOOLS) {
const tool = byName(name)
expect((tool.outputSchema as { required?: string[] })?.required, name).toContain('staged')
expect(tool.description, name).toMatch(/stag(e|ing)/i)
expect(tool.annotations.readOnlyHint, name).toBe(false)
}
expect(OPERATION_RISK_TIERS.create_sales_order).toBe('low')
expect(OPERATION_RISK_TIERS.transition_sales_order).toBe('low')
expect(OPERATION_RISK_TIERS.register_sales_order_delivery).toBe('low')
expect(OPERATION_RISK_TIERS.create_invoice_from_sales_order).toBe('medium')
})
})
describe('gnubok_list_sales_orders', () => {
it('returns qualified ids with derived progress and pagination', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: [
{
id: ORDER_ID,
order_number: 'OR-7',
status: 'confirmed',
customer_id: CUSTOMER_ID,
order_date: '2026-09-01',
requested_delivery_date: null,
last_delivery_date: '2026-09-02',
currency: 'SEK',
subtotal: 1000,
vat_amount: 250,
total: 1250,
customer: { name: 'Testbrand AB' },
items: [{ id: ITEM_ID, line_type: 'product', quantity: 10, delivered_qty: 4, sort_order: 0 }],
},
],
count: 1,
})
vi.mocked(fetchInvoicedQuantities).mockResolvedValue({ ok: true, byItem: new Map([[ITEM_ID, 10]]) })
const result = (await byName('gnubok_list_sales_orders').execute(
{ status: 'confirmed' }, 'company-1', 'user-1', supabase as never,
)) as { sales_orders: Record<string, unknown>[]; count: number; total_count: number; has_more: boolean }
expect(result.count).toBe(1)
expect(result.total_count).toBe(1)
expect(result.has_more).toBe(false)
expect(result.sales_orders[0]).toMatchObject({
sales_order_id: ORDER_ID,
order_number: 'OR-7',
customer_name: 'Testbrand AB',
delivery_progress: 'partial',
invoicing_progress: 'full',
line_count: 1,
})
expect(result.sales_orders[0]).not.toHaveProperty('id')
expect(fetchInvoicedQuantities).toHaveBeenCalledWith(supabase, [ORDER_ID])
})
it('rejects an unknown status before any DB call', async () => {
const noop = { from: vi.fn() }
await expect(
byName('gnubok_list_sales_orders').execute({ status: 'shipped' }, 'company-1', 'user-1', noop as never),
).rejects.toThrow(/Invalid status/)
expect(noop.from).not.toHaveBeenCalled()
})
})
describe('gnubok_get_sales_order', () => {
it('returns the decorated order with qualified line ids and its invoices', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: [{ id: 'inv-1', invoice_number: null, status: 'draft', invoice_date: '2026-09-02', total: 500, currency: 'SEK' }] })
const result = (await byName('gnubok_get_sales_order').execute(
{ sales_order_id: ORDER_ID }, 'company-1', 'user-1', supabase as never,
)) as Record<string, unknown>
expect(result).toMatchObject({ sales_order_id: ORDER_ID, status: 'confirmed', item_count: 1 })
expect((result.items as Record<string, unknown>[])[0]).toMatchObject({
sales_order_item_id: ITEM_ID,
invoiced_qty: 0,
remaining_qty: 10,
})
expect((result.invoices as Record<string, unknown>[])[0]).toMatchObject({ invoice_id: 'inv-1', status: 'draft' })
})
it('maps SALES_ORDER_NOT_FOUND onto a not-found error with a remediation hint', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
await expect(
byName('gnubok_get_sales_order').execute({ sales_order_id: ORDER_ID }, 'company-1', 'user-1', {} as never),
).rejects.toThrow(/not found.*gnubok_list_sales_orders/i)
})
})
describe('gnubok_create_sales_order', () => {
it('dry run: previews totals from the shared line math and stages nothing', async () => {
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
enqueue({ data: makeCustomer({ id: CUSTOMER_ID, name: 'Testbrand AB', customer_type: 'swedish_business', vat_number_validated: false }) })
const result = (await byName('gnubok_create_sales_order').execute(
{
customer_id: CUSTOMER_ID,
items: [
{ description: 'Konsulttimmar', quantity: 10, unit: 'tim', unit_price: 100, discount_percent: 10 },
{ line_type: 'text', description: 'Enligt offert' },
],
dry_run: true,
},
'company-1', 'user-1', supabase as never,
)) as { staged: boolean; dry_run?: boolean; preview: Record<string, unknown> }
expect(result.staged).toBe(false)
expect(result.dry_run).toBe(true)
// 10 x 100 net of 10 % = 900; 25 % VAT = 225.
expect(result.preview).toMatchObject({ customer_name: 'Testbrand AB', subtotal: 900, vat_amount: 225, total: 1125, currency: 'SEK' })
expect((result.preview.items as Record<string, unknown>[])[0]).toMatchObject({ line_total: 900, vat_rate: 25 })
expect((result.preview.items as Record<string, unknown>[])[1]).toMatchObject({ line_type: 'text', line_total: 0 })
expect(findCalls('pending_operations', 'insert')).toEqual([])
})
it('refuses a VAT rate outside the customer permitted set (same gate as the service)', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: makeCustomer({ id: CUSTOMER_ID, customer_type: 'swedish_business', vat_number_validated: false }) })
await expect(
byName('gnubok_create_sales_order').execute(
{ customer_id: CUSTOMER_ID, items: [{ description: 'X', quantity: 1, unit: 'st', unit_price: 100, vat_rate: 7 }], dry_run: true },
'company-1', 'user-1', supabase as never,
),
).rejects.toThrow(/INVOICE_CREATE_VAT_RULE_VIOLATION/)
})
})
describe('gnubok_transition_sales_order', () => {
it('refuses cancel while invoices exist (SALES_ORDER_HAS_INVOICES)', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
vi.mocked(hasOpenInvoices).mockResolvedValue({ ok: true, open: true })
await expect(
byName('gnubok_transition_sales_order').execute(
{ sales_order_id: ORDER_ID, action: 'cancel', dry_run: true }, 'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_HAS_INVOICES/)
})
it('refuses a transition the current status does not allow', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'confirmed' }) })
await expect(
byName('gnubok_transition_sales_order').execute(
{ sales_order_id: ORDER_ID, action: 'confirm', dry_run: true }, 'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_INVALID_STATE/)
})
it('dry run: previews confirm on a draft', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'draft', confirmed_at: null }) })
const { supabase } = createQueuedMockSupabase()
const result = (await byName('gnubok_transition_sales_order').execute(
{ sales_order_id: ORDER_ID, action: 'confirm', dry_run: true }, 'company-1', 'user-1', supabase as never,
)) as { staged: boolean; risk_level: string; preview: Record<string, unknown> }
expect(result.staged).toBe(false)
expect(result.risk_level).toBe('low')
expect(result.preview).toMatchObject({ current_status: 'draft', new_status: 'confirmed', order_number: 'OR-7' })
})
})
describe('gnubok_register_sales_order_delivery', () => {
it('refuses delivered_qty above the ordered quantity', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
await expect(
byName('gnubok_register_sales_order_delivery').execute(
{ sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 11 }], dry_run: true },
'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_OVER_DELIVERED/)
})
it('refuses delivery on a draft order', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'draft' }) })
await expect(
byName('gnubok_register_sales_order_delivery').execute(
{ sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 1 }], dry_run: true },
'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_INVALID_STATE/)
})
it('dry run: previews the cumulative delivery per line and skips text rows', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({
ok: true,
order: makeOrder({
items: [makeItem({ delivered_qty: 4 }), makeItem({ id: TEXT_ID, line_type: 'text', quantity: 0, sort_order: 1 })],
}),
})
const { supabase } = createQueuedMockSupabase()
const result = (await byName('gnubok_register_sales_order_delivery').execute(
{
sales_order_id: ORDER_ID,
delivery_date: '2026-09-03',
lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 7 }, { sales_order_item_id: TEXT_ID, delivered_qty: 0 }],
dry_run: true,
},
'company-1', 'user-1', supabase as never,
)) as { staged: boolean; preview: { lines: Record<string, unknown>[]; delivery_date: string } }
expect(result.staged).toBe(false)
expect(result.preview.delivery_date).toBe('2026-09-03')
expect(result.preview.lines).toHaveLength(1)
expect(result.preview.lines[0]).toMatchObject({ sales_order_item_id: ITEM_ID, delivered_before: 4, delivered_after: 7, delta: 3 })
})
})
describe('gnubok_create_invoice_from_sales_order', () => {
it('refuses a draft order with a confirm hint', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'draft' }) })
await expect(
byName('gnubok_create_invoice_from_sales_order').execute(
{ sales_order_id: ORDER_ID, dry_run: true }, 'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_INVALID_STATE.*gnubok_transition_sales_order/)
})
it('refuses when nothing is left to invoice', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({
ok: true,
order: makeOrder({ items: [makeItem({ invoiced_qty: 10, remaining_qty: 0 })] }),
})
await expect(
byName('gnubok_create_invoice_from_sales_order').execute(
{ sales_order_id: ORDER_ID, dry_run: true }, 'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_NOTHING_TO_INVOICE/)
})
it('refuses an explicit pick above remaining_qty', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({
ok: true,
order: makeOrder({ items: [makeItem({ invoiced_qty: 8, remaining_qty: 2 })] }),
})
await expect(
byName('gnubok_create_invoice_from_sales_order').execute(
{ sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, quantity: 3 }], dry_run: true },
'company-1', 'user-1', {} as never,
),
).rejects.toThrow(/SALES_ORDER_OVER_INVOICED/)
})
it('dry run: previews the delivered-not-invoiced quantities with line totals and due date', async () => {
vi.mocked(loadSalesOrder).mockResolvedValue({
ok: true,
order: makeOrder({ last_delivery_date: '2026-09-02', items: [makeItem({ delivered_qty: 4, invoiced_qty: 1, remaining_qty: 9 })] }),
})
const { supabase, findCalls } = createQueuedMockSupabase()
const result = (await byName('gnubok_create_invoice_from_sales_order').execute(
{ sales_order_id: ORDER_ID, mode: 'delivered', invoice_date: '2026-09-05', dry_run: true },
'company-1', 'user-1', supabase as never,
)) as { staged: boolean; risk_level: string; preview: Record<string, unknown> }
expect(result.staged).toBe(false)
expect(result.risk_level).toBe('medium')
// delivered 4 - invoiced 1 = 3 x 100 = 300 net, 75 VAT.
expect(result.preview).toMatchObject({
mode: 'delivered',
subtotal: 300,
vat_amount: 75,
total: 375,
invoice_date: '2026-09-05',
due_date: '2026-10-05',
delivery_date: '2026-09-02',
})
expect((result.preview.items as Record<string, unknown>[])[0]).toMatchObject({
sales_order_item_id: ITEM_ID,
quantity: 3,
line_total: 300,
remaining_after: 6,
})
expect(findCalls('pending_operations', 'insert')).toEqual([])
})
})
+839 -3
View File
@@ -220,7 +220,18 @@ import { findMatchingInvoices } from '@/lib/invoices/invoice-matching'
import { sanitizeDeliveryRecipientStatuses } from '@/lib/invoices/delivery-recipient-statuses'
import { listRotRutCandidates, createRotRutPayoutRequest } from '@/lib/invoices/rot-rut-service'
import { importRotRutBeslutFile } from '@/lib/invoices/rot-rut-beslut-import'
import { RotRutBeslutFileSchema } from '@/lib/api/schemas'
import {
CreateInvoiceFromSalesOrderSchema,
CreateSalesOrderSchema,
RegisterSalesOrderDeliverySchema,
RotRutBeslutFileSchema,
SalesOrderTransitionSchema,
} from '@/lib/api/schemas'
import { decorate as decorateSalesOrder, fetchInvoicedQuantities, loadSalesOrder } from '@/lib/sales-orders/load'
import { normalizeSalesOrderLines } from '@/lib/sales-orders/lines'
import { hasOpenInvoices } from '@/lib/sales-orders/write'
import { pickLines } from '@/lib/sales-orders/create-invoice-from-order'
import type { ServiceFailure } from '@/lib/sales-orders/result'
import {
findMatchingVouchersForInvoice,
validateVoucherForInvoiceLink,
@@ -289,7 +300,7 @@ import { appendProcessingHistory } from '@/lib/processing-history/append'
import { getUserCompanies } from '@/lib/company/context'
// ensureInitialized() is called by the extension router (ext/[...path]/route.ts)
// which dispatches to this handler: no duplicate call needed here.
import type { Transaction, TransactionCategory, EntityType, VatTreatment, Invoice, Currency, CompanySettings, Customer, InvoiceItem, PendingOperation, VatPeriodType, VatDeclarationRutor, YearEndBlockerCode } from '@/types'
import type { Transaction, TransactionCategory, EntityType, VatTreatment, Invoice, Currency, CompanySettings, Customer, InvoiceItem, PendingOperation, VatPeriodType, VatDeclarationRutor, YearEndBlockerCode, SalesOrder, SalesOrderItem, SalesOrderStatus } from '@/types'
// ── Actor context ────────────────────────────────────────────
@@ -3047,6 +3058,165 @@ function projectMcpPayload<T>(value: T, namespace: McpToolNamespace): T {
return projectToolReferences(value, namespace, getCanonicalToolNames())
}
// ── Kundorder (sales orders) helpers ─────────────────────────
const SALES_ORDER_STATUSES = ['draft', 'confirmed', 'completed', 'cancelled'] as const
const SALES_ORDER_PROGRESS = ['none', 'partial', 'full'] as const
/**
* Staging-time mirror of the header state machine in
* lib/sales-orders/transitions.ts. The service is authoritative at commit
* (it re-reads the order and compare-and-sets on the status it saw); this
* copy exists only so an impossible transition is refused before it costs
* an approval round-trip.
*/
const SALES_ORDER_TRANSITIONS: Record<
'confirm' | 'cancel' | 'reopen',
{ from: readonly SalesOrderStatus[]; to: SalesOrderStatus }
> = {
confirm: { from: ['draft'], to: 'confirmed' },
cancel: { from: ['draft', 'confirmed'], to: 'cancelled' },
reopen: { from: ['cancelled'], to: 'draft' },
}
/** Surface a lib/sales-orders ServiceFailure through the tool error envelope. */
function throwSalesOrderFailure(failure: ServiceFailure, context: string): never {
if ('dbError' in failure) throw dbError(failure.dbError)
const entry = getErrorEntry(failure.code)
const details = failure.details ? ` ${JSON.stringify(failure.details)}` : ''
throw new Error(`${context}: ${failure.code}. ${entry?.message_en ?? ''}${details}`.trim())
}
async function loadSalesOrderOrThrow(
supabase: SupabaseClient,
companyId: string,
rawId: unknown,
): Promise<SalesOrder> {
const orderId = String(rawId ?? '').trim()
if (!orderId) throw new Error('sales_order_id is required. Use gnubok_list_sales_orders to find IDs.')
const res = await loadSalesOrder(supabase, companyId, orderId)
if (!res.ok) {
if ('code' in res && res.code === 'SALES_ORDER_NOT_FOUND') {
throw new Error('Sales order not found. Use gnubok_list_sales_orders to find valid IDs.')
}
throwSalesOrderFailure(res, 'Could not load sales order')
}
return res.order
}
/** First Zod issue of a staged sales-order payload as a tool error. */
function throwFirstZodIssue(result: { success: false; error: z.ZodError }, field?: string): never {
const issue = result.error.issues[0]
const path = [field, ...(issue?.path ?? [])].filter((p) => p !== undefined && p !== '').join('.')
throw new Error(`Invalid ${path || 'arguments'}: ${issue?.message ?? 'validation failed'}`)
}
function salesOrderSummary(order: SalesOrder) {
return {
sales_order_id: order.id,
order_number: order.order_number ?? null,
status: order.status,
customer_id: order.customer_id ?? null,
customer_name: (order.customer as { name?: string } | null | undefined)?.name ?? null,
order_date: order.order_date,
requested_delivery_date: order.requested_delivery_date ?? null,
last_delivery_date: order.last_delivery_date ?? null,
currency: order.currency,
subtotal: order.subtotal,
vat_amount: order.vat_amount,
total: order.total,
delivery_progress: order.delivery_progress ?? 'none',
invoicing_progress: order.invoicing_progress ?? 'none',
line_count: (order.items ?? []).length,
}
}
function salesOrderLineOut(item: SalesOrderItem) {
return {
sales_order_item_id: item.id,
line_type: item.line_type,
description: item.description,
quantity: item.quantity,
delivered_qty: item.delivered_qty,
invoiced_qty: item.invoiced_qty ?? 0,
remaining_qty: item.remaining_qty ?? Math.max(0, item.quantity - (item.invoiced_qty ?? 0)),
unit: item.unit,
unit_price: item.unit_price,
discount_percent: item.discount_percent,
line_total: item.line_total,
vat_rate: item.vat_rate,
article_id: item.article_id ?? null,
revenue_account: item.revenue_account ?? null,
dimensions: item.dimensions ?? {},
}
}
const SALES_ORDER_SUMMARY_PROPS = {
sales_order_id: { type: 'string' },
order_number: { type: ['string', 'null'], description: 'OR-<n>; null only if numbering failed at creation' },
status: { type: 'string', enum: SALES_ORDER_STATUSES },
customer_id: { type: ['string', 'null'] },
customer_name: { type: ['string', 'null'] },
order_date: { type: 'string' },
requested_delivery_date: { type: ['string', 'null'] },
last_delivery_date: { type: ['string', 'null'], description: 'Latest registered delivery; becomes delivery_date on invoices created from the order' },
currency: { type: 'string' },
subtotal: { type: 'number' },
vat_amount: { type: 'number' },
total: { type: 'number' },
delivery_progress: { type: 'string', enum: SALES_ORDER_PROGRESS },
invoicing_progress: { type: 'string', enum: SALES_ORDER_PROGRESS },
line_count: { type: 'number' },
} as const
const SALES_ORDER_SUMMARY_REQUIRED = [
'sales_order_id', 'status', 'order_date', 'currency', 'subtotal', 'vat_amount', 'total',
'delivery_progress', 'invoicing_progress', 'line_count',
] as const
const SALES_ORDER_LINE_OUTPUT_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
sales_order_item_id: { type: 'string' },
line_type: { type: 'string', description: 'product or text' },
description: { type: 'string' },
quantity: { type: 'number' },
delivered_qty: { type: 'number', description: 'Cumulative delivered quantity registered so far' },
invoiced_qty: { type: 'number', description: 'Derived from linked lines on non-cancelled, non-credited invoices' },
remaining_qty: { type: 'number', description: 'quantity - invoiced_qty, never negative' },
unit: { type: 'string' },
unit_price: { type: 'number' },
discount_percent: { type: 'number', description: 'Line discount 0-100; line_total is net of it' },
line_total: { type: 'number', description: 'Net of discount, order currency' },
vat_rate: { type: 'number' },
article_id: { type: ['string', 'null'] },
revenue_account: { type: ['string', 'null'] },
dimensions: { type: 'object', additionalProperties: { type: 'string' } },
},
required: [
'sales_order_item_id', 'line_type', 'description', 'quantity', 'delivered_qty', 'invoiced_qty',
'remaining_qty', 'unit', 'unit_price', 'line_total', 'vat_rate',
],
} as const
const SALES_ORDER_LINE_INPUT_SCHEMA = {
type: 'object',
properties: {
description: { type: 'string' },
quantity: { type: 'number' },
unit: { type: 'string', description: 'st, tim, dag, mån' },
unit_price: { type: 'number', description: 'Per unit excl. VAT' },
discount_percent: { type: 'number', description: 'Line discount 0-100' },
vat_rate: { type: 'number', description: 'VAT rate 0-100; default from customer VAT rules' },
article_id: { type: 'string', description: 'Article UUID; prefills like gnubok_create_invoice, line values win' },
line_type: { type: 'string', enum: ['product', 'text'], description: 'text = free-text row, no amounts' },
revenue_account: { type: ['string', 'null'], description: 'BAS class 1-3 account override' },
dimensions: { type: 'object', additionalProperties: { type: 'string' }, description: 'Dims bag {sie_dim_no: kod eller namn}' },
},
required: ['quantity'],
} as const
// ── Tools ────────────────────────────────────────────────────
export const tools: McpTool[] = [
@@ -6424,7 +6594,7 @@ export const tools: McpTool[] = [
const { data: invoice, error } = await supabase
.from('invoices')
.select(
'id, invoice_number, status, document_type, customer_id, invoice_date, due_date, delivery_date, currency, subtotal, vat_amount, total, paid_amount, remaining_amount, your_reference, our_reference, invoice_marking, notes, default_dimensions, journal_entry_id, is_self_billed, credited_invoice_id, customer:customers(name), items:invoice_items(id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions)',
'id, invoice_number, status, document_type, customer_id, invoice_date, due_date, delivery_date, currency, subtotal, vat_amount, total, paid_amount, remaining_amount, your_reference, our_reference, invoice_marking, notes, default_dimensions, journal_entry_id, is_self_billed, credited_invoice_id, customer:customers(name), items:invoice_items(id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, sales_order_item_id, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions)',
)
.eq('id', invoiceId)
.eq('company_id', companyId)
@@ -6755,6 +6925,672 @@ export const tools: McpTool[] = [
},
},
// ── Kundorder (sales orders) ─────────────────────────────────
//
// The non-ledger document between agreement and invoice. Orders never
// book: delivery is a fact the user records, invoicing creates a DRAFT
// kundfaktura through the same builder gnubok_create_invoice uses. Every
// write stages for approval and commits through lib/sales-orders.
{
name: 'gnubok_list_sales_orders',
keywords: ['kundorder', 'order', 'ordrar', 'orderbekräftelse', 'leverans', 'delfaktura'],
title: 'List Sales Orders',
description: 'List kundorder (sales orders) for the active company, newest first, with delivery and invoicing progress per order. Optional status and customer filters. Use gnubok_get_sales_order for the lines.',
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
status: { type: 'string', enum: SALES_ORDER_STATUSES, description: 'Filter by order status' },
customer_id: { type: 'string', description: 'Filter by customer UUID' },
limit: { type: 'number', description: 'Max results (default 50, max 100)' },
offset: { type: 'integer', minimum: 0, description: 'Number of results to skip for pagination (default 0)' },
},
},
// Item keys listed in prose instead of declared: the typed summary schema
// costs ~350 tokens of the tools/list budget (payload-size.bench.test.ts)
// and gnubok_get_sales_order (search-only) declares the same fields fully.
outputSchema: paginatedSchema('sales_orders', {
type: 'object',
description: 'sales_order_id, order_number, status, customer_id, customer_name, order_date, requested_delivery_date, last_delivery_date, currency, subtotal, vat_amount, total, delivery_progress, invoicing_progress (none|partial|full), line_count',
}),
annotations: ANNOTATIONS_READ_ONLY,
async execute(args, companyId, userId, supabase) {
const limit = Math.min(Math.max(1, Number(args.limit) || 50), 100)
const offset = Math.max(0, Math.floor(Number(args.offset) || 0))
const status = typeof args.status === 'string' ? args.status : undefined
const customerId = typeof args.customer_id === 'string' ? args.customer_id.trim() : ''
if (status && !(SALES_ORDER_STATUSES as readonly string[]).includes(status)) {
throw new Error(`Invalid status "${status}". Allowed: ${SALES_ORDER_STATUSES.join(', ')}`)
}
let query = supabase
.from('sales_orders')
.select(
'id, order_number, status, customer_id, order_date, requested_delivery_date, last_delivery_date, currency, subtotal, vat_amount, total, customer:customers(name), items:sales_order_items(id, line_type, quantity, delivered_qty, sort_order)',
{ count: 'exact' },
)
.eq('company_id', companyId)
if (status) query = query.eq('status', status)
if (customerId) query = query.eq('customer_id', customerId)
const { data, error, count } = await query
.order('order_date', { ascending: false })
.order('id', { ascending: false })
.range(offset, offset + limit)
if (error) throw dbError(error)
const rows = ((data ?? []) as unknown as SalesOrder[]).slice(0, limit)
// Progress needs the invoiced quantity per line, which lives on the
// linked invoice_items (one RPC for the whole page, RLS applies).
const invoiced = await fetchInvoicedQuantities(supabase, rows.map((r) => r.id))
if (!invoiced.ok) throw dbError(invoiced.dbError)
const salesOrders = rows.map((row) => salesOrderSummary(decorateSalesOrder(row, invoiced.byItem)))
const fetched = (data ?? []).length
const hasMore = count == null ? fetched > limit : offset + salesOrders.length < count
const total = count ?? offset + salesOrders.length + (hasMore ? 1 : 0)
return {
sales_orders: salesOrders,
count: salesOrders.length,
total_count: total,
has_more: hasMore,
...(hasMore ? { next_offset: offset + salesOrders.length } : {}),
}
},
},
{
name: 'gnubok_get_sales_order',
keywords: ['kundorder', 'order', 'orderrader', 'leverans', 'delfaktura'],
title: 'Get Sales Order',
description: 'One kundorder (sales order): header plus every line with delivered_qty, invoiced_qty and remaining_qty, and the invoices created from it. Read it before registering delivery or invoicing so line ids and remaining quantities are exact.',
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
sales_order_id: { type: 'string', description: 'UUID from gnubok_list_sales_orders' },
},
required: ['sales_order_id'],
},
outputSchema: {
type: 'object',
additionalProperties: false,
properties: {
...SALES_ORDER_SUMMARY_PROPS,
source_invoice_id: { type: ['string', 'null'], description: 'Proforma the order was converted from, if any' },
your_reference: { type: ['string', 'null'] },
our_reference: { type: ['string', 'null'] },
notes: { type: ['string', 'null'] },
default_dimensions: { type: 'object', additionalProperties: { type: 'string' } },
confirmed_at: { type: ['string', 'null'] },
completed_at: { type: ['string', 'null'] },
cancelled_at: { type: ['string', 'null'] },
items: { type: 'array', description: 'Lines in display order', items: SALES_ORDER_LINE_OUTPUT_SCHEMA },
item_count: { type: 'number' },
invoices: {
type: 'array',
description: 'Invoices created from this order (all statuses)',
items: {
type: 'object',
additionalProperties: false,
properties: {
invoice_id: { type: 'string' },
invoice_number: { type: ['string', 'null'], description: 'null until sent' },
status: { type: 'string' },
invoice_date: { type: 'string' },
total: { type: 'number' },
currency: { type: 'string' },
},
required: ['invoice_id', 'status', 'total', 'currency'],
},
},
},
required: [...SALES_ORDER_SUMMARY_REQUIRED, 'items', 'item_count', 'invoices'],
},
annotations: ANNOTATIONS_READ_ONLY,
// Search-only like gnubok_get_invoice: the line-level detail read behind
// the delivery and invoicing writes. Reads stay callable on Claude.ai via
// gnubok_call_tool; the tools/list budget (payload-size.bench.test.ts)
// has no room for its typed line schema in the default catalog.
catalogVisibility: 'search',
async execute(args, companyId, userId, supabase) {
const order = await loadSalesOrderOrThrow(supabase, companyId, args.sales_order_id)
const { data: invoiceRows, error: invoiceError } = await supabase
.from('invoices')
.select('id, invoice_number, status, invoice_date, total, currency')
.eq('company_id', companyId)
.eq('sales_order_id', order.id)
.order('invoice_date', { ascending: true })
.order('id', { ascending: true })
if (invoiceError) throw dbError(invoiceError)
const items = (order.items ?? []).map(salesOrderLineOut)
return {
...salesOrderSummary(order),
source_invoice_id: order.source_invoice_id ?? null,
your_reference: order.your_reference ?? null,
our_reference: order.our_reference ?? null,
notes: order.notes ?? null,
default_dimensions: order.default_dimensions ?? {},
confirmed_at: order.confirmed_at ?? null,
completed_at: order.completed_at ?? null,
cancelled_at: order.cancelled_at ?? null,
items,
item_count: items.length,
invoices: (invoiceRows ?? []).map((inv) => ({
invoice_id: inv.id,
invoice_number: inv.invoice_number ?? null,
status: inv.status,
invoice_date: inv.invoice_date,
total: inv.total,
currency: inv.currency,
})),
}
},
},
{
name: 'gnubok_create_sales_order',
keywords: ['kundorder', 'order', 'ny order', 'orderbekräftelse'],
title: 'Create Sales Order',
description: 'Stage a new kundorder (sales order) as a draft with its lines. Stages for approval: nothing is booked; totals are informational. Confirm it afterwards with gnubok_transition_sales_order, then deliver and invoice from it.',
outputSchema: STAGED_OPERATION_SCHEMA,
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
customer_id: { type: 'string', description: 'Customer UUID' },
items: { type: 'array', items: SALES_ORDER_LINE_INPUT_SCHEMA, description: 'Order lines' },
default_dimensions: {
type: 'object',
additionalProperties: { type: 'string' },
description: 'Dims bag {sie_dim_no: kod eller namn} applied to every item not setting the key',
},
order_date: { type: 'string', description: 'YYYY-MM-DD (default today)' },
requested_delivery_date: { type: 'string', description: 'YYYY-MM-DD' },
currency: { type: 'string', enum: ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'] },
our_reference: { type: 'string' },
your_reference: { type: 'string' },
notes: { type: 'string' },
dry_run: { type: 'boolean', description: 'Preview without staging' },
idempotency_key: { type: 'string', description: 'UUID for safe retries (24h)' },
},
required: ['customer_id', 'items'],
},
annotations: ANNOTATIONS_IDEMPOTENT_WRITE,
// Search-only (same footing as the mileage and skattekonto families): the
// tools/list budget (payload-size.bench.test.ts) has ~900 tokens of
// headroom and the four staged kundorder writes need ~2000 even trimmed.
// gnubok_list_sales_orders stays in the default catalog as the entry
// point; promoting the writes means demoting other reads first.
catalogVisibility: 'search',
async execute(args, companyId, userId, supabase, actor) {
const customerId = typeof args.customer_id === 'string' ? args.customer_id.trim() : ''
const rawItems = Array.isArray(args.items) ? (args.items as StagedInvoiceLineInput[]) : []
if (!customerId) throw new Error('customer_id is required. Use gnubok_list_customers to find IDs.')
if (rawItems.length === 0) throw new Error('At least one item is required.')
const { data: customer, error: custError } = await supabase
.from('customers')
.select('*')
.eq('id', customerId)
.eq('company_id', companyId)
.maybeSingle<Customer>()
if (custError) throw dbError(custError)
if (!customer) throw new Error('Customer not found. Use gnubok_list_customers to find valid IDs.')
const currency = ((args.currency as string) || 'SEK') as Currency
const today = new Date().toISOString().split('T')[0]
// Article prefill with the same rules as gnubok_create_invoice: the
// line's own values win, the article fills the rest, and its VAT rate
// is adopted only inside the customer's default rate set.
const adoptableVatRates = getArticleVatRateAdoptionSet(customer.customer_type, customer.vat_number_validated)
const articleIds = Array.from(new Set(rawItems.map((i) => i.article_id).filter((a): a is string => !!a)))
const articlesById = new Map<string, InvoiceLineArticle>()
if (articleIds.length > 0) {
const { data: articleRows, error: articleError } = await supabase
.from('articles')
.select('id, name, unit, price_excl_vat, vat_rate, revenue_account, currency, active')
.eq('company_id', companyId)
.in('id', articleIds)
if (articleError) throw dbError(articleError)
for (const row of articleRows ?? []) articlesById.set(row.id, row)
}
const resolvedLines = rawItems.map((item, i) =>
resolveInvoiceLineFromArticle(
item,
item.article_id ? articlesById.get(item.article_id) : undefined,
currency,
adoptableVatRates,
i,
),
)
// Resolve-don't-select for dimensions (names to registry codes), same
// as gnubok_create_invoice; the resolved bags are what gets staged.
const defaultDimensions = parseDimensionsArg(args.default_dimensions, 'default_dimensions')
const { bags: resolvedDimBags, resolutions: dimensionResolutions } = await resolveDimensionBags(
supabase,
companyId,
[defaultDimensions, ...resolvedLines.map((item, i) => parseDimensionsArg(item.dimensions, `items[${i}].dimensions`))],
)
const resolvedDefaultDimensions = resolvedDimBags[0]
const items = resolvedLines.map((line, i) => {
const bag = resolvedDimBags[i + 1]
return {
line_type: line.line_type ?? 'product',
description: line.description,
quantity: line.quantity,
unit: line.unit,
unit_price: line.unit_price,
...(line.discount_percent != null ? { discount_percent: line.discount_percent } : {}),
...(line.vat_rate != null ? { vat_rate: line.vat_rate } : {}),
...(line.article_id ? { article_id: line.article_id } : {}),
...(line.revenue_account != null ? { revenue_account: line.revenue_account } : {}),
...(bag && Object.keys(bag).length > 0 ? { dimensions: bag } : {}),
}
})
// Same schema the cookie route validates with, so a payload refused
// here is refused identically at the commit boundary.
const parsed = CreateSalesOrderSchema.safeParse({
customer_id: customerId,
order_date: (args.order_date as string) || today,
...(args.requested_delivery_date ? { requested_delivery_date: args.requested_delivery_date } : {}),
currency,
...(args.your_reference ? { your_reference: args.your_reference } : {}),
...(args.our_reference ? { our_reference: args.our_reference } : {}),
...(args.notes ? { notes: args.notes } : {}),
...(resolvedDefaultDimensions && Object.keys(resolvedDefaultDimensions).length > 0
? { default_dimensions: resolvedDefaultDimensions }
: {}),
items,
})
if (!parsed.success) throwFirstZodIssue(parsed)
const params = parsed.data
// Preview totals from the exact line math the service stores (net of
// discount, öre-exact) including the per-customer VAT gate.
const lines = normalizeSalesOrderLines(params.items, customer)
if (!lines.ok) throwSalesOrderFailure(lines, 'Cannot create sales order')
return stagePendingOperation(supabase, companyId, userId, 'create_sales_order',
`Ny kundorder: ${customer.name} ${lines.totals.total} ${currency}`,
params as unknown as Record<string, unknown>,
{
customer_name: customer.name,
customer_type: customer.customer_type,
items: lines.rows.map((row) => ({
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,
})),
subtotal: lines.totals.subtotal,
vat_amount: lines.totals.vat_amount,
total: lines.totals.total,
currency,
order_date: params.order_date,
requested_delivery_date: params.requested_delivery_date ?? null,
// Informational: an order is not a verifikat, so no period check.
writes_verifikat: false,
...(dimensionResolutions.length > 0 ? { dimension_resolutions: dimensionResolutions } : {}),
},
actor,
{
description: 'Once approved, the order is a draft. Confirm it with gnubok_transition_sales_order (action: confirm) before delivering or invoicing.',
tool: 'gnubok_transition_sales_order',
args: { action: 'confirm' },
},
{
dryRun: Boolean(args.dry_run),
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
},
)
},
},
{
name: 'gnubok_transition_sales_order',
keywords: ['kundorder', 'order', 'bekräfta order', 'makulera order', 'återöppna order'],
title: 'Transition Sales Order',
description: 'Stage a status change on a kundorder: confirm (draft to confirmed), cancel (draft or confirmed), or reopen (cancelled to draft). Stages for approval. Cancel and reopen are refused while invoices created from the order exist.',
outputSchema: STAGED_OPERATION_SCHEMA,
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
sales_order_id: { type: 'string', description: 'UUID from gnubok_list_sales_orders' },
action: { type: 'string', enum: ['confirm', 'cancel', 'reopen'] },
dry_run: { type: 'boolean', description: 'Preview without staging' },
idempotency_key: { type: 'string', description: 'UUID for safe retries (24h)' },
},
required: ['sales_order_id', 'action'],
},
annotations: ANNOTATIONS_IDEMPOTENT_WRITE,
// Search-only: see gnubok_create_sales_order.
catalogVisibility: 'search',
async execute(args, companyId, userId, supabase, actor) {
const parsedAction = SalesOrderTransitionSchema.safeParse({ action: args.action })
if (!parsedAction.success) throwFirstZodIssue(parsedAction)
const { action } = parsedAction.data
const order = await loadSalesOrderOrThrow(supabase, companyId, args.sales_order_id)
const rule = SALES_ORDER_TRANSITIONS[action]
if (!rule.from.includes(order.status)) {
throw new Error(
`Cannot ${action} sales order ${order.order_number ?? order.id}: SALES_ORDER_INVALID_STATE. ` +
`Status is "${order.status}"; ${action} requires ${rule.from.map((s) => `"${s}"`).join(' or ')}.`,
)
}
if (action === 'confirm' && !order.customer_id) {
throw new Error('Cannot confirm sales order: SALES_ORDER_CUSTOMER_MISSING. Set a customer first.')
}
if (action === 'cancel' || action === 'reopen') {
const open = await hasOpenInvoices(supabase, companyId, order.id)
if (!open.ok) throw dbError(open.dbError)
if (open.open) {
throw new Error(
`Cannot ${action} sales order ${order.order_number ?? order.id}: SALES_ORDER_HAS_INVOICES. ` +
'Cancel or credit the invoices created from it first (see gnubok_get_sales_order.invoices).',
)
}
}
const label = order.order_number ?? order.id
const titleVerb = action === 'confirm' ? 'Bekräfta' : action === 'cancel' ? 'Makulera' : 'Återöppna'
const customerName = (order.customer as { name?: string } | null | undefined)?.name ?? null
return stagePendingOperation(supabase, companyId, userId, 'transition_sales_order',
`${titleVerb} kundorder ${label}`,
{ sales_order_id: order.id, action },
{
sales_order_id: order.id,
order_number: order.order_number ?? null,
customer_name: customerName,
action,
current_status: order.status,
new_status: rule.to,
total: order.total,
currency: order.currency,
writes_verifikat: false,
},
actor,
action === 'confirm'
? {
description: 'Once confirmed, register deliveries with gnubok_register_sales_order_delivery or invoice it with gnubok_create_invoice_from_sales_order.',
tool: 'gnubok_create_invoice_from_sales_order',
args: { sales_order_id: order.id },
}
: {
description: 'Check the order afterwards with gnubok_get_sales_order.',
tool: 'gnubok_get_sales_order',
args: { sales_order_id: order.id },
},
{
dryRun: Boolean(args.dry_run),
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
},
)
},
},
{
name: 'gnubok_register_sales_order_delivery',
keywords: ['kundorder', 'leverans', 'leverera', 'delleverans', 'levererat antal'],
title: 'Register Sales Order Delivery',
description: 'Stage delivered quantities on a confirmed kundorder. delivered_qty is CUMULATIVE per line (the new total, not a delta), so retries are safe. Stages for approval; nothing is booked. Sets the delivery date used by invoices created afterwards.',
outputSchema: STAGED_OPERATION_SCHEMA,
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
sales_order_id: { type: 'string', description: 'UUID from gnubok_list_sales_orders' },
delivery_date: { type: 'string', description: 'YYYY-MM-DD (default today)' },
lines: {
type: 'array',
description: 'Delivered lines; omitted lines are untouched',
items: {
type: 'object',
properties: {
sales_order_item_id: { type: 'string', description: 'Line UUID from gnubok_get_sales_order' },
delivered_qty: { type: 'number', description: 'Cumulative delivered total, 0..quantity' },
},
required: ['sales_order_item_id', 'delivered_qty'],
},
},
dry_run: { type: 'boolean', description: 'Preview without staging' },
idempotency_key: { type: 'string', description: 'UUID for safe retries (24h)' },
},
required: ['sales_order_id', 'lines'],
},
annotations: ANNOTATIONS_IDEMPOTENT_WRITE,
// Search-only: see gnubok_create_sales_order.
catalogVisibility: 'search',
async execute(args, companyId, userId, supabase, actor) {
const parsed = RegisterSalesOrderDeliverySchema.safeParse({
...(args.delivery_date ? { delivery_date: args.delivery_date } : {}),
lines: args.lines,
})
if (!parsed.success) throwFirstZodIssue(parsed)
const input = parsed.data
const order = await loadSalesOrderOrThrow(supabase, companyId, args.sales_order_id)
if (order.status !== 'confirmed' && order.status !== 'completed') {
throw new Error(
`Cannot register delivery on sales order ${order.order_number ?? order.id}: SALES_ORDER_INVALID_STATE. ` +
`Status is "${order.status}"; confirm it first with gnubok_transition_sales_order.`,
)
}
// Same per-line guards the service applies at commit (line exists,
// text rows carry no quantity, never above the ordered quantity), so
// the agent learns about a bad line now instead of after approval.
const byId = new Map((order.items ?? []).map((i) => [i.id, i]))
const previewLines: Record<string, unknown>[] = []
for (const line of input.lines) {
const item = byId.get(line.sales_order_item_id)
if (!item) {
throw new Error(
`SALES_ORDER_LINE_NOT_FOUND: line ${line.sales_order_item_id} is not on this order. Read gnubok_get_sales_order for the line ids.`,
)
}
if (item.line_type === 'text') continue
if (line.delivered_qty > item.quantity) {
throw new Error(
`SALES_ORDER_OVER_DELIVERED: line "${item.description}" has quantity ${item.quantity}, cannot mark ${line.delivered_qty} delivered.`,
)
}
previewLines.push({
sales_order_item_id: item.id,
description: item.description,
quantity: item.quantity,
unit: item.unit,
delivered_before: item.delivered_qty,
delivered_after: line.delivered_qty,
delta: roundOre(line.delivered_qty - item.delivered_qty),
})
}
if (previewLines.length === 0) throw new Error('No product lines to deliver: every referenced line is a text row.')
const deliveryDate = input.delivery_date ?? new Date().toISOString().split('T')[0]
const label = order.order_number ?? order.id
const customerName = (order.customer as { name?: string } | null | undefined)?.name ?? null
return stagePendingOperation(supabase, companyId, userId, 'register_sales_order_delivery',
`Leverans kundorder ${label}`,
{ sales_order_id: order.id, delivery_date: deliveryDate, lines: input.lines },
{
sales_order_id: order.id,
order_number: order.order_number ?? null,
customer_name: customerName,
delivery_date: deliveryDate,
lines: previewLines,
// Quantities only: no inventory, no verifikat.
writes_verifikat: false,
},
actor,
{
description: 'Once approved, invoice the delivered quantities with gnubok_create_invoice_from_sales_order (mode: delivered).',
tool: 'gnubok_create_invoice_from_sales_order',
args: { sales_order_id: order.id, mode: 'delivered' },
},
{
dryRun: Boolean(args.dry_run),
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
},
)
},
},
{
name: 'gnubok_create_invoice_from_sales_order',
keywords: ['kundorder', 'fakturera order', 'delfaktura', 'delfakturera', 'slutfaktura', 'fakturera leverans'],
title: 'Create Invoice From Sales Order',
description: 'Stage a DRAFT kundfaktura from a confirmed kundorder: mode remaining (default) bills everything left, delivered bills what is delivered but not yet invoiced, or pick lines explicitly (delfaktura). Stages for approval; the number is assigned on send.',
outputSchema: STAGED_OPERATION_SCHEMA,
inputSchema: {
type: 'object',
additionalProperties: false,
properties: {
sales_order_id: { type: 'string', description: 'UUID from gnubok_list_sales_orders' },
mode: { type: 'string', enum: ['remaining', 'delivered'], description: 'Line selection when lines is omitted (default remaining)' },
lines: {
type: 'array',
description: 'Explicit picks (win over mode)',
items: {
type: 'object',
properties: {
sales_order_item_id: { type: 'string', description: 'Line UUID from gnubok_get_sales_order' },
quantity: { type: 'number', description: 'Positive, at most remaining_qty' },
},
required: ['sales_order_item_id', 'quantity'],
},
},
invoice_date: { type: 'string', description: 'YYYY-MM-DD (default today)' },
due_date: { type: 'string', description: 'YYYY-MM-DD (default from payment terms)' },
dry_run: { type: 'boolean', description: 'Preview without staging' },
idempotency_key: { type: 'string', description: 'UUID for safe retries (24h)' },
},
required: ['sales_order_id'],
},
annotations: ANNOTATIONS_IDEMPOTENT_WRITE,
// Search-only: see gnubok_create_sales_order.
catalogVisibility: 'search',
async execute(args, companyId, userId, supabase, actor) {
const parsed = CreateInvoiceFromSalesOrderSchema.safeParse({
...(args.mode ? { mode: args.mode } : {}),
...(args.lines !== undefined ? { lines: args.lines } : {}),
...(args.invoice_date ? { invoice_date: args.invoice_date } : {}),
...(args.due_date ? { due_date: args.due_date } : {}),
})
if (!parsed.success) throwFirstZodIssue(parsed)
const input = parsed.data
const order = await loadSalesOrderOrThrow(supabase, companyId, args.sales_order_id)
const label = order.order_number ?? order.id
if (order.status !== 'confirmed') {
const hint =
order.status === 'draft'
? 'Confirm it first with gnubok_transition_sales_order (action: confirm).'
: order.status === 'completed'
? 'It is fully invoiced already; see gnubok_get_sales_order.invoices.'
: 'A cancelled order cannot be invoiced; reopen and confirm it first.'
throw new Error(`Cannot invoice sales order ${label}: SALES_ORDER_INVALID_STATE. Status is "${order.status}". ${hint}`)
}
if (!order.customer_id) {
throw new Error(`Cannot invoice sales order ${label}: SALES_ORDER_CUSTOMER_MISSING. Set a customer first.`)
}
// The same picker the service runs at commit, against the CURRENT
// invoiced quantities: nothing left to bill, or a pick above
// remaining_qty, is refused here rather than after approval.
const pickedRes = pickLines(order, input)
if (!pickedRes.ok) throwSalesOrderFailure(pickedRes, `Cannot invoice sales order ${label}`)
const { picked } = pickedRes
// Preview line math: computeLineNet + roundOre, the same primitives the
// invoice builder uses; the builder is authoritative at commit.
let subtotal = 0
let vatAmount = 0
const previewLines = picked.map(({ item, quantity }) => {
const remaining = item.remaining_qty ?? Math.max(0, item.quantity - (item.invoiced_qty ?? 0))
const lineTotal = computeLineNet(quantity, item.unit_price, item.discount_percent)
const lineVat = roundOre((lineTotal * item.vat_rate) / 100)
subtotal = roundOre(subtotal + lineTotal)
vatAmount = roundOre(vatAmount + lineVat)
return {
sales_order_item_id: item.id,
description: item.description,
quantity,
unit: item.unit,
unit_price: item.unit_price,
discount_percent: item.discount_percent,
vat_rate: item.vat_rate,
line_total: lineTotal,
vat_amount: lineVat,
remaining_after: roundOre(remaining - quantity),
}
})
const total = roundOre(subtotal + vatAmount)
const customer = order.customer as (Customer | null | undefined)
const invoiceDate = input.invoice_date ?? new Date().toISOString().split('T')[0]
let dueDate = input.due_date
if (!dueDate) {
const due = new Date(invoiceDate)
due.setDate(due.getDate() + (customer?.default_payment_terms ?? 30))
dueDate = due.toISOString().split('T')[0]
}
const anyDelivered = picked.some((p) => p.item.delivered_qty > 0)
return stagePendingOperation(supabase, companyId, userId, 'create_invoice_from_sales_order',
`Faktura från kundorder ${label}: ${customer?.name ?? ''} ${total} ${order.currency}`.replace(/\s+/g, ' '),
{
sales_order_id: order.id,
...(input.mode ? { mode: input.mode } : {}),
...(input.lines ? { lines: input.lines } : {}),
invoice_date: invoiceDate,
due_date: dueDate,
},
{
sales_order_id: order.id,
order_number: order.order_number ?? null,
customer_name: customer?.name ?? null,
mode: input.lines && input.lines.length > 0 ? 'explicit' : (input.mode ?? 'remaining'),
items: previewLines,
subtotal,
vat_amount: vatAmount,
total,
currency: order.currency,
invoice_date: invoiceDate,
due_date: dueDate,
// Taxable-event date only when the invoice covers delivered goods.
delivery_date: anyDelivered ? (order.last_delivery_date ?? null) : null,
creates_draft: true,
},
actor,
{
description: 'Once approved, the invoice exists as a draft linked to the order. Send it with gnubok_send_invoice or use gnubok_mark_invoice_as_sent if delivered outside the system.',
tool: 'gnubok_send_invoice',
},
{
dryRun: Boolean(args.dry_run),
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
},
)
},
},
// ── Report tools ─────────────────────────────────────────────
{
+97
View File
@@ -411,6 +411,10 @@ export const CreateInvoiceItemSchema = z
// accounts are only accepted on zero-VAT lines (build-invoice-write.ts).
article_id: uuid.nullable().optional(),
revenue_account: invoicePostingAccount.nullable().optional(),
// Kundorder provenance: the order line this invoice line was created
// from. Round-tripped on draft edits; the DB trigger refuses a quantity
// that would over-invoice the order line.
sales_order_item_id: uuid.nullable().optional(),
// ROT/RUT-avdrag fields. `deduction_amount` is intentionally omitted from
// the client schema: the API computes it from rot-rut-rules.ts so a
// tampered client can't expand the 1513 receivable beyond the line total.
@@ -2284,6 +2288,9 @@ export const UpdateSettingsSchema = z.object({
// Körjournal (mileage log): UI-visibility toggle only, never load-bearing
// for correctness (trips created via API/MCP work regardless).
mileage_enabled: z.boolean().optional(),
// Kundorder (sales orders): UI-visibility toggle only, never load-bearing
// for correctness (the pages and APIs work regardless).
sales_orders_enabled: z.boolean().optional(),
// Data analysis consent (#1346): gates cross-company analysis of this
// company's bookkeeping outcomes. Flipped by a human in the settings UI
// only; deliberately absent from the v1 REST / MCP settings pick lists.
@@ -3780,3 +3787,93 @@ export const BrandAllowlistAddSchema = z.object({
export const BrandAllowlistRemoveSchema = z.object({
id: z.string().uuid(),
})
// ============================================================
// Kundorder (sales orders) schemas
// ============================================================
// Order lines mirror the invoice line shape (same editor, same line math)
// minus the invoice-only fields (ROT/RUT, periodisering). Text rows carry a
// description only.
export const SalesOrderItemSchema = z
.object({
id: uuid.optional(),
line_type: z.enum(['product', 'text']).optional(),
description: z.string().max(2000),
quantity: z.number().nonnegative(),
unit: z.string().max(32),
unit_price: z.number(),
discount_percent: z.number().min(0).max(100).nullable().optional(),
vat_rate: z.number().min(0).max(100).optional(),
article_id: uuid.nullable().optional(),
revenue_account: invoicePostingAccount.nullable().optional(),
dimensions: DimensionsBagSchema.optional(),
})
.superRefine((item, ctx) => {
if (item.line_type === 'text') return
if (!item.description.trim()) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['description'], message: 'Beskrivning krävs' })
}
})
export const CreateSalesOrderSchema = z.object({
customer_id: uuid,
order_date: isoDate.optional(),
requested_delivery_date: isoDate.nullable().optional(),
currency: CurrencySchema.optional(),
your_reference: z.string().max(200).nullable().optional(),
our_reference: z.string().max(200).nullable().optional(),
notes: z.string().max(4000).nullable().optional(),
default_dimensions: DimensionsBagSchema.optional(),
items: z.array(SalesOrderItemSchema).min(1, 'Minst en orderrad krävs').max(500),
})
// Full replace of header + lines. Lines that carry an `id` keep their
// delivered/invoiced history (the DB refuses lowering quantity below the
// invoiced quantity); lines without an id are new; omitted ids are deleted.
export const UpdateSalesOrderSchema = CreateSalesOrderSchema.partial().extend({
items: z.array(SalesOrderItemSchema).min(1).max(500).optional(),
})
export const SalesOrderTransitionSchema = z.object({
action: z.enum(['confirm', 'cancel', 'reopen']),
})
export const RegisterSalesOrderDeliverySchema = z.object({
delivery_date: isoDate.optional(),
lines: z
.array(
z.object({
sales_order_item_id: uuid,
// Cumulative delivered quantity after this registration (not a delta):
// idempotent on retry, and what the user sees in the dialog.
delivered_qty: z.number().nonnegative(),
}),
)
.min(1)
.max(500),
})
export const CreateInvoiceFromSalesOrderSchema = z.object({
// Explicit picks win. Without them, `mode` selects the lines:
// remaining = every line with quantity left to invoice (default)
// delivered = only what has been delivered but not yet invoiced
mode: z.enum(['remaining', 'delivered']).optional(),
lines: z
.array(
z.object({
sales_order_item_id: uuid,
quantity: z.number().positive(),
}),
)
.max(500)
.optional(),
invoice_date: isoDate.optional(),
due_date: isoDate.optional(),
})
export const SalesOrderListQuerySchema = z.object({
status: z.enum(['draft', 'confirmed', 'completed', 'cancelled']).optional(),
customer_id: uuid.optional(),
q: z.string().max(200).optional(),
})
+1 -1
View File
@@ -35,4 +35,4 @@ export const INVOICE_PDF_COLUMNS =
'paid_amount, remaining_amount, deduction_total, deduction_personnummer_last4'
export const INVOICE_ITEM_FULL_COLUMNS =
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, created_at'
'id, sort_order, line_type, description, quantity, unit, unit_price, discount_percent, line_total, vat_rate, vat_amount, article_id, revenue_account, deduction_type, deduction_amount, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, dimensions, sales_order_item_id, created_at'
+10 -2
View File
@@ -16,8 +16,8 @@ export const API_KEY_SCOPES = {
'customers:write': { label: 'Kunder: skriv', description: 'Skapa och uppdatera kunder' },
'articles:read': { label: 'Artiklar: läs', description: 'Lista artiklar i artikelregistret' },
'articles:write': { label: 'Artiklar: skriv', description: 'Skapa och uppdatera artiklar' },
'invoices:read': { label: 'Fakturor: läs', description: 'Lista fakturor' },
'invoices:write': { label: 'Fakturor: skriv', description: 'Skapa, skicka, markera betald/skickad' },
'invoices:read': { label: 'Fakturor: läs', description: 'Lista fakturor och kundorder' },
'invoices:write': { label: 'Fakturor: skriv', description: 'Skapa, skicka, markera betald/skickad; kundorder (skapa, bekräfta, leverera, fakturera)' },
'suppliers:read': { label: 'Leverantörer: läs', description: 'Lista leverantörer och leverantörsfakturor, hitta verifikat-kandidater' },
'suppliers:write': { label: 'Leverantörer: skriv', description: 'Skapa leverantörer; godkänn, kreditera, betal-länka och hantera leverantörsfakturor' },
'reports:read': { label: 'Rapporter: läs', description: 'Kontoplan, huvudbok, balansräkning, resultaträkning, moms, KPI, reskontra, perioder, bankavstämning, SIE-export' },
@@ -260,6 +260,14 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
gnubok_send_invoice: 'invoices:write',
gnubok_mark_invoice_as_paid: 'invoices:write',
gnubok_mark_invoice_as_sent: 'invoices:write',
// Kundorder (sales orders): the pre-invoice document. Reads and staged
// writes ride the invoice scopes (an order exists only to become one).
gnubok_list_sales_orders: 'invoices:read',
gnubok_get_sales_order: 'invoices:read',
gnubok_create_sales_order: 'invoices:write',
gnubok_transition_sales_order: 'invoices:write',
gnubok_register_sales_order_delivery: 'invoices:write',
gnubok_create_invoice_from_sales_order: 'invoices:write',
// Recurring invoice schedules (staged template writes; no send/book at commit)
gnubok_list_recurring_schedules: 'invoices:read',
gnubok_create_recurring_schedule: 'invoices:write',
+40
View File
@@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest'
import { addDaysIso, daysBetweenIso, todayIsoStockholm, toIsoDate } from '../iso'
describe('todayIsoStockholm', () => {
it('rolls over to the next Swedish calendar day before UTC midnight (CEST, UTC+2)', () => {
expect(todayIsoStockholm(new Date('2026-06-30T22:30:00Z'))).toBe('2026-07-01')
})
it('keeps the same day at midday', () => {
expect(todayIsoStockholm(new Date('2026-01-15T12:00:00Z'))).toBe('2026-01-15')
})
it('rolls over one hour later in winter (CET, UTC+1)', () => {
expect(todayIsoStockholm(new Date('2026-01-15T22:30:00Z'))).toBe('2026-01-15')
expect(todayIsoStockholm(new Date('2026-01-15T23:30:00Z'))).toBe('2026-01-16')
})
it('defaults to now and returns a YYYY-MM-DD string', () => {
expect(todayIsoStockholm()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
})
})
describe('UTC helpers', () => {
it('addDaysIso is pure UTC arithmetic', () => {
expect(addDaysIso('2026-02-28', 1)).toBe('2026-03-01')
expect(addDaysIso('2026-03-29', 1)).toBe('2026-03-30')
expect(addDaysIso('2026-01-01', -1)).toBe('2025-12-31')
})
it('daysBetweenIso is signed', () => {
expect(daysBetweenIso('2026-01-01', '2026-01-31')).toBe(30)
expect(daysBetweenIso('2026-01-31', '2026-01-01')).toBe(-30)
})
it('toIsoDate takes the UTC calendar date, unlike todayIsoStockholm', () => {
const late = new Date('2026-06-30T22:30:00Z')
expect(toIsoDate(late)).toBe('2026-06-30')
expect(todayIsoStockholm(late)).toBe('2026-07-01')
})
})
+16
View File
@@ -30,3 +30,19 @@ export function toIsoDate(d: Date): string {
export function todayIsoUtc(): string {
return new Date().toISOString().slice(0, 10)
}
/**
* Today's calendar date in Europe/Stockholm as YYYY-MM-DD. Business dates
* (order date, delivery date, invoice date) belong to the Swedish calendar
* day, not UTC: near midnight the UTC date is still yesterday, and a
* delivery date is also the Riksbanken rate anchor for foreign-currency
* invoices.
*/
export function todayIsoStockholm(now: Date = new Date()): string {
return new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Europe/Stockholm',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(now)
}
+86
View File
@@ -1364,6 +1364,92 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
message_sv: 'Detta dokument är inte en offert.',
message_en: 'This document is not a quote.',
},
// Kundorder (sales orders): lib/sales-orders/*, app/api/sales-orders/*
SALES_ORDER_NOT_FOUND: {
httpStatus: 404,
message_sv: 'Kundordern hittades inte.',
message_en: 'The sales order was not found.',
},
SALES_ORDER_INVALID_STATE: {
httpStatus: 409,
message_sv: 'Kundordern har inte en status som tillåter den här åtgärden.',
message_en: 'The sales order is not in a state that allows this action.',
},
SALES_ORDER_NOT_EDITABLE: {
httpStatus: 409,
message_sv: 'Kundordern kan bara ändras medan den är utkast eller bekräftad.',
message_en: 'A sales order can only be edited while it is a draft or confirmed.',
},
SALES_ORDER_HAS_INVOICES: {
httpStatus: 409,
message_sv: 'Kundordern kan inte makuleras: det finns fakturor som skapats från den. Makulera eller kreditera fakturorna först.',
message_en: 'The sales order cannot be cancelled: invoices have been created from it. Cancel or credit those invoices first.',
},
SALES_ORDER_LINE_NOT_FOUND: {
httpStatus: 400,
message_sv: 'En angiven orderrad finns inte på kundordern.',
message_en: 'A referenced line does not exist on the sales order.',
},
SALES_ORDER_OVER_INVOICED: {
httpStatus: 409,
message_sv: 'Angivet antal överstiger vad som återstår att fakturera på orderraden.',
message_en: 'The requested quantity exceeds what remains to be invoiced on the order line.',
},
SALES_ORDER_OVER_DELIVERED: {
httpStatus: 400,
message_sv: 'Levererat antal kan inte överstiga beställt antal.',
message_en: 'Delivered quantity cannot exceed the ordered quantity.',
},
SALES_ORDER_QUANTITY_BELOW_INVOICED: {
httpStatus: 409,
message_sv: 'Antalet på en orderrad kan inte sänkas under det som redan fakturerats.',
message_en: 'An order line quantity cannot be lowered below what has already been invoiced.',
},
SALES_ORDER_NOTHING_TO_INVOICE: {
httpStatus: 409,
message_sv: 'Det finns inget kvar att fakturera på kundordern.',
message_en: 'There is nothing left to invoice on the sales order.',
},
SALES_ORDER_CUSTOMER_MISSING: {
httpStatus: 409,
message_sv: 'Kundordern saknar kund. Ange en kund innan du fakturerar.',
message_en: 'The sales order has no customer. Set a customer before invoicing.',
},
SALES_ORDER_CREATE_FAILED: {
httpStatus: 500,
message_sv: 'Kundordern kunde inte sparas.',
message_en: 'The sales order could not be saved.',
},
SALES_ORDER_LINE_LOCKED: {
httpStatus: 409,
message_sv: 'En orderrad med fakturerat eller levererat antal kan inte tas bort.',
message_en: 'An order line with invoiced or delivered quantity cannot be removed.',
},
SALES_ORDER_SOURCE_NOT_PROFORMA: {
httpStatus: 400,
message_sv: 'Bara en proformafaktura kan omvandlas till kundorder.',
message_en: 'Only a proforma invoice can be converted into a sales order.',
},
SALES_ORDER_SOURCE_UNSUPPORTED_LINES: {
httpStatus: 400,
message_sv: 'Proformafakturan innehåller rader som inte kan föras över till en kundorder (ROT/RUT-avdrag, periodisering eller negativt antal). Skapa kundordern manuellt.',
message_en: 'The proforma has lines that cannot be carried into a sales order (ROT/RUT deduction, accrual period or negative quantity). Create the sales order manually.',
},
SALES_ORDER_CUSTOMER_VAT_CHANGED: {
httpStatus: 409,
message_sv: 'Kundens momsuppgifter (kundtyp eller VAT-nummer) har ändrats sedan kundordern prissattes. Öppna och spara kundordern igen så att momssatserna kontrolleras innan du fakturerar.',
message_en: 'The customer VAT facts (customer type or VAT number validation) changed after the sales order was priced. Open and save the order again so the VAT rates are re-checked before invoicing.',
},
INVOICE_UPDATE_DROPS_ORDER_LINK: {
httpStatus: 409,
message_sv: 'Fakturan är skapad från en kundorder och ändringen skulle tappa kopplingen till orderraderna. Skicka med sales_order_item_id på raderna, eller makulera fakturan och skapa en ny från kundordern.',
message_en: 'The invoice was created from a sales order and this edit would drop the link to its order lines. Keep sales_order_item_id on the lines, or cancel the invoice and create a new one from the order.',
},
SALES_ORDER_SOURCE_ALREADY_CONVERTED: {
httpStatus: 409,
message_sv: 'Proformafakturan har redan omvandlats till en kundorder.',
message_en: 'The proforma has already been converted into a sales order.',
},
// POST /api/invoices/{id}/peppol/send. The Access Point is an environment
// decision (PEPPOL_TRANSPORT_PROVIDER + adapter credentials); the product
// never pretends to send when no adapter is switched on.
@@ -25,6 +25,7 @@ function makeItem(overrides: Partial<InvoiceWriteItemRow> = {}): InvoiceWriteIte
vat_amount: 250,
article_id: null,
revenue_account: null,
sales_order_item_id: null,
deduction_type: null,
deduction_amount: 0,
labor_hours: null,
@@ -62,6 +63,7 @@ function storedRow(overrides: Record<string, unknown> = {}): Record<string, unkn
}
function createHarness(opts: {
/** Snapshot rows; omit for an empty draft, pass null for "no rows came back". */
snapshot?: unknown[] | null
snapshotError?: unknown
deleteError?: unknown
@@ -69,16 +71,19 @@ function createHarness(opts: {
insertErrors?: (unknown | null)[]
}) {
const inserts: Record<string, unknown>[][] = []
const deletes: string[] = []
let insertCall = 0
const snapshot = opts.snapshot === undefined ? [] : opts.snapshot
const supabase = {
from: vi.fn(() => ({
select: vi.fn(() => ({
eq: vi.fn(() =>
Promise.resolve({ data: opts.snapshot ?? [], error: opts.snapshotError ?? null }),
),
eq: vi.fn(() => Promise.resolve({ data: snapshot, error: opts.snapshotError ?? null })),
})),
delete: vi.fn(() => ({
eq: vi.fn(() => Promise.resolve({ error: opts.deleteError ?? null })),
eq: vi.fn((_column: string, value: string) => {
deletes.push(value)
return Promise.resolve({ error: opts.deleteError ?? null })
}),
})),
insert: vi.fn((rows: Record<string, unknown>[]) => {
inserts.push(rows)
@@ -88,11 +93,115 @@ function createHarness(opts: {
}),
})),
}
return { supabase: supabase as unknown as SupabaseClient, inserts }
return { supabase: supabase as unknown as SupabaseClient, inserts, deletes }
}
const insertBoom = { message: 'insert boom', code: '23502' }
const ORDER_LINE_1 = 'd1000000-0000-4000-8000-000000000001'
const ORDER_LINE_2 = 'd1000000-0000-4000-8000-000000000002'
const guardResult = {
ok: false,
stage: 'guard',
code: 'INVOICE_UPDATE_DROPS_ORDER_LINK',
messageSv: expect.stringContaining('kundorder'),
}
describe('replaceInvoiceItems order-link guard', () => {
it('refuses before deleting when the new lines drop a sales_order_item_id link', async () => {
const { supabase, inserts, deletes } = createHarness({
snapshot: [storedRow({ sales_order_item_id: ORDER_LINE_1 })],
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: null })])
expect(result).toEqual(guardResult)
expect(deletes).toHaveLength(0)
expect(inserts).toHaveLength(0)
})
it('proceeds when every existing link is kept on the new lines', async () => {
const { supabase, inserts, deletes } = createHarness({
snapshot: [
storedRow({ sales_order_item_id: ORDER_LINE_1 }),
storedRow({ id: 'item-old-2', sort_order: 1, sales_order_item_id: ORDER_LINE_2 }),
],
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [
// Reordered and with an extra unlinked line: still covers both links.
makeItem({ sort_order: 0, sales_order_item_id: ORDER_LINE_2 }),
makeItem({ sort_order: 1, description: 'Fri rad', sales_order_item_id: null }),
makeItem({ sort_order: 2, sales_order_item_id: ORDER_LINE_1 }),
])
expect(result).toEqual({ ok: true })
expect(deletes).toEqual(['inv-1'])
expect(inserts).toHaveLength(1)
expect(inserts[0].map((r) => r.sales_order_item_id)).toEqual([ORDER_LINE_2, null, ORDER_LINE_1])
})
it('proceeds when the draft carries no order links at all', async () => {
const { supabase, inserts, deletes } = createHarness({
snapshot: [storedRow({ sales_order_item_id: null }), storedRow({ id: 'item-old-2', sort_order: 1 })],
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ description: 'Ny rad' })])
expect(result).toEqual({ ok: true })
expect(deletes).toEqual(['inv-1'])
expect(inserts).toHaveLength(1)
})
it('compares links as a multiset: two rows on the same order line need two links back', async () => {
const { supabase, inserts } = createHarness({
snapshot: [
storedRow({ sales_order_item_id: ORDER_LINE_1 }),
storedRow({ id: 'item-old-2', sort_order: 1, sales_order_item_id: ORDER_LINE_1 }),
],
})
const dropped = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: ORDER_LINE_1 })])
expect(dropped).toEqual(guardResult)
expect(inserts).toHaveLength(0)
const kept = await replaceInvoiceItems(supabase, 'inv-1', [
makeItem({ sales_order_item_id: ORDER_LINE_1 }),
makeItem({ sort_order: 1, sales_order_item_id: ORDER_LINE_1 }),
])
expect(kept).toEqual({ ok: true })
expect(inserts).toHaveLength(1)
})
it('refuses when a link is swapped for a different order line', async () => {
const { supabase, inserts } = createHarness({
snapshot: [storedRow({ sales_order_item_id: ORDER_LINE_1 })],
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem({ sales_order_item_id: ORDER_LINE_2 })])
expect(result).toEqual(guardResult)
expect(inserts).toHaveLength(0)
})
it('fails closed before deleting when the snapshot could not be read (guard cannot run)', async () => {
// Without the snapshot the link multiset is unknown: a draft that may
// carry order links must not be emptied on a guess.
const selectBoom = { message: 'select boom' }
const { supabase, inserts, deletes } = createHarness({
snapshot: null,
snapshotError: selectBoom,
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem()])
expect(result).toEqual({ ok: false, stage: 'delete', error: selectBoom })
expect(deletes).toEqual([])
expect(inserts).toHaveLength(0)
})
})
describe('replaceInvoiceItems', () => {
it('replaces the rows and stamps invoice_id on the happy path', async () => {
const { supabase, inserts } = createHarness({ snapshot: [storedRow()] })
@@ -145,19 +254,24 @@ describe('replaceInvoiceItems', () => {
expect(inserts).toHaveLength(2)
})
it('reports restored: false when the snapshot itself could not be read', async () => {
// With no snapshot there is nothing to reinsert, and claiming the draft is
// intact would be a guess: the delete may well have removed real rows.
const { supabase, inserts } = createHarness({
it('refuses at the delete stage when the snapshot read returns no rows at all (null, no error)', async () => {
// A null snapshot without a driver error still leaves nothing to restore
// and nothing to guard against: the function stops before the delete
// instead of proceeding and later reporting restored: false.
const { supabase, inserts, deletes } = createHarness({
snapshot: null,
snapshotError: { message: 'select boom' },
insertErrors: [insertBoom],
})
const result = await replaceInvoiceItems(supabase, 'inv-1', [makeItem()])
expect(result).toMatchObject({ ok: false, stage: 'insert', restored: false })
expect(inserts).toHaveLength(1)
expect(result).toMatchObject({
ok: false,
stage: 'delete',
error: { code: 'SNAPSHOT_UNAVAILABLE', message: 'invoice_items snapshot unavailable' },
})
expect(deletes).toEqual([])
expect(inserts).toHaveLength(0)
})
it('reports restored: true when the draft had no items to begin with', async () => {
+6
View File
@@ -53,6 +53,9 @@ export interface InvoiceWriteItemInput {
vat_rate?: number
article_id?: string | null
revenue_account?: string | null
/** Kundorder line this invoice line was created from; round-tripped on
* edit so the order's derived invoiced quantity never loses a link. */
sales_order_item_id?: string | null
deduction_type?: 'rot' | 'rut' | null
labor_hours?: number | null
work_type?: string | null
@@ -142,6 +145,7 @@ export type InvoiceWriteItemRow = {
vat_amount: number
article_id: string | null
revenue_account: string | null
sales_order_item_id: string | null
deduction_type: 'rot' | 'rut' | null
deduction_amount: number
labor_hours: number | null
@@ -564,6 +568,7 @@ export async function buildInvoiceWriteData(params: {
vat_amount: 0,
article_id: null,
revenue_account: null,
sales_order_item_id: null,
deduction_type: null,
deduction_amount: 0,
labor_hours: null,
@@ -610,6 +615,7 @@ export async function buildInvoiceWriteData(params: {
// VAT-treatment-derived account in generatePerRateLines().
article_id: item.article_id ?? null,
revenue_account: item.revenue_account ?? null,
sales_order_item_id: item.sales_order_item_id ?? null,
deduction_type: deductionType,
deduction_amount: deductionAmount,
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
+55 -3
View File
@@ -18,6 +18,8 @@ import type { InvoiceWriteItemRow } from '@/lib/invoices/build-invoice-write'
* snapshot/restore idiom as commitUpdateRecurringSchedule in
* lib/pending-operations/commit.ts. `restored` on the insert-failure shape
* says whether the previous rows are back; the success path is unchanged.
* An unreadable snapshot refuses the replace outright: it is both the
* restore source and the input to the kundorder link guard below.
*
* Shared by the cookie PATCH route (app/api/invoices/[id]), the v1 REST PATCH
* route, and the update_invoice commit executor so the replace logic cannot
@@ -25,6 +27,14 @@ import type { InvoiceWriteItemRow } from '@/lib/invoices/build-invoice-write'
*/
export type ReplaceInvoiceItemsResult =
| { ok: true }
/**
* Refused before any write: the draft was created from a kundorder and the
* new line set drops one or more sales_order_item_id links. The order's
* invoiced quantity is derived from those links, so losing them would free
* the quantity for a second invoice. Every caller (cookie PATCH, v1 PATCH,
* update_invoice executor) surfaces this as INVOICE_UPDATE_DROPS_ORDER_LINK.
*/
| { ok: false; stage: 'guard'; code: 'INVOICE_UPDATE_DROPS_ORDER_LINK'; messageSv: string }
| { ok: false; stage: 'delete'; error: PostgrestError }
| {
ok: false
@@ -55,6 +65,48 @@ export async function replaceInvoiceItems(
.select('*')
.eq('invoice_id', invoiceId)
// Order-link guard: a line set that forgets sales_order_item_id (a client
// that read the lines through a projection without it, or a header-only
// edit path that re-reads a narrow column list) must not silently sever
// the kundorder link. Compare the link multiset before deleting anything.
if (snapshotError || !snapshotRows) {
// Without the snapshot the guard cannot run and the restore path has
// nothing to put back: refuse rather than fail open on a draft that may
// carry order links.
return {
ok: false,
stage: 'delete',
error:
snapshotError ??
({ message: 'invoice_items snapshot unavailable', code: 'SNAPSHOT_UNAVAILABLE' } as PostgrestError),
}
}
{
const existingLinks = (snapshotRows as Array<{ sales_order_item_id?: string | null }>)
.map((row) => row.sales_order_item_id)
.filter((id): id is string => typeof id === 'string')
if (existingLinks.length > 0) {
const incoming = new Map<string, number>()
for (const item of items) {
const link = (item as { sales_order_item_id?: string | null }).sales_order_item_id
if (link) incoming.set(link, (incoming.get(link) ?? 0) + 1)
}
for (const link of existingLinks) {
const left = incoming.get(link) ?? 0
if (left === 0) {
return {
ok: false,
stage: 'guard',
code: 'INVOICE_UPDATE_DROPS_ORDER_LINK',
messageSv:
'Fakturan är skapad från en kundorder och ändringen skulle tappa kopplingen till orderraderna.',
}
}
incoming.set(link, left - 1)
}
}
}
const { error: deleteError } = await supabase
.from('invoice_items')
.delete()
@@ -69,10 +121,10 @@ export async function replaceInvoiceItems(
if (insertError) {
// Best-effort restore of the snapshot so the draft keeps its lines. A
// failed (or impossible) restore is reported, never swallowed.
// The snapshot is guaranteed here: an unreadable one refuses the replace
// before the delete (order-link guard above).
let restored = false
if (snapshotError || snapshotRows == null) {
restored = false
} else if (snapshotRows.length === 0) {
if (snapshotRows.length === 0) {
// Nothing existed before, so the draft is already in its prior state.
restored = true
} else {
@@ -0,0 +1,396 @@
/**
* Executor tests for the four staged kundorder (sales order) operations.
* The executors are private to commit.ts and reached through
* commitPendingOperation (same pattern as ignore-transaction-executor.test.ts).
*
* The lib/sales-orders services are mocked: the executors own only the
* commit-boundary re-validation, the service call and the mapping of a
* ServiceFailure onto the CommitResult contract. Totals, VAT and the state
* machine are the services' business and are tested there.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { eventBus } from '@/lib/events'
import type { PendingOperation, SalesOrder } from '@/types'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/sales-orders/write', () => ({
createSalesOrder: vi.fn(),
}))
vi.mock('@/lib/sales-orders/transitions', () => ({
transitionSalesOrder: vi.fn(),
}))
vi.mock('@/lib/sales-orders/register-delivery', () => ({
registerSalesOrderDelivery: vi.fn(),
}))
vi.mock('@/lib/sales-orders/create-invoice-from-order', () => ({
createInvoiceFromSalesOrder: vi.fn(),
}))
import { createSalesOrder } from '@/lib/sales-orders/write'
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
import { commitPendingOperation } from '../commit'
const ORDER_ID = '00000000-0000-4000-8000-0000000000aa'
const CUSTOMER_ID = '00000000-0000-4000-8000-0000000000bb'
const ITEM_ID = '00000000-0000-4000-8000-0000000000cc'
const INVOICE_ID = '00000000-0000-4000-8000-0000000000dd'
function makeOrder(overrides: Partial<SalesOrder> = {}): SalesOrder {
return {
id: ORDER_ID,
company_id: 'company-1',
user_id: 'user-1',
customer_id: CUSTOMER_ID,
order_number: 'OR-7',
status: 'draft',
source_invoice_id: null,
order_date: '2026-09-01',
requested_delivery_date: null,
last_delivery_date: null,
currency: 'SEK',
subtotal: 1000,
vat_amount: 250,
total: 1250,
your_reference: null,
our_reference: null,
notes: null,
default_dimensions: {},
confirmed_at: null,
completed_at: null,
cancelled_at: null,
created_at: '2026-09-01T00:00:00Z',
updated_at: '2026-09-01T00:00:00Z',
items: [],
delivery_progress: 'none',
invoicing_progress: 'none',
...overrides,
}
}
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
return {
id: 'op-1',
user_id: 'user-1',
company_id: 'company-1',
operation_type: 'create_sales_order',
status: 'pending',
title: 'test',
params: {},
preview_data: {},
result_data: null,
actor_type: 'user',
actor_id: null,
actor_label: null,
risk_level: 'low',
created_at: '2026-09-01T00:00:00Z',
resolved_at: null,
updated_at: '2026-09-01T00:00:00Z',
...overrides,
} as PendingOperation
}
const CREATE_PARAMS = {
customer_id: CUSTOMER_ID,
order_date: '2026-09-01',
currency: 'SEK',
items: [{ description: 'Konsulttimmar', quantity: 10, unit: 'tim', unit_price: 100 }],
}
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
describe('commitPendingOperation: create_sales_order', () => {
it('happy path: validates the staged params, calls the service and returns the order ids', async () => {
vi.mocked(createSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } }) // CAS claim
enqueue({ data: null }) // finalize
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, order_number: 'OR-7', status: 'draft', total: 1250 })
expect(createSalesOrder).toHaveBeenCalledWith(supabase, {
companyId: 'company-1',
userId: 'user-1',
input: expect.objectContaining({ customer_id: CUSTOMER_ID, items: expect.any(Array) }),
})
})
it('maps a coded service failure onto the structured error (CUSTOMER_NOT_FOUND -> 404 auto-reject)', async () => {
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: CUSTOMER_ID } })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } }) // CAS claim
enqueue({ data: null }) // reject write
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
)
expect(result.status).toBe('rejected')
expect(result.http_status).toBe(404)
expect(result.code).toBe('CUSTOMER_NOT_FOUND')
expect(result.data).toEqual({ customerId: CUSTOMER_ID })
})
it('rejects tampered params at the commit boundary before the service runs', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } }) // CAS claim
enqueue({ data: null }) // reject write
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_sales_order', params: { ...CREATE_PARAMS, customer_id: 'not-a-uuid' } }),
)
expect(result.status).not.toBe('committed')
expect(result.http_status).toBe(400)
expect(result.error).toMatch(/customer_id/)
expect(createSalesOrder).not.toHaveBeenCalled()
})
it('surfaces a raw DB failure as a 500 with the driver message', async () => {
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, dbError: { message: 'connection reset' } })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(500)
expect(result.error).toBe('connection reset')
})
})
describe('commitPendingOperation: transition_sales_order', () => {
it('happy path: confirms through the service', async () => {
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'confirmed' }) })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'confirm' } }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, status: 'confirmed', action: 'confirm' })
expect(transitionSalesOrder).toHaveBeenCalledWith(supabase, { companyId: 'company-1', orderId: ORDER_ID, action: 'confirm' })
})
it('maps SALES_ORDER_HAS_INVOICES onto a 409 auto-reject', async () => {
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_HAS_INVOICES' })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'cancel' } }),
)
expect(result.status).toBe('rejected')
expect(result.http_status).toBe(409)
expect(result.code).toBe('SALES_ORDER_HAS_INVOICES')
expect(result.error).toMatch(/fakturor/i)
})
it('rejects an action outside the enum before the service runs', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'complete' } }),
)
expect(result.status).not.toBe('committed')
expect(result.error).toMatch(/action/)
expect(transitionSalesOrder).not.toHaveBeenCalled()
})
})
describe('commitPendingOperation: register_sales_order_delivery', () => {
const params = {
sales_order_id: ORDER_ID,
delivery_date: '2026-09-02',
lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }],
}
it('happy path: passes the cumulative quantities to the service', async () => {
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
ok: true,
order: makeOrder({ status: 'confirmed', last_delivery_date: '2026-09-02', delivery_progress: 'partial' }),
})
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, last_delivery_date: '2026-09-02', delivery_progress: 'partial' })
expect(registerSalesOrderDelivery).toHaveBeenCalledWith(supabase, {
companyId: 'company-1',
orderId: ORDER_ID,
input: { delivery_date: '2026-09-02', lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }] },
})
})
it('maps SALES_ORDER_OVER_DELIVERED (400) onto a failed op with the line details', async () => {
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
ok: false,
code: 'SALES_ORDER_OVER_DELIVERED',
details: { sales_order_item_id: ITEM_ID, quantity: 3, delivered_qty: 4 },
})
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(400)
expect(result.code).toBe('SALES_ORDER_OVER_DELIVERED')
expect(result.data).toMatchObject({ sales_order_item_id: ITEM_ID, quantity: 3 })
})
})
describe('commitPendingOperation: create_invoice_from_sales_order', () => {
const params = { sales_order_id: ORDER_ID, mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' }
const invoice = { id: INVOICE_ID, invoice_number: null, status: 'draft', total: 1250, currency: 'SEK' }
it('happy path: creates the draft through the service and emits invoice.created', async () => {
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
ok: true,
invoice: invoice as never,
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
})
const handler = vi.fn()
eventBus.on('invoice.created', handler)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } }) // CAS claim
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
enqueue({ data: null }) // finalize
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({
invoice_id: INVOICE_ID,
invoice_number: null,
sales_order_id: ORDER_ID,
order_status: 'completed',
invoicing_progress: 'full',
})
expect(createInvoiceFromSalesOrder).toHaveBeenCalledWith(supabase, {
companyId: 'company-1',
userId: 'user-1',
orderId: ORDER_ID,
input: { mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' },
})
expect(handler).toHaveBeenCalledTimes(1)
// Handlers receive the payload, not the envelope.
expect(handler.mock.calls[0][0]).toMatchObject({
invoice: expect.objectContaining({ id: INVOICE_ID }),
userId: 'user-1',
companyId: 'company-1',
})
})
it('still commits when the invoice.created emit rejects (the draft already exists)', async () => {
// eventBus.emit settles handler failures itself, so the only way the emit
// can reject is the bus throwing; the executor must treat that as a
// post-commit notification failure, not as a failed operation.
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
ok: true,
invoice: invoice as never,
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
})
const emitSpy = vi.spyOn(eventBus, 'emit').mockRejectedValueOnce(new Error('bus down'))
try {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } }) // CAS claim
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
enqueue({ data: null }) // finalize
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({ invoice_id: INVOICE_ID, sales_order_id: ORDER_ID })
expect(emitSpy).toHaveBeenCalledWith(
expect.objectContaining({ type: 'invoice.created' }),
)
} finally {
emitSpy.mockRestore()
}
})
it('maps SALES_ORDER_NOTHING_TO_INVOICE onto a 409 auto-reject and emits nothing', async () => {
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
const handler = vi.fn()
eventBus.on('invoice.created', handler)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
)
expect(result.status).toBe('rejected')
expect(result.http_status).toBe(409)
expect(result.code).toBe('SALES_ORDER_NOTHING_TO_INVOICE')
expect(handler).not.toHaveBeenCalled()
})
it('rejects a non-positive explicit pick at the commit boundary', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never, 'user-1', 'company-1',
makePendingOp({
operation_type: 'create_invoice_from_sales_order',
params: { sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, quantity: 0 }] },
}),
)
expect(result.status).not.toBe('committed')
expect(result.error).toMatch(/lines\.0\.quantity/)
expect(createInvoiceFromSalesOrder).not.toHaveBeenCalled()
})
})
@@ -6,6 +6,7 @@ import { commitPendingOperation } from '../commit'
const INVOICE_ID = '22222222-2222-4222-8222-222222222222'
const CUSTOMER_ID = '11111111-1111-4111-8111-111111111111'
const SALES_ORDER_ITEM_ID = 'd1000000-0000-4000-8000-000000000001'
function makePendingOp(params: Record<string, unknown>): PendingOperation {
return {
@@ -88,6 +89,7 @@ describe('commitPendingOperation: update_invoice', () => {
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
enqueue({ data: { vat_registered: true } }) // company_settings (builder VAT gate)
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (draft-guarded)
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no prior rows)
enqueue({ data: null }) // invoice_items delete
enqueue({ data: null }) // invoice_items insert
enqueue({ data: null }) // pending_operations final status update
@@ -110,8 +112,10 @@ describe('commitPendingOperation: update_invoice', () => {
items_replaced: true,
})
expect(supabase.from).toHaveBeenNthCalledWith(2, 'invoices')
// snapshot, delete, insert
expect(supabase.from).toHaveBeenNthCalledWith(6, 'invoice_items')
expect(supabase.from).toHaveBeenNthCalledWith(7, 'invoice_items')
expect(supabase.from).toHaveBeenNthCalledWith(8, 'invoice_items')
})
it('keeps the existing lines on a header-only edit (no full replace staged)', async () => {
@@ -146,6 +150,7 @@ describe('commitPendingOperation: update_invoice', () => {
})
enqueue({ data: { vat_registered: true } }) // company_settings
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no order links)
enqueue({ data: null }) // invoice_items delete
enqueue({ data: null }) // invoice_items insert
enqueue({ data: null }) // final status update
@@ -306,6 +311,96 @@ describe('commitPendingOperation: update_invoice', () => {
expect(findCall('invoice_items', 'insert')).toBeUndefined()
})
it('auto-rejects with INVOICE_UPDATE_DROPS_ORDER_LINK when replaced lines drop a kundorder link', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-invoice-1' } }) // claim
enqueue({ data: existingDraft() }) // invoices: existing draft (created from an order)
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
enqueue({ data: { vat_registered: true } }) // company_settings
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (header)
enqueue({
// invoice_items snapshot (replaceInvoiceItems): the stored row is linked
// to an order line; the staged items carry no sales_order_item_id.
data: [{ id: 'item-old-1', invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID, description: 'Orderrad' }],
})
enqueue({ data: null }) // pending_operations final status update
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({ invoice_id: INVOICE_ID, changes: { items: NEW_ITEMS } }),
)
// 409 from the executor: auto-rejected with the structured code so the
// approver sees WHY, same as the cookie and v1 PATCH routes.
expect(result.status).toBe('rejected')
expect(result.auto_rejected).toBe(true)
expect(result.http_status).toBe(409)
expect(result.code).toBe('INVOICE_UPDATE_DROPS_ORDER_LINK')
expect(result.error).toMatch(/kundorder/)
// The guard fires before the delete: the lines are untouched.
expect(findCall('invoice_items', 'delete')).toBeUndefined()
expect(findCall('invoice_items', 'insert')).toBeUndefined()
})
it('keeps the kundorder link on a header-only edit (re-fetch carries sales_order_item_id)', async () => {
const { supabase, enqueue, findCall, findCalls } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-invoice-1' } }) // claim
enqueue({ data: existingDraft() }) // invoices
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
enqueue({
// invoice_items re-fetch for the header-only edit
data: [
{
line_type: 'product',
description: 'Orderrad',
quantity: 4,
unit: 'h',
unit_price: 100,
discount_percent: null,
vat_rate: 25,
article_id: null,
revenue_account: null,
sales_order_item_id: SALES_ORDER_ITEM_ID,
deduction_type: null,
labor_hours: null,
work_type: null,
housing_designation: null,
apartment_number: null,
brf_org_number: null,
accrual_period_start: null,
accrual_period_end: null,
accrual_balance_account: null,
dimensions: {},
},
],
})
enqueue({ data: { vat_registered: true } }) // company_settings
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
enqueue({ data: [{ id: 'item-old-1', sales_order_item_id: SALES_ORDER_ITEM_ID }] }) // snapshot
enqueue({ data: null }) // invoice_items delete
enqueue({ data: null }) // invoice_items insert
enqueue({ data: null }) // final status update
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'Ny anteckning' } }),
)
expect(result.status).toBe('committed')
expect(result.data).toMatchObject({ items_replaced: false, item_count: 1 })
// The narrow re-fetch must include the link column, or the guard would
// refuse every header-only edit of an order-created draft.
const refetchColumns = findCalls('invoice_items', 'select')[0][0] as string
expect(refetchColumns.split(',').map((c) => c.trim())).toContain('sales_order_item_id')
const inserted = findCall('invoice_items', 'insert')![0] as Array<Record<string, unknown>>
expect(inserted).toHaveLength(1)
expect(inserted[0]).toMatchObject({ invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID })
})
it('rejects tampered staged params before reading the invoice', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-invoice-1' } })
+213 -1
View File
@@ -156,6 +156,17 @@ import { defaultRateForVatTreatment } from '@/lib/vat/account-vat-treatment'
import { SetVoucherNoteParamsSchema } from '@/lib/pending-operations/schemas/voucher-note'
import { IgnoreTransactionParamsSchema } from '@/lib/pending-operations/schemas/ignore-transaction'
import { setTransactionIgnored } from '@/lib/transactions/ignore'
import {
CreateInvoiceFromSalesOrderParamsSchema,
CreateSalesOrderParamsSchema,
RegisterSalesOrderDeliveryParamsSchema,
TransitionSalesOrderParamsSchema,
} from '@/lib/pending-operations/schemas/sales-order'
import { createSalesOrder } from '@/lib/sales-orders/write'
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
import type { ServiceFailure } from '@/lib/sales-orders/result'
import { UpdateCompanySettingsParamsSchema } from '@/lib/pending-operations/schemas/company-settings'
import { UpdateCustomerParamsSchema } from '@/lib/pending-operations/schemas/customer'
import {
@@ -1282,6 +1293,192 @@ async function commitIgnoreTransaction(
}
}
// ── Kundorder (sales orders) ────────────────────────────────────────
//
// The four executors below never touch totals, VAT or the order state
// machine themselves: they re-validate the staged params (ASVS V4.5) and
// hand them to the lib/sales-orders service the cookie routes use, so the
// MCP door and the web door produce identical rows and identical refusals.
/** Zod failure on a staged row -> 400 with the first issue named. */
function invalidStagedParams(err: unknown): ExecutorResult {
if (err instanceof z.ZodError) {
const issue = err.issues[0]
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
}
throw err
}
/**
* Map a lib/sales-orders ServiceFailure onto the ExecutorResult contract.
* A coded failure carries the structured-error httpStatus (404/409 auto-
* reject the op, 400 fails it) and its Swedish message, with the service's
* details persisted so the approver sees WHICH line was refused; a raw DB
* failure is a 500 with the driver message.
*/
function salesOrderFailure(failure: ServiceFailure): ExecutorResult {
if ('code' in failure) {
const entry = getErrorEntry(failure.code)
return {
error: entry?.message_sv ?? failure.code,
errorCode: failure.code,
status: entry?.httpStatus ?? 400,
...(failure.details ? { data: failure.details } : {}),
}
}
const dbMessage =
typeof failure.dbError === 'object' && failure.dbError !== null && 'message' in failure.dbError
? String((failure.dbError as { message: unknown }).message)
: null
return { error: dbMessage || getErrorEntry('SALES_ORDER_CREATE_FAILED')?.message_sv || 'Kundordern kunde inte sparas.', status: 500 }
}
async function commitCreateSalesOrder(
supabase: SupabaseClient,
userId: string,
companyId: string,
params: Record<string, unknown>
): Promise<ExecutorResult> {
let validated
try {
validated = CreateSalesOrderParamsSchema.parse(params)
} catch (err) {
return invalidStagedParams(err)
}
const result = await createSalesOrder(supabase, { companyId, userId, input: validated })
if (!result.ok) return salesOrderFailure(result)
const { order } = result
return {
data: {
sales_order_id: order.id,
order_number: order.order_number,
status: order.status,
total: order.total,
currency: order.currency,
},
}
}
async function commitTransitionSalesOrder(
supabase: SupabaseClient,
companyId: string,
params: Record<string, unknown>
): Promise<ExecutorResult> {
let validated
try {
validated = TransitionSalesOrderParamsSchema.parse(params)
} catch (err) {
return invalidStagedParams(err)
}
// The service re-reads the order and refuses a transition the current
// status does not allow (compare-and-set), so an order that moved between
// staging and approval lands as SALES_ORDER_INVALID_STATE, never as a
// silent overwrite.
const result = await transitionSalesOrder(supabase, {
companyId,
orderId: validated.sales_order_id,
action: validated.action,
})
if (!result.ok) return salesOrderFailure(result)
const { order } = result
return {
data: {
sales_order_id: order.id,
order_number: order.order_number,
status: order.status,
action: validated.action,
},
}
}
async function commitRegisterSalesOrderDelivery(
supabase: SupabaseClient,
companyId: string,
params: Record<string, unknown>
): Promise<ExecutorResult> {
let validated
try {
validated = RegisterSalesOrderDeliveryParamsSchema.parse(params)
} catch (err) {
return invalidStagedParams(err)
}
const { sales_order_id: orderId, ...input } = validated
const result = await registerSalesOrderDelivery(supabase, { companyId, orderId, input })
if (!result.ok) return salesOrderFailure(result)
const { order } = result
return {
data: {
sales_order_id: order.id,
order_number: order.order_number,
status: order.status,
last_delivery_date: order.last_delivery_date,
delivery_progress: order.delivery_progress ?? null,
},
}
}
async function commitCreateInvoiceFromSalesOrder(
supabase: SupabaseClient,
userId: string,
companyId: string,
params: Record<string, unknown>
): Promise<ExecutorResult> {
let validated
try {
validated = CreateInvoiceFromSalesOrderParamsSchema.parse(params)
} catch (err) {
return invalidStagedParams(err)
}
// The service re-reads the order, re-picks the lines against the CURRENT
// invoiced quantities and builds the draft through buildInvoiceWriteData,
// so a line invoiced elsewhere between staging and approval is refused
// (SALES_ORDER_OVER_INVOICED / NOTHING_TO_INVOICE) instead of double-billed.
const { sales_order_id: orderId, ...input } = validated
const result = await createInvoiceFromSalesOrder(supabase, { companyId, userId, orderId, input })
if (!result.ok) return salesOrderFailure(result)
const { invoice, order } = result
// Same event the direct create_invoice executor emits, so extension
// handlers (webhooks, digests) see order-born drafts too.
const { data: completeInvoice } = await supabase
.from('invoices')
.select('*, customer:customers(*), items:invoice_items(*)')
.eq('id', invoice.id)
.single()
// Post-commit notification only: the draft already exists, so an event
// failure must not reject an operation whose write succeeded.
try {
await eventBus.emit({
type: 'invoice.created',
payload: { invoice: (completeInvoice ?? invoice) as Invoice, userId, companyId },
})
} catch {
// Non-critical
}
return {
data: {
invoice_id: invoice.id,
// Unnumbered draft: the F-series number is assigned on send.
invoice_number: invoice.invoice_number ?? null,
sales_order_id: order.id,
order_number: order.order_number,
order_status: order.status,
invoicing_progress: order.invoicing_progress ?? null,
total: invoice.total,
currency: invoice.currency,
},
}
}
async function commitCreateSupplier(
supabase: SupabaseClient,
userId: string,
@@ -2061,7 +2258,7 @@ async function commitUpdateInvoice(
const { data: itemRows, error: itemsFetchError } = await supabase
.from('invoice_items')
.select(
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, sales_order_item_id, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
)
.eq('invoice_id', invoiceId)
.order('sort_order', { ascending: true })
@@ -2150,6 +2347,9 @@ async function commitUpdateInvoice(
const replaced = await replaceInvoiceItems(supabase, invoiceId, build.items)
if (!replaced.ok) {
if (replaced.stage === 'guard') {
return { error: replaced.messageSv, errorCode: replaced.code, status: 409 }
}
return {
error: `Fakturaraderna kunde inte skrivas om (${replaced.stage}): ${replaced.error.message}`,
status: 500,
@@ -6759,6 +6959,18 @@ async function commitPendingOperationInner(
case 'ignore_transaction':
result = await commitIgnoreTransaction(supabase, companyId, pendingOp.params)
break
case 'create_sales_order':
result = await commitCreateSalesOrder(supabase, userId, companyId, pendingOp.params)
break
case 'transition_sales_order':
result = await commitTransitionSalesOrder(supabase, companyId, pendingOp.params)
break
case 'register_sales_order_delivery':
result = await commitRegisterSalesOrderDelivery(supabase, companyId, pendingOp.params)
break
case 'create_invoice_from_sales_order':
result = await commitCreateInvoiceFromSalesOrder(supabase, userId, companyId, pendingOp.params)
break
case 'create_dimension_value':
result = await commitCreateDimensionValue(supabase, userId, companyId, pendingOp.params)
break
+13
View File
@@ -51,6 +51,15 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
// and the executor's isTransactionBooked() refusal keep it off booked rows,
// so the op cannot hide a booking even if tampered with (issue #1661).
ignore_transaction: 'low',
// Kundorder (sales orders) never book: an order is the non-ledger document
// between agreement and invoice. Creating one, moving it through its
// header state machine (confirm / cancel / reopen) and registering
// delivered quantities write only sales_orders / sales_order_items, no
// verifikat and no external side-effect, and all three are re-editable
// (cancel is refused while invoices exist, reopen undoes it).
create_sales_order: 'low',
transition_sales_order: 'low',
register_sales_order_delivery: 'low',
// ── Medium: reversible booking ─────────────────────────────────────
categorize_transaction: 'medium',
@@ -70,6 +79,10 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
// create_invoice: the target has no verifikat yet (isEditableInvoiceDraft
// is re-checked at commit), so the edit is fully reversible by editing again.
update_invoice: 'medium',
// Creates an unnumbered DRAFT kundfaktura from a confirmed order through
// the same builder as create_invoice (nothing is booked or sent at commit;
// the draft can be deleted). Same tier as create_invoice.
create_invoice_from_sales_order: 'medium',
// Recurring invoice schedules: the commit only creates/edits the monthly
// template (nothing is booked or sent at commit time), and the schedule is
// pausable/deletable before the next cron run. Not 'low' because an
@@ -0,0 +1,35 @@
import { z } from 'zod'
import {
CreateInvoiceFromSalesOrderSchema,
CreateSalesOrderSchema,
RegisterSalesOrderDeliverySchema,
SalesOrderTransitionSchema,
} from '@/lib/api/schemas'
// Commit-boundary re-validation for the staged kundorder (sales order)
// operations. A staged pending_operations row is re-parsed here before the
// lib/sales-orders service runs so a tampered row cannot inject unexpected
// fields or malformed data (defense in depth, ASVS V4.5): mirrors
// lib/pending-operations/schemas/article.ts.
//
// The shapes are the same Zod schemas the cookie routes under
// app/api/sales-orders validate with, so the MCP door and the web door
// accept exactly the same payloads. Every executor also needs the target
// order, which the route carries in the URL and the staged params carry as
// sales_order_id.
const salesOrderId = z.string().uuid()
export const CreateSalesOrderParamsSchema = CreateSalesOrderSchema
export const TransitionSalesOrderParamsSchema = SalesOrderTransitionSchema.extend({
sales_order_id: salesOrderId,
})
export const RegisterSalesOrderDeliveryParamsSchema = RegisterSalesOrderDeliverySchema.extend({
sales_order_id: salesOrderId,
})
export const CreateInvoiceFromSalesOrderParamsSchema = CreateInvoiceFromSalesOrderSchema.extend({
sales_order_id: salesOrderId,
})
+9
View File
@@ -1066,6 +1066,15 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
// Webshop order rows are booking underlag (and carry customer personal
// data), so they belong in the archive like transactions do.
{ name: 'webshop_orders', file: 'webshop_orders.json', orderBy: 'order_date' },
// Kundorder: non-ledger sales documents. Not räkenskapsinformation on
// their own, but the provenance of invoices created from them
// (invoices.sales_order_id / invoice_items.sales_order_item_id) points
// here, so a revisor reading the archive can follow the link.
{ name: 'sales_orders', file: 'sales_orders.json', orderBy: 'order_date' },
// Direct dump (the coverage contract requires it for a table with its own
// company_id); the line's currency is the parent order's, one file over,
// joined by sales_order_id.
{ name: 'sales_order_items', file: 'sales_order_items.json', orderBy: 'created_at' },
{ name: 'webshop_store_settings', file: 'webshop_store_settings.json' },
{ name: 'transaction_voucher_links', file: 'transaction_voucher_links.json' },
{ name: 'bank_file_imports', file: 'bank_file_imports.json', orderBy: 'created_at' },
@@ -0,0 +1,571 @@
/**
* pickLines (pure) and createInvoiceFromSalesOrder (queued mock, with the
* invoice builder mocked).
*
* createInvoiceFromSalesOrder queue order: loadSalesOrder (sales_orders
* select, invoiced rpc), customers select, invoices insert, invoice_items
* insert, then loadSalesOrder again. On an items-insert failure the two
* rollback deletes (invoice_items, invoices) come before the failure returns.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { IDS, invoicedRow, makeOrderCustomer, makeSalesOrder, makeSalesOrderItem } from './fixtures'
const mockBuildInvoiceWriteData = vi.fn()
vi.mock('@/lib/invoices/build-invoice-write', () => ({
buildInvoiceWriteData: (...args: unknown[]) => mockBuildInvoiceWriteData(...args),
}))
import { createInvoiceFromSalesOrder, deliveryDateFor, pickLines } from '../create-invoice-from-order'
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
const sb = supabase as unknown as SupabaseClient
function orderWith(items = [makeSalesOrderItem()], overrides = {}) {
return makeSalesOrder({ status: 'confirmed', confirmed_at: '2026-09-01T10:00:00Z', items, ...overrides })
}
describe('pickLines', () => {
const order = makeSalesOrder({
items: [
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, remaining_qty: 8 }),
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 4, delivered_qty: 0, invoiced_qty: 4, remaining_qty: 0 }),
makeSalesOrderItem({ id: IDS.item3, sort_order: 2, line_type: 'text', quantity: 0, delivered_qty: 0 }),
],
})
it('refuses an explicit pick above the remaining quantity', () => {
const result = pickLines(order, { lines: [{ sales_order_item_id: IDS.item1, quantity: 9 }] })
expect(result).toMatchObject({
ok: false,
code: 'SALES_ORDER_OVER_INVOICED',
details: { sales_order_item_id: IDS.item1, remaining_qty: 8, requested_qty: 9 },
})
})
it('accepts an explicit pick at exactly the remaining quantity', () => {
const result = pickLines(order, { lines: [{ sales_order_item_id: IDS.item1, quantity: 8 }] })
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.picked).toHaveLength(1)
expect(result.picked[0]).toMatchObject({ quantity: 8, item: { id: IDS.item1 } })
})
it('derives remaining from quantity - invoiced_qty when remaining_qty is absent', () => {
const bare = makeSalesOrder({ items: [makeSalesOrderItem({ id: IDS.item1, quantity: 10, invoiced_qty: 7 })] })
expect(pickLines(bare, { lines: [{ sales_order_item_id: IDS.item1, quantity: 4 }] })).toMatchObject({
ok: false,
code: 'SALES_ORDER_OVER_INVOICED',
details: { remaining_qty: 3 },
})
})
it('refuses an explicit pick of a text row or an unknown line', () => {
expect(pickLines(order, { lines: [{ sales_order_item_id: IDS.item3, quantity: 1 }] })).toMatchObject({
ok: false,
code: 'SALES_ORDER_LINE_NOT_FOUND',
})
expect(pickLines(order, { lines: [{ sales_order_item_id: IDS.unknownItem, quantity: 1 }] })).toMatchObject({
ok: false,
code: 'SALES_ORDER_LINE_NOT_FOUND',
details: { sales_order_item_id: IDS.unknownItem },
})
})
it('mode remaining (default) picks everything not yet invoiced', () => {
const result = pickLines(order, {})
expect(result.ok).toBe(true)
if (!result.ok) return
// item2 is fully invoiced, the text row never counts.
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item1, 8]])
})
it('mode delivered picks delivered minus invoiced, capped at remaining', () => {
const result = pickLines(order, { mode: 'delivered' })
expect(result.ok).toBe(true)
if (!result.ok) return
// item1: delivered 5 - invoiced 2 = 3
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item1, 3]])
})
it('mode delivered never goes negative when more is invoiced than delivered', () => {
const advance = makeSalesOrder({
items: [
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 1, invoiced_qty: 5 }),
makeSalesOrderItem({ id: IDS.item2, sort_order: 1, quantity: 10, delivered_qty: 6, invoiced_qty: 5 }),
],
})
const result = pickLines(advance, { mode: 'delivered' })
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.picked.map((p) => [p.item.id, p.quantity])).toEqual([[IDS.item2, 1]])
})
it('returns SALES_ORDER_NOTHING_TO_INVOICE when every line is fully invoiced', () => {
const done = makeSalesOrder({
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 4, invoiced_qty: 4, remaining_qty: 0 })],
})
expect(pickLines(done, {})).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
expect(pickLines(done, { mode: 'delivered' })).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
})
it('returns SALES_ORDER_NOTHING_TO_INVOICE in delivered mode when nothing was delivered', () => {
const undelivered = makeSalesOrder({ items: [makeSalesOrderItem({ quantity: 4, delivered_qty: 0 })] })
expect(pickLines(undelivered, { mode: 'delivered' })).toMatchObject({
ok: false,
code: 'SALES_ORDER_NOTHING_TO_INVOICE',
})
})
it('treats an empty explicit lines array like no picks', () => {
const result = pickLines(order, { lines: [] })
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.picked.map((p) => p.item.id)).toEqual([IDS.item1])
})
it('sums duplicate picks of the same line into one invoice line', () => {
const result = pickLines(order, {
lines: [
{ sales_order_item_id: IDS.item1, quantity: 3 },
{ sales_order_item_id: IDS.item1, quantity: 5 },
],
})
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.picked).toHaveLength(1)
expect(result.picked[0]).toMatchObject({ quantity: 8, item: { id: IDS.item1 } })
})
it('refuses duplicate picks whose SUM exceeds the remaining quantity', () => {
// 5 and 4 each fit within the remaining 8; together they do not.
const result = pickLines(order, {
lines: [
{ sales_order_item_id: IDS.item1, quantity: 5 },
{ sales_order_item_id: IDS.item1, quantity: 4 },
],
})
expect(result).toMatchObject({
ok: false,
code: 'SALES_ORDER_OVER_INVOICED',
details: { sales_order_item_id: IDS.item1, remaining_qty: 8, requested_qty: 9 },
})
})
it('accepts a pick equal to a float remainder (7.5 ordered, 6.9 invoiced, pick 0.6)', () => {
// 7.5 - 6.9 is 0.5999999999999996 in doubles; the pick must still fit.
const fractional = makeSalesOrder({
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 7.5, invoiced_qty: 6.9 })],
})
const explicit = pickLines(fractional, { lines: [{ sales_order_item_id: IDS.item1, quantity: 0.6 }] })
expect(explicit.ok).toBe(true)
if (!explicit.ok) return
expect(explicit.picked[0].quantity).toBe(0.6)
const remaining = pickLines(fractional, {})
expect(remaining.ok).toBe(true)
if (!remaining.ok) return
expect(remaining.picked[0].quantity).toBe(0.6)
})
it('rounds a summed fractional pick before comparing it to the remainder', () => {
const fractional = makeSalesOrder({
items: [makeSalesOrderItem({ id: IDS.item1, quantity: 1, invoiced_qty: 0.7 })],
})
// 0.1 + 0.2 = 0.30000000000000004 in doubles; remaining is exactly 0.3.
const result = pickLines(fractional, {
lines: [
{ sales_order_item_id: IDS.item1, quantity: 0.1 },
{ sales_order_item_id: IDS.item1, quantity: 0.2 },
],
})
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.picked[0].quantity).toBe(0.3)
})
})
describe('deliveryDateFor', () => {
it('is the latest per-line last_delivery_date when every pick is covered by deliveries', () => {
const picked = [
{
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, last_delivery_date: '2026-08-20' }),
quantity: 3,
},
{
item: makeSalesOrderItem({ id: IDS.item2, quantity: 4, delivered_qty: 4, invoiced_qty: 0, last_delivery_date: '2026-08-30' }),
quantity: 4,
},
]
expect(deliveryDateFor(picked)).toBe('2026-08-30')
})
it('is null when a pick exceeds what was delivered but not yet invoiced (advance invoice)', () => {
const picked = [
{
// delivered 5 - invoiced 2 = 3 available; picking 4 reaches undelivered quantity.
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 2, last_delivery_date: '2026-08-20' }),
quantity: 4,
},
]
expect(deliveryDateFor(picked)).toBeNull()
expect(
deliveryDateFor([
{ item: makeSalesOrderItem({ quantity: 10, delivered_qty: 0, last_delivery_date: null }), quantity: 1 },
]),
).toBeNull()
})
it('is null when any covered line lacks a per-line delivery date', () => {
const picked = [
{
item: makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 5, invoiced_qty: 0, last_delivery_date: '2026-08-20' }),
quantity: 5,
},
{
// Delivered before per-line dates existed: no date to anchor on.
item: makeSalesOrderItem({ id: IDS.item2, quantity: 4, delivered_qty: 4, invoiced_qty: 0, last_delivery_date: null }),
quantity: 4,
},
]
expect(deliveryDateFor(picked)).toBeNull()
})
it('tolerates float drift in the covered check (7.5 delivered, 6.9 invoiced, pick 0.6)', () => {
const picked = [
{
item: makeSalesOrderItem({ id: IDS.item1, quantity: 7.5, delivered_qty: 7.5, invoiced_qty: 6.9, last_delivery_date: '2026-08-30' }),
quantity: 0.6,
},
]
expect(deliveryDateFor(picked)).toBe('2026-08-30')
})
})
const okBuild = {
ok: true,
invoiceFields: {
customer_id: IDS.customer,
invoice_date: '2026-09-02',
due_date: '2026-10-02',
currency: 'SEK',
subtotal: 800,
vat_amount: 200,
total: 1000,
vat_treatment: 'standard_25',
},
items: [
{
sort_order: 0,
line_type: 'product',
description: 'Konsulttimme',
quantity: 8,
unit: 'h',
unit_price: 100,
line_total: 800,
vat_rate: 25,
vat_amount: 200,
sales_order_item_id: IDS.item1,
},
],
}
describe('createInvoiceFromSalesOrder', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockBuildInvoiceWriteData.mockResolvedValue(okBuild)
})
const params = { companyId: IDS.company, userId: IDS.user, orderId: IDS.order }
it('returns SALES_ORDER_NOT_FOUND for a missing order', async () => {
enqueue({ data: null })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOT_FOUND' })
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
})
it('refuses invoicing an order that is not confirmed', async () => {
enqueue({ data: makeSalesOrder({ status: 'draft' }) })
enqueue({ data: [] })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({
ok: false,
code: 'SALES_ORDER_INVALID_STATE',
details: { status: 'draft', action: 'invoice' },
})
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
})
it('refuses when nothing remains to invoice', async () => {
enqueue({ data: orderWith([makeSalesOrderItem({ id: IDS.item1, quantity: 4 })]) })
enqueue({ data: [invoicedRow(IDS.item1, 4)] })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
expect(findCall('invoices', 'insert')).toBeUndefined()
})
it('returns CUSTOMER_NOT_FOUND when the raw customer row is gone', async () => {
enqueue({ data: orderWith() })
enqueue({ data: [] })
enqueue({ data: null })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: IDS.customer } })
})
it('creates an unnumbered draft linked to the order, each line carrying its sales_order_item_id', async () => {
enqueue({
data: orderWith(
[
makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 0, discount_percent: 10 }),
makeSalesOrderItem({ id: IDS.item3, sort_order: 1, line_type: 'text', description: 'Tack', quantity: 0 }),
],
{ order_number: 'OR-7', your_reference: 'Anna', last_delivery_date: '2026-08-30' },
),
})
enqueue({ data: [invoicedRow(IDS.item1, 2)] })
enqueue({ data: makeOrderCustomer({ default_payment_terms: 20 }) })
enqueue({ data: { id: IDS.invoice, status: 'draft', invoice_number: null, sales_order_id: IDS.order } })
enqueue({ data: null }) // invoice_items insert
enqueue({ data: orderWith() }) // reload
enqueue({ data: [invoicedRow(IDS.item1, 10)] })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: { invoice_date: '2026-09-02' } })
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.invoice.id).toBe(IDS.invoice)
expect(result.order.invoicing_progress).toBe('full')
// Builder input: the remaining 8 of item1, the text row carried along,
// sales_order_item_id on the product line, due date from customer terms,
// no delivery date because nothing was delivered.
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as {
documentType: string
input: { items: Record<string, unknown>[]; due_date: string; delivery_date: unknown; notes?: string; your_reference?: string }
}
expect(buildArg.documentType).toBe('invoice')
expect(buildArg.input.due_date).toBe('2026-09-22')
expect(buildArg.input.delivery_date).toBeNull()
expect(buildArg.input.notes).toBe('Kundorder OR-7')
expect(buildArg.input.your_reference).toBe('Anna')
expect(buildArg.input.items).toEqual([
expect.objectContaining({
line_type: 'product',
quantity: 8,
unit_price: 100,
discount_percent: 10,
vat_rate: 25,
sales_order_item_id: IDS.item1,
}),
expect.objectContaining({ line_type: 'text', description: 'Tack', quantity: 0 }),
])
const invoiceInsert = findCall('invoices', 'insert')![0] as Record<string, unknown>
expect(invoiceInsert).toMatchObject({
user_id: IDS.user,
company_id: IDS.company,
invoice_number: null,
status: 'draft',
sales_order_id: IDS.order,
subtotal: 800,
total: 1000,
})
const itemRows = findCall('invoice_items', 'insert')![0] as Record<string, unknown>[]
expect(itemRows).toHaveLength(1)
for (const row of itemRows) {
expect(row.invoice_id).toBe(IDS.invoice)
expect(row.sales_order_item_id).toBe(IDS.item1)
}
expect(findCall('invoices', 'delete')).toBeUndefined()
})
it('sets delivery_date from the picked lines when the pick is covered by deliveries', async () => {
// The header last_delivery_date is display-only and deliberately later
// than the line's date: the invoice must take the LINE date.
enqueue({
data: orderWith(
[makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4, last_delivery_date: '2026-08-30' })],
{ last_delivery_date: '2026-09-01' },
),
})
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null })
enqueue({ data: orderWith() })
enqueue({ data: [] })
const result = await createInvoiceFromSalesOrder(sb, {
...params,
input: { mode: 'delivered', due_date: '2026-09-30' },
})
expect(result.ok).toBe(true)
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as { input: { delivery_date: unknown; due_date: string; items: { quantity: number }[] } }
expect(buildArg.input.delivery_date).toBe('2026-08-30')
expect(buildArg.input.due_date).toBe('2026-09-30')
expect(buildArg.input.items[0].quantity).toBe(4)
})
it('leaves delivery_date null when the pick reaches undelivered quantity (advance invoice)', async () => {
enqueue({
data: orderWith(
[makeSalesOrderItem({ id: IDS.item1, quantity: 10, delivered_qty: 4, last_delivery_date: '2026-08-30' })],
{ last_delivery_date: '2026-08-30' },
),
})
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null })
enqueue({ data: orderWith() })
enqueue({ data: [] })
// mode remaining: all 10, of which only 4 were delivered.
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: { due_date: '2026-09-30' } })
expect(result.ok).toBe(true)
const buildArg = mockBuildInvoiceWriteData.mock.calls[0][0] as { input: { delivery_date: unknown; items: { quantity: number }[] } }
expect(buildArg.input.delivery_date).toBeNull()
expect(buildArg.input.items[0].quantity).toBe(10)
})
it('refuses with SALES_ORDER_CUSTOMER_VAT_CHANGED when the customer type differs from the order snapshot', async () => {
enqueue({
data: orderWith([makeSalesOrderItem()], {
customer_type_snapshot: 'swedish_business',
customer_vat_validated_snapshot: false,
}),
})
enqueue({ data: [] })
// Since validated as an EU business: the frozen 25 % line would pass the
// permitted-set gate but is no longer what the customer should be charged.
enqueue({
data: makeOrderCustomer({ customer_type: 'eu_business', vat_number: 'DE123456789', vat_number_validated: true }),
})
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({
ok: false,
code: 'SALES_ORDER_CUSTOMER_VAT_CHANGED',
details: {
snapshot: { customer_type: 'swedish_business', vat_number_validated: false },
current: { customer_type: 'eu_business', vat_number_validated: true },
},
})
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
expect(findCall('invoices', 'insert')).toBeUndefined()
})
it('refuses when only the VAT-number validation flag changed since the snapshot', async () => {
enqueue({
data: orderWith([makeSalesOrderItem()], {
customer_type_snapshot: 'eu_business',
customer_vat_validated_snapshot: false,
}),
})
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer({ customer_type: 'eu_business', vat_number_validated: true }) })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_CUSTOMER_VAT_CHANGED' })
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
})
it('treats a null validation snapshot as false and passes when the customer still matches', async () => {
enqueue({
data: orderWith([makeSalesOrderItem()], {
customer_type_snapshot: 'swedish_business',
customer_vat_validated_snapshot: null,
}),
})
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer({ customer_type: 'swedish_business', vat_number_validated: null as unknown as boolean }) })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null })
enqueue({ data: orderWith() })
enqueue({ data: [] })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result.ok).toBe(true)
expect(mockBuildInvoiceWriteData).toHaveBeenCalledTimes(1)
})
it('passes without a snapshot check when the order carries no customer_type_snapshot (pre-snapshot orders)', async () => {
enqueue({
data: orderWith([makeSalesOrderItem()], { customer_type_snapshot: null, customer_vat_validated_snapshot: null }),
})
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer({ customer_type: 'eu_business', vat_number_validated: true }) })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null })
enqueue({ data: orderWith() })
enqueue({ data: [] })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result.ok).toBe(true)
expect(mockBuildInvoiceWriteData).toHaveBeenCalledTimes(1)
expect(findCall('invoices', 'insert')).toBeDefined()
})
it('propagates a builder domain failure without inserting', async () => {
enqueue({ data: orderWith() })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
mockBuildInvoiceWriteData.mockResolvedValue({
ok: false,
code: 'INVOICE_CREATE_VAT_RULE_VIOLATION',
details: { attemptedRate: 25 },
})
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'INVOICE_CREATE_VAT_RULE_VIOLATION', details: { attemptedRate: 25 } })
expect(findCall('invoices', 'insert')).toBeUndefined()
})
it('deletes the draft and maps the over-invoice trigger when the line insert fails', async () => {
enqueue({ data: orderWith() })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({
data: null,
error: { message: 'SALES_ORDER_OVER_INVOICED: line d1000000 would exceed ordered quantity', code: 'P0001' },
})
enqueue({ data: null }) // invoice_items delete
enqueue({ data: null }) // invoices delete
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result).toMatchObject({ ok: false, code: 'SALES_ORDER_OVER_INVOICED' })
expect(findCall('invoice_items', 'delete')).toBeDefined()
expect(findCall('invoice_items', 'eq')).toEqual(['invoice_id', IDS.invoice])
expect(findCall('invoices', 'delete')).toBeDefined()
expect(findCall('invoices', 'eq')).toEqual(['id', IDS.invoice])
})
it('deletes the draft and returns the raw DB error when the line insert fails for another reason', async () => {
enqueue({ data: orderWith() })
enqueue({ data: [] })
enqueue({ data: makeOrderCustomer() })
enqueue({ data: { id: IDS.invoice, status: 'draft' } })
enqueue({ data: null, error: { message: 'null value in column "description"', code: '23502' } })
enqueue({ data: null })
enqueue({ data: null })
const result = await createInvoiceFromSalesOrder(sb, { ...params, input: {} })
expect(result.ok).toBe(false)
expect('dbError' in result && result.dbError).toMatchObject({ code: '23502' })
expect(findCall('invoices', 'delete')).toBeDefined()
})
})
+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 }
}
+188 -1
View File
@@ -44,7 +44,8 @@
"kpi": "KPIs",
"invoice_inbox": "Documents",
"invoices": "Customer invoices",
"sales_orders": "Orders",
"sales_orders": "Sales orders",
"webshop_orders": "Webshop orders",
"customers": "Customers",
"articles": "Articles",
"products": "Products",
@@ -3847,6 +3848,12 @@
"def_address": "Address",
"def_credit_note": "Credit note",
"def_credits": "Credits",
"def_sales_order": "Sales order",
"open_sales_order": "Open the sales order",
"create_order": "Create order",
"create_order_failed_title": "Could not create the order",
"order_created_toast_title": "Sales order created",
"order_created_toast_description": "Sales order {number} was created from the proforma",
"def_converted_from": "Converted from",
"payment_section": "Payment",
"payment_confirmation_label": "Payment confirmation",
@@ -7902,6 +7909,186 @@
"settings_save_failed_title": "Could not save the setting",
"settings_open_page": "Open the driving log"
},
"sales_orders": {
"title": "Sales orders",
"new_order": "New sales order",
"search_placeholder": "Search order number or customer",
"status_picker_aria": "Filter by status",
"status_all": "All",
"status_draft": "Draft",
"status_confirmed": "Confirmed",
"status_completed": "Completed",
"status_cancelled": "Cancelled",
"col_number": "No.",
"col_customer": "Customer",
"col_date": "Order date",
"col_status": "Status",
"col_delivery": "Delivery",
"col_invoicing": "Invoicing",
"col_total": "Amount",
"delivery_none": "Not delivered",
"delivery_partial": "Partly delivered",
"delivery_full": "Delivered",
"invoicing_none": "Not invoiced",
"invoicing_partial": "Partly invoiced",
"invoicing_full": "Invoiced",
"empty_title": "No sales orders yet",
"empty_description": "Create a sales order once a commitment is agreed. The order never books; delivery and invoicing are registered step by step.",
"empty_action": "Create sales order",
"no_search_results_title": "No matches",
"no_search_results_description": "No sales order matches \"{term}\".",
"no_status_results_description": "No sales orders with that status.",
"count_footer": "{count, plural, =1 {1 sales order} other {# sales orders}}",
"load_failed_title": "Could not load sales orders",
"viewer_disabled_tooltip": "You have read-only access and cannot create sales orders",
"settings_heading": "Sales orders",
"settings_toggle_label": "Enable sales orders",
"settings_toggle_help": "Shows sales orders in the menu. There you register commitments and deliveries and create invoices from the order.",
"settings_save_failed_title": "Could not save the setting",
"settings_open_page": "Open sales orders"
},
"sales_order_form": {
"title_create": "New sales order",
"title_edit": "Edit sales order {number}",
"back": "Back to sales orders",
"back_to_order": "Back to the order",
"section_customer": "Customer",
"select_customer_placeholder": "Select customer",
"loading_customers": "Loading customers...",
"no_customers_yet": "No customers yet. Add a customer first.",
"section_details": "Details",
"order_date_label": "Order date",
"requested_delivery_date_label": "Requested delivery date",
"currency_label": "Currency",
"your_reference_label": "Your reference",
"our_reference_label": "Our reference",
"notes_label": "Notes",
"section_lines": "Order lines",
"th_description": "Description",
"th_quantity": "Qty",
"th_unit": "Unit",
"th_unit_price": "Unit price",
"th_discount": "Discount %",
"th_vat": "VAT",
"th_amount": "Amount",
"article_label": "Article",
"article_free_text": "Free text",
"article_placeholder": "Search article",
"article_search_empty": "No article matches",
"description_placeholder": "Description",
"text_row_placeholder": "Text line",
"add_row": "Add line",
"add_text_row": "Add text line",
"remove_row": "Remove line",
"subtotal": "Subtotal",
"vat": "VAT",
"total": "Total",
"submit_create": "Create sales order",
"submit_edit": "Save changes",
"validation_customer_required": "Select a customer",
"validation_lines_required": "Add at least one order line with a description",
"create_failed_title": "Could not create the sales order",
"update_failed_title": "Could not save the sales order",
"created_title": "Sales order {number} created",
"updated_title": "Sales order saved",
"load_failed_title": "Could not load the sales order",
"not_editable": "The sales order cannot be edited in its current status.",
"invoiced_hint": "{qty} invoiced"
},
"sales_order_detail": {
"back": "Back to sales orders",
"title": "Sales order {number}",
"title_unnumbered": "Sales order",
"section_details": "Details",
"def_customer": "Customer",
"def_order_date": "Order date",
"def_requested_delivery_date": "Requested delivery",
"def_last_delivery_date": "Latest delivery",
"def_currency": "Currency",
"def_your_reference": "Your reference",
"def_our_reference": "Our reference",
"def_notes": "Notes",
"def_source_invoice": "Created from",
"source_proforma": "Proforma invoice",
"def_delivery": "Delivery",
"def_invoicing": "Invoicing",
"section_lines": "Order lines",
"th_description": "Description",
"th_quantity": "Qty",
"th_delivered": "Delivered",
"th_invoiced": "Invoiced",
"th_remaining": "Remaining",
"th_unit_price": "Unit price",
"th_discount": "Discount",
"th_vat": "VAT",
"th_amount": "Amount",
"subtotal": "Subtotal",
"vat": "VAT",
"total": "Total",
"action_confirm": "Confirm",
"action_register_delivery": "Register delivery",
"action_create_invoice": "Create invoice",
"action_cancel": "Cancel order",
"action_reopen": "Reopen",
"action_edit": "Edit",
"action_delete": "Delete",
"confirm_dialog_title": "Confirm sales order {number}?",
"confirm_dialog_description": "The order becomes confirmed and can be delivered and invoiced. Lines can still be edited.",
"confirm_dialog_label": "Confirm",
"cancel_dialog_title": "Cancel sales order {number}?",
"cancel_dialog_description": "The order is marked as cancelled. Nothing is booked. It can be reopened as a draft later.",
"cancel_dialog_label": "Cancel order",
"reopen_dialog_title": "Reopen sales order {number}?",
"reopen_dialog_description": "The order goes back to draft.",
"reopen_dialog_label": "Reopen",
"delete_confirm_title": "Delete sales order {number}?",
"delete_confirm_description": "The order is deleted permanently. This cannot be undone.",
"delete_confirm_label": "Delete",
"confirmed_toast": "The sales order is confirmed",
"cancelled_toast": "The sales order is cancelled",
"reopened_toast": "The sales order is reopened",
"deleted_toast": "The sales order is deleted",
"transition_failed_title": "The action failed",
"delete_failed_title": "Could not delete the sales order",
"load_failed_title": "Could not load the sales order",
"viewer_disabled_tooltip": "You have read-only access and cannot change sales orders",
"delivery_dialog_title": "Register delivery",
"delivery_dialog_description": "Enter the total delivered quantity per line. The value is cumulative, not a partial delivery.",
"delivery_date_label": "Delivery date",
"th_ordered": "Ordered",
"th_delivered_qty": "Delivered",
"deliver_all": "Mark everything as delivered",
"delivery_submit": "Register",
"delivery_success": "The delivery is registered",
"delivery_failed_title": "Could not register the delivery",
"invoice_dialog_title": "Create invoice from the order",
"invoice_dialog_description": "Enter the quantity to invoice per line. The invoice is created as a draft you review and send as usual.",
"mode_remaining": "Everything remaining",
"mode_delivered": "Delivered, not invoiced",
"th_remaining_qty": "Remaining",
"th_invoice_qty": "Invoice",
"invoice_date_label": "Invoice date",
"due_date_label": "Due date",
"invoice_submit": "Create invoice",
"invoice_created_title": "Draft invoice created",
"invoice_created_description": "Open the invoice to review and send it.",
"open_invoice": "Open the invoice",
"invoice_failed_title": "Could not create the invoice",
"section_invoices": "Invoices",
"th_invoice_number": "Invoice",
"th_invoice_status": "Status",
"th_invoice_total": "Amount",
"invoice_draft_label": "Draft",
"invoices_load_failed_title": "Could not load the invoices",
"invoice_status_draft": "Draft",
"invoice_status_sent": "Sent",
"invoice_status_paid": "Paid",
"invoice_status_partially_paid": "Partially paid",
"invoice_status_overdue": "Overdue",
"invoice_status_cancelled": "Cancelled",
"invoice_status_credited": "Credited",
"invoice_nothing_selected": "Enter a quantity on at least one line"
},
"data_analysis": {
"group_label": "Data and privacy",
"settings_heading": "Data analysis",
+188 -1
View File
@@ -44,7 +44,8 @@
"kpi": "Nyckeltal",
"invoice_inbox": "Underlag",
"invoices": "Kundfakturor",
"sales_orders": "Order",
"sales_orders": "Kundorder",
"webshop_orders": "Webshop-order",
"customers": "Kunder",
"articles": "Artiklar",
"products": "Produkter",
@@ -3847,6 +3848,12 @@
"def_address": "Adress",
"def_credit_note": "Kreditfaktura",
"def_credits": "Krediterar",
"def_sales_order": "Kundorder",
"open_sales_order": "Öppna kundordern",
"create_order": "Skapa order",
"create_order_failed_title": "Kunde inte skapa ordern",
"order_created_toast_title": "Kundorder skapad",
"order_created_toast_description": "Kundorder {number} har skapats från proforman",
"def_converted_from": "Konverterad från",
"payment_section": "Betalning",
"payment_confirmation_label": "Betalningsbekräftelse",
@@ -7902,6 +7909,186 @@
"settings_save_failed_title": "Kunde inte spara inställningen",
"settings_open_page": "Öppna körjournalen"
},
"sales_orders": {
"title": "Kundorder",
"new_order": "Ny kundorder",
"search_placeholder": "Sök ordernummer eller kund",
"status_picker_aria": "Filtrera på status",
"status_all": "Alla",
"status_draft": "Utkast",
"status_confirmed": "Bekräftad",
"status_completed": "Slutförd",
"status_cancelled": "Makulerad",
"col_number": "Nr",
"col_customer": "Kund",
"col_date": "Orderdatum",
"col_status": "Status",
"col_delivery": "Leverans",
"col_invoicing": "Fakturering",
"col_total": "Belopp",
"delivery_none": "Ej levererad",
"delivery_partial": "Delvis levererad",
"delivery_full": "Levererad",
"invoicing_none": "Ej fakturerad",
"invoicing_partial": "Delvis fakturerad",
"invoicing_full": "Fakturerad",
"empty_title": "Inga kundorder ännu",
"empty_description": "Skapa en kundorder när ni är överens om ett åtagande. Ordern bokförs inte; leverans och fakturering registreras steg för steg.",
"empty_action": "Skapa kundorder",
"no_search_results_title": "Inga träffar",
"no_search_results_description": "Ingen kundorder matchar \"{term}\".",
"no_status_results_description": "Inga kundorder med den statusen.",
"count_footer": "{count, plural, =1 {1 kundorder} other {# kundorder}}",
"load_failed_title": "Kunde inte ladda kundorder",
"viewer_disabled_tooltip": "Du har läsbehörighet och kan inte skapa kundorder",
"settings_heading": "Kundorder",
"settings_toggle_label": "Aktivera kundorder",
"settings_toggle_help": "Visar kundorder i menyn. Där registrerar du åtaganden och leveranser och skapar fakturor från ordern.",
"settings_save_failed_title": "Kunde inte spara inställningen",
"settings_open_page": "Öppna kundorder"
},
"sales_order_form": {
"title_create": "Ny kundorder",
"title_edit": "Redigera kundorder {number}",
"back": "Tillbaka till kundorder",
"back_to_order": "Tillbaka till ordern",
"section_customer": "Kund",
"select_customer_placeholder": "Välj kund",
"loading_customers": "Laddar kunder...",
"no_customers_yet": "Inga kunder ännu. Lägg till en kund först.",
"section_details": "Uppgifter",
"order_date_label": "Orderdatum",
"requested_delivery_date_label": "Önskat leveransdatum",
"currency_label": "Valuta",
"your_reference_label": "Er referens",
"our_reference_label": "Vår referens",
"notes_label": "Anteckningar",
"section_lines": "Orderrader",
"th_description": "Beskrivning",
"th_quantity": "Antal",
"th_unit": "Enhet",
"th_unit_price": "À-pris",
"th_discount": "Rabatt %",
"th_vat": "Moms",
"th_amount": "Belopp",
"article_label": "Artikel",
"article_free_text": "Egen rad",
"article_placeholder": "Sök artikel",
"article_search_empty": "Ingen artikel matchar",
"description_placeholder": "Beskrivning",
"text_row_placeholder": "Textrad",
"add_row": "Lägg till rad",
"add_text_row": "Lägg till textrad",
"remove_row": "Ta bort rad",
"subtotal": "Netto",
"vat": "Moms",
"total": "Totalt",
"submit_create": "Skapa kundorder",
"submit_edit": "Spara ändringar",
"validation_customer_required": "Välj en kund",
"validation_lines_required": "Lägg till minst en orderrad med beskrivning",
"create_failed_title": "Kunde inte skapa kundordern",
"update_failed_title": "Kunde inte spara kundordern",
"created_title": "Kundorder {number} skapad",
"updated_title": "Kundordern är sparad",
"load_failed_title": "Kunde inte ladda kundordern",
"not_editable": "Kundordern kan inte redigeras i sin nuvarande status.",
"invoiced_hint": "{qty} fakturerat"
},
"sales_order_detail": {
"back": "Tillbaka till kundorder",
"title": "Kundorder {number}",
"title_unnumbered": "Kundorder",
"section_details": "Uppgifter",
"def_customer": "Kund",
"def_order_date": "Orderdatum",
"def_requested_delivery_date": "Önskad leverans",
"def_last_delivery_date": "Senaste leverans",
"def_currency": "Valuta",
"def_your_reference": "Er referens",
"def_our_reference": "Vår referens",
"def_notes": "Anteckningar",
"def_source_invoice": "Skapad från",
"source_proforma": "Proformafaktura",
"def_delivery": "Leverans",
"def_invoicing": "Fakturering",
"section_lines": "Orderrader",
"th_description": "Beskrivning",
"th_quantity": "Antal",
"th_delivered": "Levererat",
"th_invoiced": "Fakturerat",
"th_remaining": "Återstår",
"th_unit_price": "À-pris",
"th_discount": "Rabatt",
"th_vat": "Moms",
"th_amount": "Belopp",
"subtotal": "Netto",
"vat": "Moms",
"total": "Totalt",
"action_confirm": "Bekräfta",
"action_register_delivery": "Registrera leverans",
"action_create_invoice": "Skapa faktura",
"action_cancel": "Makulera",
"action_reopen": "Återöppna",
"action_edit": "Redigera",
"action_delete": "Ta bort",
"confirm_dialog_title": "Bekräfta kundorder {number}?",
"confirm_dialog_description": "Ordern blir bekräftad och kan levereras och faktureras. Raderna kan fortfarande redigeras.",
"confirm_dialog_label": "Bekräfta",
"cancel_dialog_title": "Makulera kundorder {number}?",
"cancel_dialog_description": "Ordern markeras som makulerad. Inget bokförs. Den kan återöppnas som utkast senare.",
"cancel_dialog_label": "Makulera",
"reopen_dialog_title": "Återöppna kundorder {number}?",
"reopen_dialog_description": "Ordern återgår till utkast.",
"reopen_dialog_label": "Återöppna",
"delete_confirm_title": "Ta bort kundorder {number}?",
"delete_confirm_description": "Ordern tas bort permanent. Detta går inte att ångra.",
"delete_confirm_label": "Ta bort",
"confirmed_toast": "Kundordern är bekräftad",
"cancelled_toast": "Kundordern är makulerad",
"reopened_toast": "Kundordern är återöppnad",
"deleted_toast": "Kundordern är borttagen",
"transition_failed_title": "Åtgärden misslyckades",
"delete_failed_title": "Kunde inte ta bort kundordern",
"load_failed_title": "Kunde inte ladda kundordern",
"viewer_disabled_tooltip": "Du har läsbehörighet och kan inte ändra kundorder",
"delivery_dialog_title": "Registrera leverans",
"delivery_dialog_description": "Ange totalt levererat antal per rad. Värdet är ackumulerat, inte en delleverans.",
"delivery_date_label": "Leveransdatum",
"th_ordered": "Beställt",
"th_delivered_qty": "Levererat",
"deliver_all": "Markera allt som levererat",
"delivery_submit": "Registrera",
"delivery_success": "Leveransen är registrerad",
"delivery_failed_title": "Kunde inte registrera leveransen",
"invoice_dialog_title": "Skapa faktura från ordern",
"invoice_dialog_description": "Ange antal att fakturera per rad. Fakturan skapas som utkast som du granskar och skickar som vanligt.",
"mode_remaining": "Allt som återstår",
"mode_delivered": "Levererat ej fakturerat",
"th_remaining_qty": "Återstår",
"th_invoice_qty": "Fakturera",
"invoice_date_label": "Fakturadatum",
"due_date_label": "Förfallodatum",
"invoice_submit": "Skapa faktura",
"invoice_created_title": "Fakturautkast skapat",
"invoice_created_description": "Öppna fakturan för att granska och skicka den.",
"open_invoice": "Öppna fakturan",
"invoice_failed_title": "Kunde inte skapa fakturan",
"section_invoices": "Fakturor",
"th_invoice_number": "Faktura",
"th_invoice_status": "Status",
"th_invoice_total": "Belopp",
"invoice_draft_label": "Utkast",
"invoices_load_failed_title": "Kunde inte ladda fakturorna",
"invoice_status_draft": "Utkast",
"invoice_status_sent": "Skickad",
"invoice_status_paid": "Betald",
"invoice_status_partially_paid": "Delbetalad",
"invoice_status_overdue": "Förfallen",
"invoice_status_cancelled": "Makulerad",
"invoice_status_credited": "Krediterad",
"invoice_nothing_selected": "Ange ett antal på minst en rad"
},
"data_analysis": {
"group_label": "Data och integritet",
"settings_heading": "Dataanalys",
+3 -3
View File
@@ -125,7 +125,7 @@ Request body:
external_invoice_number?: string | "",
self_billing_agreement_ref?: string,
received_date?: string | "",
items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
}
```
@@ -306,7 +306,7 @@ Request body:
our_reference?: string | unknown,
notes?: string | unknown,
default_dimensions?: Record<string, string>,
items?: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
items?: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[]
}
```
@@ -777,7 +777,7 @@ Bulk-creation endpoint. Each invoice in the request array is validated and inser
Request body:
```ts
{
invoices: { customer_id: string, invoice_date: string, due_date: string, delivery_date?: string | "", currency: "SEK" | "EUR" | "USD" | "GBP" | "NOK" | "DKK", document_type?: "invoice" | "proforma" | "delivery_note", your_reference?: string, our_reference?: string, invoice_marking?: string, notes?: string, payment_link_url?: string | "", payment_link_auto?: boolean, deduction_personnummer?: string, deduction_housing_designation?: string, deduction_apartment_number?: string, deduction_brf_org_number?: string | "", save_as_draft?: boolean, ore_rounding?: boolean, default_dimensions?: Record<string, string>, is_self_billed?: boolean, external_invoice_number?: string | "", self_billing_agreement_ref?: string, received_date?: string | "", items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[] }[],
invoices: { customer_id: string, invoice_date: string, due_date: string, delivery_date?: string | "", currency: "SEK" | "EUR" | "USD" | "GBP" | "NOK" | "DKK", document_type?: "invoice" | "proforma" | "delivery_note", your_reference?: string, our_reference?: string, invoice_marking?: string, notes?: string, payment_link_url?: string | "", payment_link_auto?: boolean, deduction_personnummer?: string, deduction_housing_designation?: string, deduction_apartment_number?: string, deduction_brf_org_number?: string | "", save_as_draft?: boolean, ore_rounding?: boolean, default_dimensions?: Record<string, string>, is_self_billed?: boolean, external_invoice_number?: string | "", self_billing_agreement_ref?: string, received_date?: string | "", items: { line_type?: "product" | "text", description: string, quantity: number, unit: string, unit_price: number, discount_percent?: number, vat_rate?: number, article_id?: string, revenue_account?: string, sales_order_item_id?: string, deduction_type?: "rot" | "rut", labor_hours?: number, work_type?: string, housing_designation?: string, apartment_number?: string, brf_org_number?: string | "", accrual_period_start?: string, accrual_period_end?: string, accrual_balance_account?: string, dimensions?: Record<string, string> }[] }[],
all_or_nothing?: boolean
}
```
@@ -0,0 +1,550 @@
-- Kundorder (sales orders): the document between "agreed" and "faktura".
--
-- A sales order is a NON-ledger document: it never books, carries no BFL
-- sequence or immutability obligation, and exists so a company that delivers
-- or invoices in parts has one place that says what was ordered, what has
-- been delivered and what has been invoiced. Invoices created from an order
-- go through the ordinary invoice path (draft, F-number at finalize, booking
-- in the engine); the order only remembers which invoice lines came from
-- which order lines.
--
-- Design (kundorder plan, 2026-09-02):
-- * status is a four-state header machine: draft, confirmed, completed,
-- cancelled. Delivery state and invoicing state are two independent axes
-- DERIVED from line quantities, never stored as status values: an order
-- is normally both partially delivered and partially invoiced at once.
-- * invoiced quantity is NOT a stored counter. Every invoice line created
-- from an order line carries invoice_items.sales_order_item_id, and the
-- invoiced quantity is the sum over linked lines whose invoice is neither
-- cancelled nor credited. A BEFORE trigger on invoice_items locks the
-- order line and refuses over-invoicing, so a counter cannot drift and a
-- credited invoice automatically frees its quantity for re-invoicing.
-- * completion (confirmed <-> completed) is maintained by AFTER triggers on
-- invoice_items and invoices.status from the same derived quantity, so a
-- cancelled or deleted draft reopens the order without application code.
-- * delivered_qty IS stored (there is no delivery document to derive it
-- from); delivery registration is an explicit user action.
-- * no inventory. Articles stay a non-inventory register; lines freeze the
-- article's description/unit/price/vat/revenue_account like invoice_items.
--
-- Naming note: the existing /orders page and the `sales_orders` nav label
-- key belong to webshop_orders (store-sync mirror, service-role INSERT only).
-- This table is user-authored and lives at /sales-orders.
-- =============================================================================
-- 1. sales_orders
-- =============================================================================
CREATE TABLE public.sales_orders (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
customer_id uuid REFERENCES public.customers(id) ON DELETE SET NULL,
order_number text,
status text NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'confirmed', 'completed', 'cancelled')),
-- The proforma this order was created from (proforma -> order conversion);
-- informational back-pointer only.
source_invoice_id uuid REFERENCES public.invoices(id) ON DELETE SET NULL,
order_date date NOT NULL DEFAULT CURRENT_DATE,
requested_delivery_date date,
-- Latest registered delivery date; becomes the invoice's delivery_date
-- (taxable event, ML 8 kap 21-23 §) when an invoice is created from the order.
last_delivery_date date,
currency text NOT NULL DEFAULT 'SEK' REFERENCES public.currencies(code),
subtotal numeric NOT NULL DEFAULT 0,
vat_amount numeric NOT NULL DEFAULT 0,
total numeric NOT NULL DEFAULT 0,
your_reference text,
our_reference text,
notes text,
-- Dimensions bag applied to every invoice created from the order.
default_dimensions jsonb NOT NULL DEFAULT '{}'::jsonb,
confirmed_at timestamptz,
completed_at timestamptz,
cancelled_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE public.sales_orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY "view own-company sales_orders"
ON public.sales_orders FOR SELECT USING (company_id IN (SELECT user_company_ids()));
CREATE POLICY "insert own-company sales_orders"
ON public.sales_orders FOR INSERT WITH CHECK (company_id IN (SELECT user_company_ids()));
CREATE POLICY "update own-company sales_orders"
ON public.sales_orders FOR UPDATE USING (company_id IN (SELECT user_company_ids()));
CREATE POLICY "delete own-company sales_orders"
ON public.sales_orders FOR DELETE USING (company_id IN (SELECT user_company_ids()));
CREATE INDEX idx_sales_orders_company_id ON public.sales_orders (company_id);
CREATE INDEX idx_sales_orders_company_status ON public.sales_orders (company_id, status, order_date DESC);
CREATE INDEX idx_sales_orders_customer_id ON public.sales_orders (customer_id);
CREATE INDEX idx_sales_orders_source_invoice_id ON public.sales_orders (source_invoice_id);
CREATE UNIQUE INDEX uq_sales_orders_company_number
ON public.sales_orders (company_id, order_number) WHERE order_number IS NOT NULL;
CREATE TRIGGER set_updated_at_sales_orders
BEFORE UPDATE ON public.sales_orders
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
CREATE TRIGGER audit_sales_orders
AFTER INSERT OR UPDATE OR DELETE ON public.sales_orders
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
-- =============================================================================
-- 2. sales_order_items
-- =============================================================================
CREATE TABLE public.sales_order_items (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
-- Own company_id (defense in depth alongside the parent join): the
-- over-invoice trigger compares it against the invoice's company.
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
sales_order_id uuid NOT NULL REFERENCES public.sales_orders(id) ON DELETE CASCADE,
sort_order integer NOT NULL DEFAULT 0,
line_type text NOT NULL DEFAULT 'product' CHECK (line_type IN ('product', 'text')),
description text NOT NULL DEFAULT '',
quantity numeric NOT NULL DEFAULT 1 CHECK (quantity >= 0),
delivered_qty numeric NOT NULL DEFAULT 0 CHECK (delivered_qty >= 0),
unit text NOT NULL DEFAULT 'st',
unit_price numeric NOT NULL DEFAULT 0,
discount_percent numeric NOT NULL DEFAULT 0 CHECK (discount_percent >= 0 AND discount_percent <= 100),
vat_rate numeric NOT NULL DEFAULT 25,
-- NET of discount, order currency (same formula as invoice_items.line_total).
line_total numeric NOT NULL DEFAULT 0,
article_id uuid REFERENCES public.articles(id) ON DELETE SET NULL,
-- Frozen copy of the article's posting-account override at line-create time.
revenue_account text,
dimensions jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT sales_order_items_delivered_within_ordered CHECK (delivered_qty <= quantity)
);
ALTER TABLE public.sales_order_items ENABLE ROW LEVEL SECURITY;
CREATE POLICY "view own-company sales_order_items"
ON public.sales_order_items FOR SELECT USING (company_id IN (SELECT user_company_ids()));
CREATE POLICY "insert own-company sales_order_items"
ON public.sales_order_items FOR INSERT WITH CHECK (company_id IN (SELECT user_company_ids()));
CREATE POLICY "update own-company sales_order_items"
ON public.sales_order_items FOR UPDATE USING (company_id IN (SELECT user_company_ids()));
CREATE POLICY "delete own-company sales_order_items"
ON public.sales_order_items FOR DELETE USING (company_id IN (SELECT user_company_ids()));
CREATE INDEX idx_sales_order_items_order ON public.sales_order_items (sales_order_id, sort_order);
CREATE INDEX idx_sales_order_items_company_id ON public.sales_order_items (company_id);
CREATE INDEX idx_sales_order_items_article_id ON public.sales_order_items (article_id);
CREATE TRIGGER set_updated_at_sales_order_items
BEFORE UPDATE ON public.sales_order_items
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
-- =============================================================================
-- 3. company_settings: module toggle + per-company order-number counter
-- =============================================================================
-- sales_orders_enabled is a UI-visibility gate only (same contract as
-- dimensions_enabled / mileage_enabled): the pages and APIs work regardless.
ALTER TABLE public.company_settings
ADD COLUMN IF NOT EXISTS sales_orders_enabled boolean NOT NULL DEFAULT false;
ALTER TABLE public.company_settings
ADD COLUMN IF NOT EXISTS next_sales_order_number integer NOT NULL DEFAULT 1;
-- =============================================================================
-- 4. invoices / invoice_items back-links
-- =============================================================================
-- RESTRICT on both: an order with invoices can be cancelled but never
-- deleted, so the invoice's provenance survives (the invoice is
-- räkenskapsinformation; its source order is context a revisor may ask for).
ALTER TABLE public.invoices
ADD COLUMN IF NOT EXISTS sales_order_id uuid REFERENCES public.sales_orders(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS idx_invoices_sales_order_id
ON public.invoices (sales_order_id) WHERE sales_order_id IS NOT NULL;
ALTER TABLE public.invoice_items
ADD COLUMN IF NOT EXISTS sales_order_item_id uuid REFERENCES public.sales_order_items(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS idx_invoice_items_sales_order_item_id
ON public.invoice_items (sales_order_item_id) WHERE sales_order_item_id IS NOT NULL;
-- =============================================================================
-- 5. generate_sales_order_number RPC: atomic + idempotent
-- (clone of generate_article_number incl. the 20260901100000 hardening:
-- membership check, empty search_path, no anon/PUBLIC execute).
-- Orders are not verifikationer, so gaps are legally irrelevant; the
-- number is allocated at creation.
-- =============================================================================
CREATE OR REPLACE FUNCTION public.generate_sales_order_number(
p_company_id uuid,
p_order_id uuid
)
RETURNS text
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
v_existing text;
v_number integer;
v_final text;
v_trusted boolean;
BEGIN
-- Same fail-closed gate as generate_article_number after 20260901100000:
-- a JWT with a role but no sub (the anon key) is refused; a direct DB
-- connection with no claims at all (migrations, pg tests) is trusted.
v_trusted := auth.uid() IS NULL
AND (
COALESCE(auth.role(), '') = 'service_role'
OR (auth.role() IS NULL AND session_user <> 'authenticator')
);
IF NOT v_trusted AND NOT EXISTS (
SELECT 1 FROM public.company_members
WHERE user_id = auth.uid() AND company_id = p_company_id
) THEN
RAISE EXCEPTION 'unauthorized: caller is not a member of company %', p_company_id
USING ERRCODE = '42501';
END IF;
SELECT order_number INTO v_existing
FROM public.sales_orders
WHERE id = p_order_id AND company_id = p_company_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'Sales order % not found in company %', p_order_id, p_company_id;
END IF;
IF v_existing IS NOT NULL THEN
RETURN v_existing;
END IF;
UPDATE public.company_settings
SET next_sales_order_number = next_sales_order_number + 1,
updated_at = now()
WHERE company_id = p_company_id
RETURNING next_sales_order_number - 1
INTO v_number;
IF v_number IS NULL THEN
RAISE EXCEPTION 'Company settings not found for company %', p_company_id;
END IF;
v_final := 'OR-' || v_number::text;
UPDATE public.sales_orders
SET order_number = v_final
WHERE id = p_order_id AND company_id = p_company_id;
RETURN v_final;
END;
$function$;
REVOKE EXECUTE ON FUNCTION public.generate_sales_order_number(uuid, uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.generate_sales_order_number(uuid, uuid) TO authenticated, service_role;
-- =============================================================================
-- 6. Derived invoiced quantity (read side, SECURITY INVOKER: RLS applies)
-- =============================================================================
-- One row per order line with the quantity already invoiced. Linked lines on
-- cancelled or credited invoices do not count, so a makulerad draft or a
-- fully credited invoice frees the quantity again. Credit notes never link
-- to order lines (they reference the invoice they credit), but the
-- credited_invoice_id guard keeps a hand-linked one from netting a line.
CREATE OR REPLACE FUNCTION public.sales_order_invoiced_quantities(p_order_ids uuid[])
RETURNS TABLE (sales_order_id uuid, sales_order_item_id uuid, invoiced_qty numeric)
LANGUAGE sql
STABLE
SET search_path = ''
AS $$
SELECT soi.sales_order_id,
soi.id AS sales_order_item_id,
COALESCE(SUM(ii.quantity) FILTER (
WHERE i.id IS NOT NULL
AND i.status NOT IN ('cancelled', 'credited')
AND i.credited_invoice_id IS NULL
), 0) AS invoiced_qty
FROM public.sales_order_items soi
LEFT JOIN public.invoice_items ii ON ii.sales_order_item_id = soi.id
LEFT JOIN public.invoices i ON i.id = ii.invoice_id
WHERE soi.sales_order_id = ANY (p_order_ids)
GROUP BY soi.sales_order_id, soi.id
$$;
REVOKE EXECUTE ON FUNCTION public.sales_order_invoiced_quantities(uuid[]) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.sales_order_invoiced_quantities(uuid[]) TO authenticated, service_role;
-- =============================================================================
-- 7. Over-invoicing guard on invoice_items (BEFORE INSERT/UPDATE)
-- =============================================================================
-- Locks the order line so two concurrent invoice creations serialize, then
-- refuses a linked line whose quantity would push the invoiced total past the
-- ordered quantity. SECURITY DEFINER because the sum must see every linked
-- line regardless of the caller's RLS view; the company check keeps a line
-- from linking across tenants.
CREATE OR REPLACE FUNCTION public.enforce_sales_order_item_invoiced_qty()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
v_ordered numeric;
v_item_company uuid;
v_invoice_company uuid;
v_invoice_status text;
v_other numeric;
BEGIN
IF NEW.sales_order_item_id IS NULL THEN
RETURN NEW;
END IF;
SELECT soi.quantity, soi.company_id
INTO v_ordered, v_item_company
FROM public.sales_order_items soi
WHERE soi.id = NEW.sales_order_item_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'SALES_ORDER_ITEM_NOT_FOUND: order line % does not exist', NEW.sales_order_item_id
USING ERRCODE = 'foreign_key_violation';
END IF;
SELECT i.company_id, i.status
INTO v_invoice_company, v_invoice_status
FROM public.invoices i
WHERE i.id = NEW.invoice_id;
IF v_invoice_company IS DISTINCT FROM v_item_company THEN
RAISE EXCEPTION 'SALES_ORDER_ITEM_COMPANY_MISMATCH: invoice and order line belong to different companies'
USING ERRCODE = 'check_violation';
END IF;
-- A line on an already cancelled/credited invoice does not count and is
-- not counted against; nothing to enforce.
IF v_invoice_status IN ('cancelled', 'credited') THEN
RETURN NEW;
END IF;
SELECT COALESCE(SUM(ii.quantity), 0)
INTO v_other
FROM public.invoice_items ii
JOIN public.invoices i ON i.id = ii.invoice_id
WHERE ii.sales_order_item_id = NEW.sales_order_item_id
AND ii.id <> NEW.id
AND i.status NOT IN ('cancelled', 'credited')
AND i.credited_invoice_id IS NULL;
IF v_other + NEW.quantity > v_ordered THEN
RAISE EXCEPTION 'SALES_ORDER_OVER_INVOICED: order line % has % of % already invoiced, cannot add %',
NEW.sales_order_item_id, v_other, v_ordered, NEW.quantity
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$function$;
CREATE TRIGGER enforce_sales_order_item_invoiced_qty
BEFORE INSERT OR UPDATE OF quantity, sales_order_item_id, invoice_id ON public.invoice_items
FOR EACH ROW EXECUTE FUNCTION public.enforce_sales_order_item_invoiced_qty();
-- =============================================================================
-- 8. Order line guards: quantity never below what is invoiced; a line with
-- linked invoice lines cannot be deleted (RESTRICT FK already does that).
-- =============================================================================
CREATE OR REPLACE FUNCTION public.enforce_sales_order_item_quantity_floor()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
v_invoiced numeric;
BEGIN
IF NEW.quantity >= OLD.quantity THEN
RETURN NEW;
END IF;
SELECT COALESCE(SUM(ii.quantity), 0)
INTO v_invoiced
FROM public.invoice_items ii
JOIN public.invoices i ON i.id = ii.invoice_id
WHERE ii.sales_order_item_id = NEW.id
AND i.status NOT IN ('cancelled', 'credited')
AND i.credited_invoice_id IS NULL;
IF NEW.quantity < v_invoiced THEN
RAISE EXCEPTION 'SALES_ORDER_QUANTITY_BELOW_INVOICED: order line % has % invoiced, cannot reduce to %',
NEW.id, v_invoiced, NEW.quantity
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$function$;
CREATE TRIGGER enforce_sales_order_item_quantity_floor
BEFORE UPDATE OF quantity ON public.sales_order_items
FOR EACH ROW EXECUTE FUNCTION public.enforce_sales_order_item_quantity_floor();
-- =============================================================================
-- 9. Completion maintenance: confirmed <-> completed from derived quantities
-- =============================================================================
-- An order is completed when it has at least one product line with a
-- positive quantity and every such line is fully invoiced. Runs after any
-- change to a linked invoice line or to a linked invoice's status, so
-- makulering / crediting / draft deletion reopens the order. Draft and
-- cancelled orders are never touched.
CREATE OR REPLACE FUNCTION public.refresh_sales_order_completion(p_order_id uuid)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
v_company uuid;
v_trusted boolean;
v_has_lines boolean;
v_open_lines boolean;
v_complete boolean;
BEGIN
IF p_order_id IS NULL THEN
RETURN;
END IF;
-- Callable by authenticated (the confirm transition invokes it directly),
-- so it carries the same fail-closed membership gate as the numbering
-- RPCs. Trigger invocations run under the DML user's claims (a member's)
-- or under a trusted no-claims connection.
SELECT company_id INTO v_company FROM public.sales_orders WHERE id = p_order_id;
IF v_company IS NULL THEN
RETURN;
END IF;
v_trusted := auth.uid() IS NULL
AND (
COALESCE(auth.role(), '') = 'service_role'
OR (auth.role() IS NULL AND session_user <> 'authenticator')
);
IF NOT v_trusted AND NOT EXISTS (
SELECT 1 FROM public.company_members
WHERE user_id = auth.uid() AND company_id = v_company
) THEN
RAISE EXCEPTION 'unauthorized: caller is not a member of company %', v_company
USING ERRCODE = '42501';
END IF;
SELECT EXISTS (
SELECT 1 FROM public.sales_order_items soi
WHERE soi.sales_order_id = p_order_id AND soi.line_type = 'product' AND soi.quantity > 0
) INTO v_has_lines;
SELECT EXISTS (
SELECT 1
FROM public.sales_order_items soi
WHERE soi.sales_order_id = p_order_id
AND soi.line_type = 'product'
AND soi.quantity > 0
AND soi.quantity > (
SELECT COALESCE(SUM(ii.quantity), 0)
FROM public.invoice_items ii
JOIN public.invoices i ON i.id = ii.invoice_id
WHERE ii.sales_order_item_id = soi.id
AND i.status NOT IN ('cancelled', 'credited')
AND i.credited_invoice_id IS NULL
)
) INTO v_open_lines;
v_complete := v_has_lines AND NOT v_open_lines;
UPDATE public.sales_orders so
SET status = CASE WHEN v_complete THEN 'completed' ELSE 'confirmed' END,
completed_at = CASE WHEN v_complete THEN COALESCE(so.completed_at, now()) ELSE NULL END
WHERE so.id = p_order_id
AND so.status IN ('confirmed', 'completed')
AND so.status IS DISTINCT FROM (CASE WHEN v_complete THEN 'completed' ELSE 'confirmed' END);
END;
$function$;
REVOKE EXECUTE ON FUNCTION public.refresh_sales_order_completion(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.refresh_sales_order_completion(uuid) TO authenticated, service_role;
CREATE OR REPLACE FUNCTION public.sales_order_completion_from_invoice_items()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
v_item uuid;
v_order uuid;
BEGIN
v_item := COALESCE(NEW.sales_order_item_id, OLD.sales_order_item_id);
IF v_item IS NULL THEN
RETURN NULL;
END IF;
SELECT sales_order_id INTO v_order FROM public.sales_order_items WHERE id = v_item;
PERFORM public.refresh_sales_order_completion(v_order);
-- A re-link from one order line to another refreshes both orders.
IF TG_OP = 'UPDATE' AND NEW.sales_order_item_id IS DISTINCT FROM OLD.sales_order_item_id
AND OLD.sales_order_item_id IS NOT NULL THEN
SELECT sales_order_id INTO v_order FROM public.sales_order_items WHERE id = OLD.sales_order_item_id;
PERFORM public.refresh_sales_order_completion(v_order);
END IF;
RETURN NULL;
END;
$function$;
CREATE TRIGGER sales_order_completion_from_invoice_items
AFTER INSERT OR UPDATE OR DELETE ON public.invoice_items
FOR EACH ROW EXECUTE FUNCTION public.sales_order_completion_from_invoice_items();
CREATE OR REPLACE FUNCTION public.sales_order_completion_from_invoice_status()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
BEGIN
IF NEW.status IS DISTINCT FROM OLD.status THEN
-- Resolve the affected orders through the LINE links, not the header
-- back-pointer, so a hand-linked line on an invoice without
-- sales_order_id still keeps its order's completion honest.
PERFORM public.refresh_sales_order_completion(o.sales_order_id)
FROM (
SELECT DISTINCT soi.sales_order_id
FROM public.invoice_items ii
JOIN public.sales_order_items soi ON soi.id = ii.sales_order_item_id
WHERE ii.invoice_id = NEW.id
) o;
END IF;
RETURN NULL;
END;
$function$;
CREATE TRIGGER sales_order_completion_from_invoice_status
AFTER UPDATE OF status ON public.invoices
FOR EACH ROW EXECUTE FUNCTION public.sales_order_completion_from_invoice_status();
-- Confirming an order whose lines are already fully invoiced (hand-linked
-- lines) or changing line quantities also re-evaluates completion.
CREATE OR REPLACE FUNCTION public.sales_order_completion_from_order_items()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
BEGIN
PERFORM public.refresh_sales_order_completion(COALESCE(NEW.sales_order_id, OLD.sales_order_id));
RETURN NULL;
END;
$function$;
CREATE TRIGGER sales_order_completion_from_order_items
AFTER INSERT OR UPDATE OF quantity, line_type OR DELETE ON public.sales_order_items
FOR EACH ROW EXECUTE FUNCTION public.sales_order_completion_from_order_items();
COMMENT ON TABLE public.sales_orders IS
'Kundorder: non-ledger sales document between quote/agreement and invoice. Never books; invoices created from it go through the normal invoice path.';
COMMENT ON COLUMN public.invoice_items.sales_order_item_id IS
'Order line this invoice line was created from. The invoiced quantity of an order line is derived from these links (sales_order_invoiced_quantities); never stored.';
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,127 @@
-- Add the four kundorder (sales order) operation types to the
-- pending_operations operation_type CHECK constraint.
--
-- The MCP server stages every sales-order write for approval, exactly like
-- invoices and articles; the user approves it in Granskning and the commit
-- executors in lib/pending-operations/commit.ts apply it through the same
-- lib/sales-orders services the cookie routes under app/api/sales-orders
-- use, so the MCP door and the web door cannot drift:
--
-- create_sales_order gnubok_create_sales_order: a draft order
-- with its lines (number allocated at
-- creation; orders are not verifikationer).
-- Risk 'low': nothing is booked.
-- transition_sales_order gnubok_transition_sales_order: the header
-- state machine (confirm / cancel / reopen).
-- Cancel and reopen are refused while linked
-- invoices exist. Risk 'low'.
-- register_sales_order_delivery gnubok_register_sales_order_delivery:
-- cumulative delivered quantities per line
-- (no inventory, nothing is booked; the
-- order's last_delivery_date becomes the
-- taxable-event date on later invoices).
-- Risk 'low'.
-- create_invoice_from_sales_order gnubok_create_invoice_from_sales_order:
-- an unnumbered DRAFT kundfaktura from a
-- confirmed order (remaining, delivered or
-- explicit line picks) through
-- buildInvoiceWriteData, so VAT gating and
-- totals stay in the invoice builder. Risk
-- 'medium', same tier as create_invoice.
--
-- NOTE on the value list: this constraint is re-created wholesale (the
-- established pattern here), so the list below is every value of the
-- constraint as left by 20260831070000 (ignore_transaction, which built on
-- 20260830160000's update_salary_run) PLUS the four new values. Dropping
-- any existing value here would silently revoke it.
--
-- NOT VALID + separate VALIDATE migration (paired file, same pattern as
-- 20260831070000 / 20260831070001).
--
-- pg-test: tests/pg/pending-operations-op-type-audit.pg.test.ts (collects
-- the staged op types from server.ts and OPERATION_RISK_TIERS).
ALTER TABLE public.pending_operations
DROP CONSTRAINT IF EXISTS pending_operations_operation_type_check;
ALTER TABLE public.pending_operations
ADD CONSTRAINT pending_operations_operation_type_check
CHECK (operation_type IN (
'categorize_transaction',
'create_customer',
'create_invoice',
'mark_invoice_paid',
'send_invoice',
'mark_invoice_sent',
'match_transaction_invoice',
'close_period',
'lock_period',
'unlock_period',
'set_opening_balances',
'run_year_end',
'post_kontantmetod_cutoff',
'run_currency_revaluation',
'import_sie',
'explain_voucher_gap',
'uncategorize_transaction',
'approve_supplier_invoice',
'credit_supplier_invoice',
'credit_invoice',
'convert_invoice',
'delete_draft_invoice',
'create_transaction',
'attach_document_to_transaction',
'create_voucher',
'correct_entry',
'reverse_entry',
'create_supplier',
'create_supplier_invoice_from_inbox',
'post_annual_depreciation',
'link_invoice_voucher',
'undo_sie_import',
'match_batch_allocate',
'bulk_book_transactions',
'create_salary_run',
'generate_agi',
'link_transaction_journal_entry',
'link_supplier_invoice_voucher',
'submit_vat_declaration',
'submit_agi',
'create_article',
'update_article',
'bulk_book_inbox_items',
'create_dimension_value',
'retag_line_dimensions',
'link_document_to_voucher',
'update_payslip_line',
'set_run_salary',
'update_salary_run',
'register_absence',
'create_employee',
'update_employee',
'set_employee_opening_balances',
'vacation_year_close',
'create_account',
'update_account',
'set_voucher_note',
'book_salary_run',
'delete_absence',
'update_company_settings',
'update_customer',
'update_invoice',
'create_recurring_schedule',
'update_recurring_schedule',
'log_mileage_trip',
'book_mileage_period',
'link_documents_to_vouchers',
'reconciliation_match',
'reconciliation_unmatch',
'reconciliation_signoff',
'reconciliation_residual',
'book_skattekonto_row',
'book_skattekonto_rows',
'ignore_transaction',
'create_sales_order',
'transition_sales_order',
'register_sales_order_delivery',
'create_invoice_from_sales_order'
)) NOT VALID;
@@ -0,0 +1,6 @@
-- Validate the operation type CHECK re-added in 20260902141000.
-- This separate transaction avoids a full-table scan while the preceding
-- migration holds its stronger table lock.
ALTER TABLE public.pending_operations
VALIDATE CONSTRAINT pending_operations_operation_type_check;
@@ -0,0 +1,79 @@
-- Kundorder hardening (skeptic + security review of PR #2166).
--
-- Additive follow-up to 20260902130000_sales_orders.sql (version 20260902180000;
-- originally 20260902160000, renamed after colliding with parties_substrate on main):
--
-- 1. Tenant consistency between an order line and its parent order is now
-- a database invariant: a composite FK (sales_order_id, company_id)
-- -> sales_orders (id, company_id). Before this, the line's own
-- company_id and its parent reference were independently writable, so
-- a PostgREST caller could park a line under its own company while
-- pointing at another tenant's order (Superagent P2).
-- 2. Both tables get the same aa_enforce_company_writer_role gate as every
-- other membership-only table (20260902093000), so a viewer cannot
-- write through the browser Supabase client. Routes already carry
-- requireWrite; this is the defense-in-depth layer.
-- 3. Per-line delivery date. The header last_delivery_date is the latest
-- delivery across ALL lines; using it as the invoice's delivery_date
-- stamps a wrong leveransdatum (ML 17 kap 24 § p.7) and a wrong FX
-- anchor (ML 8 kap 21-23 §) on an invoice for lines delivered earlier.
-- Each line now remembers its own latest delivery date and the invoice
-- takes the latest over the lines it actually covers, only when every
-- covered quantity has been delivered.
-- 4. Customer VAT snapshot. Order lines freeze a VAT rate that was lawful
-- for the customer at order time. If the customer's type or VAT-number
-- validation changes before invoicing (an EU business validated later,
-- or reclassified as domestic), the frozen rate can still pass the
-- permitted-set gate (25 % is permitted for a validated EU business via
-- the ML 6 kap. exceptions) and land silently on the invoice. The order
-- stores the customer facts it was priced under; invoicing refuses when
-- they changed until the order is re-saved (which re-validates the
-- lines against the current rules).
-- 1. Composite tenant FK -----------------------------------------------------
-- Idempotent on purpose: this file was renamed from 20260902160000 after a
-- version collision with parties_substrate, and a preview branch that had
-- already applied it under the old version replays it under the new one.
-- The FK depends on the unique index, so it is dropped first.
ALTER TABLE public.sales_order_items
DROP CONSTRAINT IF EXISTS sales_order_items_order_company_fkey;
ALTER TABLE public.sales_orders
DROP CONSTRAINT IF EXISTS sales_orders_id_company_id_key;
ALTER TABLE public.sales_orders
ADD CONSTRAINT sales_orders_id_company_id_key UNIQUE (id, company_id);
ALTER TABLE public.sales_order_items
ADD CONSTRAINT sales_order_items_order_company_fkey
FOREIGN KEY (sales_order_id, company_id)
REFERENCES public.sales_orders (id, company_id)
ON DELETE CASCADE;
-- 2. Writer-role gate (mirrors 20260902093000) -------------------------------
DROP TRIGGER IF EXISTS aa_enforce_company_writer_role ON public.sales_orders;
CREATE TRIGGER aa_enforce_company_writer_role
BEFORE INSERT OR UPDATE OR DELETE ON public.sales_orders
FOR EACH ROW EXECUTE FUNCTION public.enforce_company_writer_role();
DROP TRIGGER IF EXISTS aa_enforce_company_writer_role ON public.sales_order_items;
CREATE TRIGGER aa_enforce_company_writer_role
BEFORE INSERT OR UPDATE OR DELETE ON public.sales_order_items
FOR EACH ROW EXECUTE FUNCTION public.enforce_company_writer_role();
-- 3. Per-line delivery date --------------------------------------------------
ALTER TABLE public.sales_order_items
ADD COLUMN IF NOT EXISTS last_delivery_date date;
COMMENT ON COLUMN public.sales_order_items.last_delivery_date IS
'Latest registered delivery date for this line. An invoice created from the order uses the latest over the lines it covers as delivery_date, only when the covered quantity has been delivered.';
-- 4. Customer VAT snapshot ---------------------------------------------------
ALTER TABLE public.sales_orders
ADD COLUMN IF NOT EXISTS customer_type_snapshot text
CHECK (customer_type_snapshot IN ('individual', 'swedish_business', 'eu_business', 'non_eu_business'));
ALTER TABLE public.sales_orders
ADD COLUMN IF NOT EXISTS customer_vat_validated_snapshot boolean;
COMMENT ON COLUMN public.sales_orders.customer_type_snapshot IS
'customer_type the lines were VAT-validated under. Invoicing refuses when the customer no longer matches; re-saving the order refreshes it.';
NOTIFY pgrst, 'reload schema';
+1
View File
@@ -551,6 +551,7 @@ export function makeCompanySettings(
reminder_interest_rate_override: null,
dimensions_enabled: false,
mileage_enabled: false,
sales_orders_enabled: false,
data_analysis_opt_in: false,
preferred_payment_format: 'pain001',
salary_pay_day: 25,
@@ -64,6 +64,11 @@ const AUTHENTICATED_GUARDED_WRITERS = [
'generate_delivery_note_number(uuid)',
'generate_article_number(uuid,uuid)',
'check_and_increment_inbox_quota(uuid,integer,integer)',
// Kundorder (20260902130000): numbering + completion refresh, both called
// on the user's session client; non-member refusal is exercised in
// tests/pg/sales-orders.pg.test.ts.
'generate_sales_order_number(uuid,uuid)',
'refresh_sales_order_completion(uuid)',
]
interface GrantRow {
+466
View File
@@ -0,0 +1,466 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getClient, getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser, insertCompanyMember } from './fixtures'
// pg-real coverage for the kundorder migration (20260902130000): the
// generate_sales_order_number RPC (atomic, idempotent, membership-gated),
// RLS isolation on both tables, the derived invoiced-quantity RPC, the
// over-invoice BEFORE trigger on invoice_items (incl. release on
// cancel/credit and the cross-company refusal), the quantity floor on
// order lines, the delivered-within-ordered CHECK, and the completion
// triggers that flip confirmed <-> completed from the derived quantity.
async function seedSettings(companyId: string, userId: string): Promise<void> {
await getPool().query(
`INSERT INTO public.company_settings (user_id, company_id) VALUES ($1, $2)
ON CONFLICT (company_id) DO NOTHING`,
[userId, companyId],
)
}
async function insertCustomer(companyId: string, userId: string): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
VALUES ($1, $2, $3, 'Testbrand AB', 'swedish_business')`,
[id, userId, companyId],
)
return id
}
async function insertOrder(
companyId: string,
userId: string,
customerId: string,
status: 'draft' | 'confirmed' | 'completed' | 'cancelled' = 'confirmed',
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.sales_orders (id, company_id, user_id, customer_id, status, order_date)
VALUES ($1, $2, $3, $4, $5, '2026-09-01')`,
[id, companyId, userId, customerId, status],
)
return id
}
async function insertOrderItem(
companyId: string,
orderId: string,
quantity: number,
overrides: { lineType?: 'product' | 'text'; sortOrder?: number } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.sales_order_items
(id, company_id, sales_order_id, sort_order, line_type, description, quantity, unit, unit_price, vat_rate, line_total)
VALUES ($1, $2, $3, $4, $5, 'Konsulttimmar', $6, 'tim', 1000, 25, $7)`,
[id, companyId, orderId, overrides.sortOrder ?? 0, overrides.lineType ?? 'product', quantity, quantity * 1000],
)
return id
}
async function insertInvoice(
companyId: string,
userId: string,
customerId: string,
overrides: { status?: string; salesOrderId?: string | null; creditedInvoiceId?: string | null } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.invoices
(id, user_id, company_id, customer_id, invoice_number, document_type,
invoice_date, due_date, currency, subtotal, vat_amount, total,
vat_treatment, vat_rate, moms_ruta, status, sales_order_id, credited_invoice_id)
VALUES ($1, $2, $3, $4, NULL, 'invoice',
'2026-09-01', '2026-10-01', 'SEK', 1000, 250, 1250,
'standard_25', 25, '10', $5, $6, $7)`,
[id, userId, companyId, customerId, overrides.status ?? 'draft', overrides.salesOrderId ?? null, overrides.creditedInvoiceId ?? null],
)
return id
}
async function insertInvoiceItem(
invoiceId: string,
quantity: number,
salesOrderItemId: string | null,
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.invoice_items
(id, invoice_id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, sales_order_item_id)
VALUES ($1, $2, 0, 'Konsulttimmar', $3, 'tim', 1000, $4, 25, $5, $6)`,
[id, invoiceId, quantity, quantity * 1000, quantity * 250, salesOrderItemId],
)
return id
}
async function orderStatus(orderId: string): Promise<{ status: string; completed_at: string | null }> {
const { rows } = await getPool().query<{ status: string; completed_at: string | null }>(
`SELECT status, completed_at FROM public.sales_orders WHERE id = $1`,
[orderId],
)
return rows[0]!
}
async function invoicedQty(orderId: string, itemId: string): Promise<number> {
const { rows } = await getPool().query<{ invoiced_qty: string }>(
`SELECT invoiced_qty FROM public.sales_order_invoiced_quantities(ARRAY[$1::uuid])
WHERE sales_order_item_id = $2`,
[orderId, itemId],
)
return Number(rows[0]?.invoiced_qty ?? 0)
}
async function seedOrderWithLine(quantity = 10) {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const orderId = await insertOrder(companyId, userId, customerId, 'confirmed')
const itemId = await insertOrderItem(companyId, orderId, quantity)
return { userId, companyId, customerId, orderId, itemId }
}
describe('generate_sales_order_number RPC', () => {
it('assigns OR-<n> sequentially, is idempotent, and advances the counter once per order', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const o1 = await insertOrder(companyId, userId, customerId, 'draft')
const o2 = await insertOrder(companyId, userId, customerId, 'draft')
const first = await getPool().query<{ n: string }>(
`SELECT public.generate_sales_order_number($1, $2) AS n`,
[companyId, o1],
)
expect(first.rows[0]!.n).toBe('OR-1')
const again = await getPool().query<{ n: string }>(
`SELECT public.generate_sales_order_number($1, $2) AS n`,
[companyId, o1],
)
expect(again.rows[0]!.n).toBe('OR-1')
const second = await getPool().query<{ n: string }>(
`SELECT public.generate_sales_order_number($1, $2) AS n`,
[companyId, o2],
)
expect(second.rows[0]!.n).toBe('OR-2')
const settings = await getPool().query<{ next_sales_order_number: number }>(
`SELECT next_sales_order_number FROM public.company_settings WHERE company_id = $1`,
[companyId],
)
expect(settings.rows[0]!.next_sales_order_number).toBe(3)
})
it('refuses a signed-in caller who is not a member of the company', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const orderId = await insertOrder(companyId, userId, customerId, 'draft')
const outsider = await seedCompany()
await expect(
withUserContext(outsider.userId, (client) =>
client.query('SELECT public.generate_sales_order_number($1, $2)', [companyId, orderId]),
),
).rejects.toThrow(/unauthorized/i)
const { rows } = await getPool().query<{ order_number: string | null }>(
`SELECT order_number FROM public.sales_orders WHERE id = $1`,
[orderId],
)
expect(rows[0]!.order_number).toBeNull()
})
it('refuses an anon-shaped caller (role claim, no sub)', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const orderId = await insertOrder(companyId, userId, customerId, 'draft')
const client = await getClient()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('request.jwt.claims', '{"role":"anon"}', true)`)
await client.query(`SELECT set_config('request.jwt.claim.role', 'anon', true)`)
await expect(
client.query('SELECT public.generate_sales_order_number($1, $2)', [companyId, orderId]),
).rejects.toThrow(/unauthorized/i)
} finally {
await client.query('ROLLBACK').catch(() => {})
client.release()
}
})
})
describe('sales_orders RLS', () => {
it('isolates orders and lines by company', async () => {
const { userId, companyId, orderId, itemId } = await seedOrderWithLine()
const stranger = await insertAuthUser()
const own = await withUserContext(userId, async (client) => {
const orders = await client.query(`SELECT id FROM public.sales_orders WHERE id = $1`, [orderId])
const items = await client.query(`SELECT id FROM public.sales_order_items WHERE id = $1`, [itemId])
return { orders: orders.rows.length, items: items.rows.length }
})
expect(own).toEqual({ orders: 1, items: 1 })
const other = await withUserContext(stranger, async (client) => {
const orders = await client.query(`SELECT id FROM public.sales_orders WHERE id = $1`, [orderId])
const items = await client.query(`SELECT id FROM public.sales_order_items WHERE id = $1`, [itemId])
return { orders: orders.rows.length, items: items.rows.length }
})
expect(other).toEqual({ orders: 0, items: 0 })
// A member can read the RPC; a stranger sees nothing through it.
const strangerRpc = await withUserContext(stranger, (client) =>
client.query(`SELECT * FROM public.sales_order_invoiced_quantities(ARRAY[$1::uuid])`, [orderId]),
)
expect(strangerRpc.rows).toHaveLength(0)
expect(companyId).toBeTruthy()
})
})
describe('over-invoicing guard on invoice_items', () => {
it('sums linked lines and refuses a line that would exceed the ordered quantity', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(10)
const invA = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(invA, 6, itemId)
expect(await invoicedQty(orderId, itemId)).toBe(6)
const invB = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await expect(insertInvoiceItem(invB, 5, itemId)).rejects.toThrow(/SALES_ORDER_OVER_INVOICED/)
await insertInvoiceItem(invB, 4, itemId)
expect(await invoicedQty(orderId, itemId)).toBe(10)
})
it('releases the quantity when the invoice is cancelled or credited', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(10)
const invA = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(invA, 10, itemId)
const invB = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await expect(insertInvoiceItem(invB, 1, itemId)).rejects.toThrow(/SALES_ORDER_OVER_INVOICED/)
await getPool().query(`UPDATE public.invoices SET status = 'cancelled' WHERE id = $1`, [invA])
expect(await invoicedQty(orderId, itemId)).toBe(0)
await insertInvoiceItem(invB, 10, itemId)
expect(await invoicedQty(orderId, itemId)).toBe(10)
// A credited invoice is by definition numbered (invoices_sent_requires_number).
await getPool().query(
`UPDATE public.invoices SET invoice_number = $2, status = 'credited' WHERE id = $1`,
[invB, `F-${invB.slice(0, 8)}`],
)
expect(await invoicedQty(orderId, itemId)).toBe(0)
})
it('refuses linking an invoice line to another company\'s order line', async () => {
const victim = await seedOrderWithLine(10)
const attacker = await seedCompany()
await seedSettings(attacker.companyId, attacker.userId)
const attackerCustomer = await insertCustomer(attacker.companyId, attacker.userId)
const inv = await insertInvoice(attacker.companyId, attacker.userId, attackerCustomer)
await expect(insertInvoiceItem(inv, 1, victim.itemId)).rejects.toThrow(/SALES_ORDER_ITEM_COMPANY_MISMATCH/)
})
it('refuses a dangling order line reference', async () => {
const { userId, companyId, customerId } = await seedOrderWithLine(1)
const inv = await insertInvoice(companyId, userId, customerId)
await expect(insertInvoiceItem(inv, 1, randomUUID())).rejects.toThrow()
})
})
describe('order line guards', () => {
it('refuses lowering quantity below the invoiced quantity', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(10)
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(inv, 6, itemId)
await expect(
getPool().query(`UPDATE public.sales_order_items SET quantity = 5 WHERE id = $1`, [itemId]),
).rejects.toThrow(/SALES_ORDER_QUANTITY_BELOW_INVOICED/)
await getPool().query(`UPDATE public.sales_order_items SET quantity = 6 WHERE id = $1`, [itemId])
await getPool().query(`UPDATE public.sales_order_items SET quantity = 12 WHERE id = $1`, [itemId])
})
it('refuses delivered_qty above quantity', async () => {
const { itemId } = await seedOrderWithLine(3)
await expect(
getPool().query(`UPDATE public.sales_order_items SET delivered_qty = 4 WHERE id = $1`, [itemId]),
).rejects.toThrow(/sales_order_items_delivered_within_ordered/)
await getPool().query(`UPDATE public.sales_order_items SET delivered_qty = 3 WHERE id = $1`, [itemId])
})
it('refuses deleting an order line with linked invoice lines', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(2)
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(inv, 1, itemId)
await expect(
getPool().query(`DELETE FROM public.sales_order_items WHERE id = $1`, [itemId]),
).rejects.toThrow(/foreign key|violates/i)
await expect(
getPool().query(`DELETE FROM public.sales_orders WHERE id = $1`, [orderId]),
).rejects.toThrow(/foreign key|violates/i)
})
})
describe('completion maintenance', () => {
it('flips confirmed -> completed when every product line is fully invoiced, and back on cancel', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(10)
await insertOrderItem(companyId, orderId, 0, { lineType: 'text', sortOrder: 1 })
const second = await insertOrderItem(companyId, orderId, 2, { sortOrder: 2 })
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(inv, 10, itemId)
expect((await orderStatus(orderId)).status).toBe('confirmed')
await insertInvoiceItem(inv, 2, second)
const done = await orderStatus(orderId)
expect(done.status).toBe('completed')
expect(done.completed_at).not.toBeNull()
await getPool().query(`UPDATE public.invoices SET status = 'cancelled' WHERE id = $1`, [inv])
const reopened = await orderStatus(orderId)
expect(reopened.status).toBe('confirmed')
expect(reopened.completed_at).toBeNull()
})
it('reopens when a draft invoice created from the order is deleted', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(4)
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(inv, 4, itemId)
expect((await orderStatus(orderId)).status).toBe('completed')
await getPool().query(`DELETE FROM public.invoice_items WHERE invoice_id = $1`, [inv])
await getPool().query(`DELETE FROM public.invoices WHERE id = $1`, [inv])
expect((await orderStatus(orderId)).status).toBe('confirmed')
})
it('never touches draft or cancelled orders', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const draft = await insertOrder(companyId, userId, customerId, 'draft')
const draftItem = await insertOrderItem(companyId, draft, 1)
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: draft })
await insertInvoiceItem(inv, 1, draftItem)
expect((await orderStatus(draft)).status).toBe('draft')
})
it('completes on confirm-time refresh when lines are already covered, and gates the RPC on membership', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const customerId = await insertCustomer(companyId, userId)
const draft = await insertOrder(companyId, userId, customerId, 'draft')
const item = await insertOrderItem(companyId, draft, 1)
const inv = await insertInvoice(companyId, userId, customerId, { salesOrderId: draft })
await insertInvoiceItem(inv, 1, item)
await getPool().query(`UPDATE public.sales_orders SET status = 'confirmed' WHERE id = $1`, [draft])
expect((await orderStatus(draft)).status).toBe('confirmed')
const outsider = await seedCompany()
await expect(
withUserContext(outsider.userId, (client) =>
client.query('SELECT public.refresh_sales_order_completion($1)', [draft]),
),
).rejects.toThrow(/unauthorized/i)
// withUserContext rolls back at the end, so read the effect inside it.
const memberView = await withUserContext(userId, async (client) => {
await client.query('SELECT public.refresh_sales_order_completion($1)', [draft])
const res = await client.query<{ status: string }>(
`SELECT status FROM public.sales_orders WHERE id = $1`,
[draft],
)
return res.rows[0]!.status
})
expect(memberView).toBe('completed')
})
})
describe('sales_order_invoiced_quantities RPC', () => {
it('returns one row per line with cancelled and credit-note lines excluded', async () => {
const { userId, companyId, customerId, orderId, itemId } = await seedOrderWithLine(10)
const second = await insertOrderItem(companyId, orderId, 5, { sortOrder: 1 })
const invA = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId })
await insertInvoiceItem(invA, 3, itemId)
await insertInvoiceItem(invA, 5, second)
const invCancelled = await insertInvoice(companyId, userId, customerId, { salesOrderId: orderId, status: 'cancelled' })
await insertInvoiceItem(invCancelled, 7, itemId)
const creditNote = await insertInvoice(companyId, userId, customerId, { creditedInvoiceId: invA })
await insertInvoiceItem(creditNote, -3, itemId)
const { rows } = await getPool().query<{ sales_order_item_id: string; invoiced_qty: string }>(
`SELECT sales_order_item_id, invoiced_qty FROM public.sales_order_invoiced_quantities(ARRAY[$1::uuid]) ORDER BY invoiced_qty`,
[orderId],
)
const byItem = new Map(rows.map((r) => [r.sales_order_item_id, Number(r.invoiced_qty)]))
expect(byItem.get(itemId)).toBe(3)
expect(byItem.get(second)).toBe(5)
})
})
describe('hardening (20260902180000)', () => {
it('refuses an order line whose company differs from its parent order (composite FK)', async () => {
const victim = await seedOrderWithLine(1)
const attacker = await seedCompany()
await expect(
getPool().query(
`INSERT INTO public.sales_order_items (company_id, sales_order_id, description, quantity)
VALUES ($1, $2, 'Smuggled line', 1)`,
[attacker.companyId, victim.orderId],
),
).rejects.toThrow(/sales_order_items_order_company_fkey|foreign key/i)
})
it('blocks a viewer from writing orders and lines through the session client, and lets a member through', async () => {
const { userId, companyId, customerId } = await seedOrderWithLine(1)
const viewer = await insertAuthUser()
await insertCompanyMember({ companyId, userId: viewer, role: 'viewer' })
const member = await insertAuthUser()
await insertCompanyMember({ companyId, userId: member, role: 'member' })
await expect(
withUserContext(viewer, (client) =>
client.query(
`INSERT INTO public.sales_orders (company_id, user_id, customer_id) VALUES ($1, $2, $3)`,
[companyId, viewer, customerId],
),
),
).rejects.toThrow(/no write access|row-level security/i)
const inserted = await withUserContext(member, async (client) => {
const res = await client.query<{ id: string }>(
`INSERT INTO public.sales_orders (company_id, user_id, customer_id) VALUES ($1, $2, $3) RETURNING id`,
[companyId, member, customerId],
)
return res.rows[0]!.id
})
expect(inserted).toBeTruthy()
expect(userId).toBeTruthy()
})
it('carries the per-line delivery date and the customer VAT snapshot columns', async () => {
const { orderId, itemId } = await seedOrderWithLine(2)
await getPool().query(
`UPDATE public.sales_order_items SET delivered_qty = 1, last_delivery_date = '2026-09-01' WHERE id = $1`,
[itemId],
)
await getPool().query(
`UPDATE public.sales_orders SET customer_type_snapshot = 'eu_business', customer_vat_validated_snapshot = true WHERE id = $1`,
[orderId],
)
const { rows } = await getPool().query<{ last_delivery_date: string; customer_type_snapshot: string }>(
`SELECT soi.last_delivery_date::text, so.customer_type_snapshot
FROM public.sales_order_items soi JOIN public.sales_orders so ON so.id = soi.sales_order_id
WHERE soi.id = $1`,
[itemId],
)
expect(rows[0]!.last_delivery_date).toBe('2026-09-01')
expect(rows[0]!.customer_type_snapshot).toBe('eu_business')
await expect(
getPool().query(`UPDATE public.sales_orders SET customer_type_snapshot = 'company' WHERE id = $1`, [orderId]),
).rejects.toThrow(/check/i)
})
})
+9 -1
View File
@@ -145,7 +145,15 @@ const KNOWN_STALE_ON_CONFLICT: Record<string, string> = {}
// lib/stripe/subscription-sync.ts scopes the cancel-time multi_user expiry
// update with an .or() interpolating a timestamp; every column named in both
// strings is a literal (company_id, team_id, expires_at).
const UNRESOLVED_CEILING = 393
// 2026-09-02: +2 for kundorder (lib/sales-orders): create-invoice-from-order.ts
// spreads buildInvoiceWriteData()'s invoiceFields into the invoices insert and
// maps its item rows into invoice_items, the exact shape the webshop
// create-invoice route and POST /api/invoices already use (their columns are
// pinned by build-invoice-write.ts and its tests); write.ts inserts order
// lines as a row array built from one literal mapper (toInsertRow). Every
// header/line update in the module is an object literal. Merged with main
// (parties phase 1, #2162/#2168/#2169) at 395: 397.
const UNRESOLVED_CEILING = 397
/**
* Floor on statically resolved column references. Guards the guard: if a change
+112
View File
@@ -548,6 +548,12 @@ export interface CompanySettings {
// for correctness. The nav row also shows when mileage_trips rows exist.
mileage_enabled: boolean
// Kundorder (sales orders): UI-visibility toggle only, never load-bearing
// for correctness (the /sales-orders pages and APIs work regardless).
sales_orders_enabled: boolean
// Per-company counter behind generate_sales_order_number (OR-<n>).
next_sales_order_number?: number
// Data analysis consent (migration 20260828120000): when true, the
// company's bookkeeping outcomes may be read across companies to evaluate
// and improve automatic booking. Default false, enforced server-side
@@ -942,6 +948,96 @@ export interface SupplierPaymentBatchItem {
created_at: string
}
// Kundorder (sales order): the non-ledger document between agreement and
// invoice. Never books. Four-state header machine; delivery and invoicing
// progress are derived per line (see SalesOrderItem.invoiced_qty).
export type SalesOrderStatus = 'draft' | 'confirmed' | 'completed' | 'cancelled'
/** Derived per-axis progress: none / partial / full. */
export type SalesOrderProgress = 'none' | 'partial' | 'full'
export interface SalesOrder {
id: string
company_id: string
user_id: string
customer_id: string | null
/** OR-<n>, allocated at creation by generate_sales_order_number. */
order_number: string | null
status: SalesOrderStatus
/** Proforma the order was converted from, if any. */
source_invoice_id: string | null
order_date: string
requested_delivery_date: string | null
/** Latest registered delivery date across all lines (display only; invoices use per-line dates). */
last_delivery_date: string | null
/** Customer facts the lines were VAT-validated under; invoicing refuses when they changed. */
customer_type_snapshot?: CustomerType | null
customer_vat_validated_snapshot?: boolean | null
currency: string
subtotal: number
vat_amount: number
total: number
your_reference: string | null
our_reference: string | null
notes: string | null
default_dimensions: Record<string, string>
confirmed_at: string | null
completed_at: string | null
cancelled_at: string | null
created_at: string
updated_at: string
// Embeds / derived (list + detail responses)
customer?: Customer | null
items?: SalesOrderItem[]
delivery_progress?: SalesOrderProgress
invoicing_progress?: SalesOrderProgress
}
export interface SalesOrderItem {
id: string
company_id: string
sales_order_id: string
sort_order: number
line_type: 'product' | 'text'
description: string
quantity: number
/** Stored: registered by the user via the deliver action. */
delivered_qty: number
/** Latest delivery date registered for this line (null until delivered). */
last_delivery_date?: string | null
unit: string
unit_price: number
discount_percent: number
vat_rate: number
/** NET of discount, order currency. */
line_total: number
article_id: string | null
revenue_account: string | null
dimensions: Record<string, string>
created_at: string
updated_at: string
/** Derived from linked invoice_items on non-cancelled, non-credited invoices. */
invoiced_qty?: number
/** quantity - invoiced_qty (never negative). */
remaining_qty?: number
}
export interface SalesOrderItemInput {
id?: string
line_type?: 'product' | 'text'
description: string
quantity: number
unit: string
unit_price: number
discount_percent?: number | null
vat_rate?: number
article_id?: string | null
revenue_account?: string | null
dimensions?: Record<string, string>
}
// Article (artikelregister): reusable invoice-line preset. NON-INVENTORY:
// no stock fields and no inventory postings, by deliberate design.
export type ArticleType = 'vara' | 'tjanst'
@@ -1234,6 +1330,10 @@ export interface Invoice {
// Conversion tracking (proforma -> invoice)
converted_from_id: string | null
// Kundorder this invoice was created from (sales_orders.id). Header-level
// provenance only; the per-line link is invoice_items.sales_order_item_id.
sales_order_id?: string | null
// Self-billing received (mottagen självfaktura, ML 17 kap 15§). When
// `is_self_billed` is true the customer issued the invoice on our behalf;
// for us it is a sale. The counterparty's number lives in
@@ -1388,6 +1488,12 @@ export interface InvoiceItem {
article_id?: string | null
revenue_account?: string | null
// Kundorder line this invoice line was created from. The order line's
// invoiced quantity is DERIVED from these links (never stored), so an
// edit that drops the link would free the quantity for double invoicing:
// every write path round-trips it.
sales_order_item_id?: string | null
// Periodisering (förutbetald intäkt): when set, the revenue entry credits
// accrual_balance_account (29xx) instead of the line's revenue account, and
// an accrual_schedules row dissolves the net amount monthly over the
@@ -2205,6 +2311,12 @@ export type PendingOperationType =
| 'update_company_settings'
| 'create_article'
| 'update_article'
// Kundorder (gnubok_create_sales_order / _transition_sales_order /
// _register_sales_order_delivery / _create_invoice_from_sales_order)
| 'create_sales_order'
| 'transition_sales_order'
| 'register_sales_order_delivery'
| 'create_invoice_from_sales_order'
// Kontoplan reference data (gnubok_create_account / gnubok_update_account)
| 'create_account'
| 'update_account'