feat(sales-orders): kundorder with partial delivery and partial invoicing (#2166)
* feat(sales-orders): kundorder with partial delivery and partial invoicing Adds sales orders (kundorder) as their own non-ledger document between agreement and invoice, for companies that deliver or invoice in parts. Schema (20260902130000): sales_orders + sales_order_items with RLS via user_company_ids(), OR-<n> numbering RPC (membership-gated, no anon execute), company_settings.sales_orders_enabled UI gate, and back-links invoices.sales_order_id / invoice_items.sales_order_item_id. The invoiced quantity per order line is DERIVED from the linked invoice lines on non-cancelled, non-credited invoices and enforced by a BEFORE trigger, so no counter can drift and a credited invoice frees its quantity. Header status is draft / confirmed / completed / cancelled; completion is kept by DB triggers from the same derived quantity. Delivery and invoicing progress are derived per line, never stored as status. Service + API: lib/sales-orders (create/update with id-preserving line replace, transitions with compare-and-set, cumulative delivery registration, invoice-from-order through buildInvoiceWriteData so booking stays in the engine, proforma -> order conversion), routes under /api/sales-orders and /api/invoices/[id]/convert-to-order, structured SALES_ORDER_* error codes, archive classification of the new tables. The invoice editor round-trips sales_order_item_id so a draft edit cannot drop the link; GET /api/invoices gains ?sales_order_id=. UI: /sales-orders list, create/edit form reusing the invoice line conventions, detail with deliver and create-invoice dialogs and linked invoices; nav row behind the settings toggle; the webshop row is relabelled webshop_orders; "Skapa order" on proformas. MCP (20260902141000/141001): list/get reads plus four staged writes (create, transition, register delivery, create invoice from order) whose executors call the lib services; op types added to the pending operations CHECK. Tests: route tests for every route (401/400/404/happy), service unit tests, executor and tool tests, and tests/pg/sales-orders.pg.test.ts (16 cases, green on staging) covering RLS, numbering guards, the over-invoice trigger incl. release on cancel/credit and cross-company refusal, the quantity floor, and completion maintenance. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RQW7mXvbAPgjUHq7dSEamr * fix(sales-orders): harden kundorder after skeptic and security review Resolves every finding from the PR #2166 review pass in one batch. Order link integrity: replaceInvoiceItems now refuses a line set that drops an existing sales_order_item_id (INVOICE_UPDATE_DROPS_ORDER_LINK), closing the MCP update_invoice header-only edit and the v1 PATCH path that severed the link and freed the quantity for double invoicing. The update_invoice re-fetch, gnubok_get_invoice and the v1 item projection now carry sales_order_item_id so well-behaved clients round-trip it. Quantity math: derived remaining/invoiced quantities are rounded to six decimals and compared with an epsilon (roundQty, qtyGreater) so a float remainder such as 0.5999999999999996 can neither refuse the final partial invoice nor land as an invoice quantity; duplicate explicit picks are summed before validation. Leveransdatum: per-line last_delivery_date (migration 20260902160000); an invoice takes the latest date over the lines it covers and only when the covered quantity was delivered, never the header date and never for an advance invoice (ML 17 kap 24 p.7, FX anchor per ML 8 kap 21-23). VAT drift: the order stores the customer type and VAT-validation flag its lines were priced under; invoicing refuses with SALES_ORDER_CUSTOMER_VAT_CHANGED when they differ, and re-saving the order re-validates the lines. Customer and currency are frozen once invoices exist. Tenant and role gates: composite FK (sales_order_id, company_id) ties a line to its parent's company (Superagent P2); aa_enforce_company_writer_role on both tables so a viewer cannot write through the browser client. Proforma -> order refuses proformas with ROT/RUT, periodisering or negative-quantity lines instead of dropping those fields. RESTRICT FK errors on delete map to SALES_ORDER_LINE_LOCKED / SALES_ORDER_HAS_INVOICES. Also: schema-guard literal payloads in lib/sales-orders (ceiling +2 with reason), regenerated skills/accounted-api (sales_order_item_id on invoice items), pg tests for the composite FK, the viewer gate and the new columns, unit tests for every changed path. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): resolve CodeRabbit round on PR #2166 Quick wins from the review, all in one pass: - replaceInvoiceItems fails closed when the invoice_items snapshot cannot be read (it is both the restore source and the input to the kundorder link guard); the guard branch is explicit in both PATCH routes. - Cumulative delivery registration carries an optimistic predicate on the quantity it read, so two concurrent registrations cannot regress each other; DELETE of an order keeps its allowed status in the predicate and answers a conflict when zero rows match. - Business dates (order date, delivery date, invoice date) default to the Europe/Stockholm calendar day (todayIsoStockholm), never UTC: the delivery date is also the Riksbanken rate anchor. - The invoice-from-order executor treats an event emit failure as non-blocking: the draft already exists. - sales_order_items are archived through their parent with the order currency denormalised, like invoice_items. - Proforma "Skapa order" tolerates a 2xx without a parsable body; the settings toggle refreshes the server-rendered nav. - List route doc states that q matches the order number (customer names are matched client-side). Declined (out of scope for this PR): moving header + line writes and the delivery loop into transactional RPCs (same PostgREST pattern as the invoice PATCH path, tracked as a follow-up), the MCP approval handler's error message shape (pre-existing code outside this change), and the docstring-coverage warning (no repo convention). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): move hardening migration off a colliding version; archive contract; ceiling - 20260902160000_sales_orders_hardening.sql collided with main's 20260902160000_parties_substrate.sql after the third sync; renamed to 20260902180000 and made idempotent (DROP ... IF EXISTS before each ADD CONSTRAINT) so a preview branch that applied it under the old version replays it cleanly. Staging's schema_migrations row renamed. - sales_order_items goes back to a direct archive dump: the coverage contract (tests/pg/full-archive-coverage.pg.test.ts) requires it for a table with its own company_id; the currency lives on the parent order one file over, joined by sales_order_id. - Scanner ceiling re-baselined after merging main (parties phase 1): 397. - v1 PATCH test queues a real empty invoice_items snapshot now that replaceInvoiceItems fails closed on an unreadable one. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW * fix(sales-orders): drop the composite FK before its unique index on replay The idempotent guard in 20260902180000_sales_orders_hardening.sql dropped the unique (id, company_id) before the FK that depends on its index, so the preview branch replay (which had applied the file under its former version) failed with SQLSTATE 2BP01. Order swapped; replay verified on staging. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XzFmmH82hCJNmZbPqycDiW --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
c40e63e3f7
commit
c0818bb2d2
@@ -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
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user