Files
accounted/lib/sales-orders/create-invoice-from-order.ts
T
MattssonandClaude Fable 5.1 9782f80db0 feat(invoices): offert to kundorder, the missing step in offert, order, faktura (#2442)
* feat(invoices): offert to kundorder, the missing step in offert, order, faktura

"Skapa order" on an open or accepted quote creates a draft kundorder from
its lines. The quote stays as the customer's accepted agreement (flips to
quote_status accepted with a compare-and-set on the decision that was
read); the order is delivered and invoiced, in full or in parts, from the
kundorder page. Declined quotes are refused. Same action on the MCP side:
gnubok_convert_invoice takes target 'order', staged under the existing
convert_invoice operation type.

Why the problem occurred: the proforma -> order conversion refused every
source that was not a proforma, so the offert, which is what users
actually send before an order, could only become an invoice. The product
had both ends of the Fortnox flow (offert, kundorder) but no bridge.

What was removed or simplified: no second service and no new operation
type. The proforma conversion became the document conversion
(lib/sales-orders/convert-to-sales-order.ts) with the quote source as a
branch on the source update, mirroring how convertToInvoice already
treats the two. The MCP surface is one tool with a target parameter
rather than a sibling tool, which also gives proforma -> order the MCP
surface it did not have.

Why this shape: the sale must never exist twice. A quote with a live
converted invoice cannot become an order (INVOICE_QUOTE_ALREADY_INVOICED),
and a quote with a live kundorder cannot become an invoice a second time
(new INVOICE_QUOTE_ALREADY_ORDERED: invoice from the order instead). A
cancelled order or invoice frees the quote again. Rejected: cancelling the
quote like the proforma path (hides the accepted agreement), a separate
gnubok_convert_quote_to_order tool, and refusing expired quotes (the
invoice path allows them behind a confirm; the order path does the same).

Fixes #2224

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

* fix(sales-orders): hold the one-sale-per-quote guard in the database and fail closed on a missing FX rate

Skeptic refutations on the offert -> kundorder change:

1. An already-accepted quote could be converted twice concurrently (two
   orders, or an order and an invoice): the services' pre-checks are not
   serialized and the accepted -> accepted compare-and-set matches for
   every caller. Migration 20260908152555 adds a partial unique index
   (one live kundorder per source document) and two BEFORE triggers that
   lock the quote row and refuse a live order beside a live converted
   invoice and vice versa, so concurrent conversions queue and the second
   one sees the first. The services map the raised codes onto the same
   409s the pre-checks use. pg-real test covers the index, both
   directions, reopen from cancelled, the member-session lock, and the
   concurrent pair on two connections.

2. createInvoiceFromSalesOrder booked a foreign-currency invoice with a
   NULL exchange rate when Riksbanken had none, which resolveSekAmount()
   then posts 1:1 as kronor. Pre-existing, but the quote now depends on
   the order path and the fail-closed quote -> invoice route is refused
   while an order lives. The order path now fails closed with
   SALES_ORDER_INVOICE_FX_RATE_UNAVAILABLE, like convertToInvoice.

Refs #2224

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(pending): describe the kundorder outcome when approving a convert_invoice staged with target order

The approval dialog's consequence sentence was keyed on operation_type
alone and promised a faktura with F-number for every convert_invoice.
With target 'order' the commit creates a draft kundorder and books
nothing, so the sentence now reads the params (skeptic refutation).

Refs #2224

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(invoices): lock the quote decision behind a live kundorder, run the guards as definer, name the offert on the order page

Correctness skeptic refutations on the offert -> kundorder change:

1. A quote with a live kundorder could still be set to open or declined
   (dashboard route, v1, MCP): the decision guard only knew converted
   invoices. The dashboard then hid the re-accept button, so the quote
   was stuck as "Avböjd" behind a confirmed, invoiced order. Migration
   20260908155231 extends invoices_quote_decision_guard to refuse leaving
   accepted while a live kundorder points at the quote
   (INVOICE_QUOTE_ALREADY_ORDERED); the three writers map the code.

2. The two source guards from 20260908152555 locked the quote row with a
   SELECT FOR UPDATE as the invoker. Under RLS that also applies the
   UPDATE policy, which admits only the caller's active company, so a
   multi-company member writing for another company through raw
   PostgREST got no row, no lock and no guard. All three guard functions
   are now SECURITY DEFINER. pg-real test covers the non-active company
   and the decision lock.

3. The kundorder page labelled every source "Proformafaktura". It now
   loads the source document and shows "Offert OF-nnn" for a quote; the
   MCP field description and the type comment say proforma or quote.

Refs #2224

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(mcp): keep tools/list under its token ceiling and refuse cross-company sources in the definer guards

CI: the target parameter and two description edits pushed the projected
tools/list payload to 60 502 tokens against the 60 500 ceiling; the same
facts now fit in fewer words (ceiling unchanged).

Superagent P2: the source guards run as definer since 20260908155231, so
a source_invoice_id or converted_from_id pointing at another company's
document would have locked and inspected that row. Both guards now
require the source to belong to the row's company and refuse otherwise
(SALES_ORDER_SOURCE_COMPANY_MISMATCH / INVOICE_CONVERT_SOURCE_COMPANY_MISMATCH),
covered by a cross-company pg-real case. Migration 20260908155231 was
re-applied to staging under the same version (never on prod).

Refs #2224

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(migrations): move the quote conversion guards to versions after main's 20260908164944

Main merged a later version while this branch was open; Supabase applies
pending versions in order, so both files are renamed to fresh versions
(20260908165000, 20260908165100) and re-tracked on staging under those.
Byte-identical SQL.

Refs #2224

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 18:29:37 +02:00

245 lines
9.6 KiB
TypeScript

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)
}
// Fail closed on a missing Riksbanken rate, like convertToInvoice does: the
// builder leaves exchange_rate NULL on a miss and resolveSekAmount() would
// then book the foreign amount 1:1 as kronor on 1510/3xxx/26xx.
if (order.currency !== 'SEK' && build.invoiceFields.exchange_rate == null) {
return fail('SALES_ORDER_INVOICE_FX_RATE_UNAVAILABLE', { currency: order.currency })
}
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 }
}