Files
accounted/supabase/migrations/20260908165000_quote_source_conversion_guards.sql
Mattsson 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

118 lines
4.5 KiB
PL/PgSQL

-- Offert -> kundorder (issue #2224): the sale behind a quote must never
-- exist twice. The services check for a live converted invoice and a live
-- kundorder before converting, but those reads are not serialized: two
-- conversions of an already-accepted quote (order + order, or order +
-- invoice) both pass their pre-checks, and the quote's compare-and-set
-- (accepted -> accepted) matches for both. Only the database can close
-- that window.
--
-- 1. One live kundorder per source document (partial unique index). A
-- cancelled order frees the source again, matching the service rule.
-- 2. A kundorder whose source is a quote cannot become live (insert, or
-- reopen from cancelled) while a live invoice was converted from that
-- quote. The trigger locks the quote row first (FOR UPDATE), so a
-- concurrent converted-invoice insert queues behind it and sees the
-- committed order.
-- 3. The mirror: an invoice with converted_from_id = a quote cannot become
-- live while a live kundorder points at that quote. Same lock, same
-- serialization, raised with the registry code the services map to 409
-- INVOICE_QUOTE_ALREADY_ORDERED.
--
-- Both triggers exit before the lock on every update that does not make a
-- row live (the common status changes), and never touch proformas: the
-- proforma path cancels its source, which its compare-and-set already
-- serializes.
CREATE UNIQUE INDEX IF NOT EXISTS uq_sales_orders_one_live_per_source
ON public.sales_orders (source_invoice_id)
WHERE source_invoice_id IS NOT NULL AND status <> 'cancelled';
CREATE OR REPLACE FUNCTION public.sales_orders_source_guard()
RETURNS trigger
LANGUAGE plpgsql
SET search_path = ''
AS $function$
DECLARE
v_source_type text;
BEGIN
IF NEW.source_invoice_id IS NULL OR NEW.status = 'cancelled' THEN
RETURN NEW;
END IF;
-- Only a row that BECOMES live is checked: an insert, a reopen from
-- cancelled, or a re-pointed source.
IF TG_OP = 'UPDATE'
AND OLD.status <> 'cancelled'
AND OLD.source_invoice_id IS NOT DISTINCT FROM NEW.source_invoice_id THEN
RETURN NEW;
END IF;
SELECT i.document_type INTO v_source_type
FROM public.invoices i
WHERE i.id = NEW.source_invoice_id
FOR UPDATE;
IF v_source_type = 'quote' AND EXISTS (
SELECT 1 FROM public.invoices c
WHERE c.converted_from_id = NEW.source_invoice_id
AND c.status <> 'cancelled'
) THEN
RAISE EXCEPTION 'INVOICE_QUOTE_ALREADY_INVOICED: quote % has a live converted invoice', NEW.source_invoice_id
USING ERRCODE = 'P0001';
END IF;
RETURN NEW;
END;
$function$;
DROP TRIGGER IF EXISTS trg_sales_orders_source_guard ON public.sales_orders;
CREATE TRIGGER trg_sales_orders_source_guard
BEFORE INSERT OR UPDATE OF status, source_invoice_id ON public.sales_orders
FOR EACH ROW
EXECUTE FUNCTION public.sales_orders_source_guard();
CREATE OR REPLACE FUNCTION public.invoices_converted_source_guard()
RETURNS trigger
LANGUAGE plpgsql
SET search_path = ''
AS $function$
DECLARE
v_source_type text;
BEGIN
IF NEW.converted_from_id IS NULL OR NEW.status = 'cancelled' THEN
RETURN NEW;
END IF;
IF TG_OP = 'UPDATE'
AND OLD.status <> 'cancelled'
AND OLD.converted_from_id IS NOT DISTINCT FROM NEW.converted_from_id THEN
RETURN NEW;
END IF;
SELECT i.document_type INTO v_source_type
FROM public.invoices i
WHERE i.id = NEW.converted_from_id
FOR UPDATE;
IF v_source_type = 'quote' AND EXISTS (
SELECT 1 FROM public.sales_orders o
WHERE o.source_invoice_id = NEW.converted_from_id
AND o.status <> 'cancelled'
) THEN
RAISE EXCEPTION 'INVOICE_QUOTE_ALREADY_ORDERED: quote % has a live kundorder', NEW.converted_from_id
USING ERRCODE = 'P0001';
END IF;
RETURN NEW;
END;
$function$;
DROP TRIGGER IF EXISTS trg_invoices_converted_source_guard ON public.invoices;
CREATE TRIGGER trg_invoices_converted_source_guard
BEFORE INSERT OR UPDATE OF status, converted_from_id ON public.invoices
FOR EACH ROW
EXECUTE FUNCTION public.invoices_converted_source_guard();
COMMENT ON FUNCTION public.sales_orders_source_guard() IS
'A kundorder created from a quote cannot become live while a live invoice was converted from that quote. Locks the quote row so concurrent conversions serialize. Raises INVOICE_QUOTE_ALREADY_INVOICED.';
COMMENT ON FUNCTION public.invoices_converted_source_guard() IS
'An invoice converted from a quote cannot become live while a live kundorder was created from that quote. Locks the quote row so concurrent conversions serialize. Raises INVOICE_QUOTE_ALREADY_ORDERED.';
NOTIFY pgrst, 'reload schema';