Files
accounted/tests/pg/quote-source-conversion-guards.pg.test.ts
T
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

296 lines
14 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getClient, getPool, withUserContext } from './setup'
import { insertCompany, insertCompanyMember, seedCompany } from './fixtures'
// pg-real coverage for migrations 20260908165000 and 20260908165100 (issue
// #2224, offert -> kundorder): one live kundorder per source document, a
// quote with a live converted invoice cannot get a live order, a quote with
// a live order cannot get a live converted invoice, the quote decision is
// locked while an order lives, the guards run as definer so a non-active
// company is still guarded, and the two conversions serialize on the quote
// row so a concurrent pair cannot both land.
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 insertSource(
companyId: string,
userId: string,
customerId: string,
documentType: 'quote' | 'proforma',
): Promise<string> {
const id = randomUUID()
const isQuote = documentType === 'quote'
await getPool().query(
`INSERT INTO public.invoices
(id, user_id, company_id, customer_id, invoice_number, document_type,
invoice_date, due_date, valid_until, quote_status, currency,
subtotal, vat_amount, total, vat_treatment, vat_rate, moms_ruta, status)
VALUES ($1, $2, $3, $4, $5, $6,
'2026-06-01', '2026-07-01', $7, $8, 'SEK',
1000, 250, 1250, 'standard_25', 25, '10', 'sent')`,
[
id,
userId,
companyId,
customerId,
isQuote ? 'OF-001' : 'P-001',
documentType,
isQuote ? '2026-07-01' : null,
isQuote ? 'accepted' : null,
],
)
return id
}
function orderInsertSql(): string {
return `INSERT INTO public.sales_orders (id, company_id, user_id, customer_id, status, order_date, source_invoice_id)
VALUES ($1, $2, $3, $4, $5, '2026-09-01', $6)`
}
async function insertOrder(
companyId: string,
userId: string,
customerId: string,
sourceInvoiceId: string,
status: 'draft' | 'cancelled' = 'draft',
): Promise<string> {
const id = randomUUID()
await getPool().query(orderInsertSql(), [id, companyId, userId, customerId, status, sourceInvoiceId])
return id
}
function convertedInvoiceSql(): string {
return `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, converted_from_id)
VALUES ($1, $2, $3, $4, NULL, 'invoice',
'2026-09-01', '2026-10-01', 'SEK', 1000, 250, 1250,
'standard_25', 25, '10', $5, $6)`
}
async function insertConvertedInvoice(
companyId: string,
userId: string,
customerId: string,
convertedFromId: string,
status: 'draft' | 'cancelled' = 'draft',
): Promise<string> {
const id = randomUUID()
await getPool().query(convertedInvoiceSql(), [id, userId, companyId, customerId, status, convertedFromId])
return id
}
describe('quote source conversion guards (20260908165000)', () => {
it('allows one live kundorder per source and refuses a second one until the first is cancelled', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const first = await insertOrder(companyId, userId, customerId, quoteId)
await expect(insertOrder(companyId, userId, customerId, quoteId)).rejects.toThrow(
/uq_sales_orders_one_live_per_source/,
)
// A cancelled second order is not live and may point at the same source.
await insertOrder(companyId, userId, customerId, quoteId, 'cancelled')
await getPool().query(`UPDATE public.sales_orders SET status = 'cancelled' WHERE id = $1`, [first])
await expect(insertOrder(companyId, userId, customerId, quoteId)).resolves.toBeTruthy()
})
it('refuses a live converted invoice while a live kundorder points at the quote, and frees it on cancel', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const orderId = await insertOrder(companyId, userId, customerId, quoteId)
await expect(insertConvertedInvoice(companyId, userId, customerId, quoteId)).rejects.toThrow(
/INVOICE_QUOTE_ALREADY_ORDERED/,
)
// A cancelled converted invoice is not live and is allowed.
await insertConvertedInvoice(companyId, userId, customerId, quoteId, 'cancelled')
await getPool().query(`UPDATE public.sales_orders SET status = 'cancelled' WHERE id = $1`, [orderId])
await expect(insertConvertedInvoice(companyId, userId, customerId, quoteId)).resolves.toBeTruthy()
})
it('refuses a live kundorder (insert or reopen) while a live invoice was converted from the quote', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const cancelledOrder = await insertOrder(companyId, userId, customerId, quoteId, 'cancelled')
const invoiceId = await insertConvertedInvoice(companyId, userId, customerId, quoteId)
await expect(insertOrder(companyId, userId, customerId, quoteId)).rejects.toThrow(
/INVOICE_QUOTE_ALREADY_INVOICED/,
)
await expect(
getPool().query(`UPDATE public.sales_orders SET status = 'draft' WHERE id = $1`, [cancelledOrder]),
).rejects.toThrow(/INVOICE_QUOTE_ALREADY_INVOICED/)
await getPool().query(`UPDATE public.invoices SET status = 'cancelled' WHERE id = $1`, [invoiceId])
await expect(
getPool().query(`UPDATE public.sales_orders SET status = 'draft' WHERE id = $1`, [cancelledOrder]),
).resolves.toBeTruthy()
})
it('leaves status changes that do not make a row live alone (confirm, complete, cancel)', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const orderId = await insertOrder(companyId, userId, customerId, quoteId)
// A converted invoice that slipped in before the order (cancelled now) must
// not block the order's own lifecycle.
await insertConvertedInvoice(companyId, userId, customerId, quoteId, 'cancelled')
await getPool().query(`UPDATE public.sales_orders SET status = 'confirmed' WHERE id = $1`, [orderId])
await getPool().query(`UPDATE public.sales_orders SET status = 'cancelled' WHERE id = $1`, [orderId])
const { rows } = await getPool().query<{ status: string }>(
'SELECT status FROM public.sales_orders WHERE id = $1',
[orderId],
)
expect(rows[0].status).toBe('cancelled')
})
it('does not gate proforma sources: the proforma path serializes on cancelling the proforma', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const proformaId = await insertSource(companyId, userId, customerId, 'proforma')
await insertConvertedInvoice(companyId, userId, customerId, proformaId)
await expect(insertOrder(companyId, userId, customerId, proformaId)).resolves.toBeTruthy()
})
it('runs under a member session: the quote row lock passes RLS and the guard raises its own code', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
// No live invoice: a member may create the order from the quote.
await withUserContext(userId, async (client) => {
await client.query(orderInsertSql(), [randomUUID(), companyId, userId, customerId, 'draft', quoteId])
})
// Live invoice: the refusal is the registry code, not a permission error
// from the FOR UPDATE lock on the quote row.
await insertConvertedInvoice(companyId, userId, customerId, quoteId)
await withUserContext(userId, async (client) => {
await expect(
client.query(orderInsertSql(), [randomUUID(), companyId, userId, customerId, 'draft', quoteId]),
).rejects.toThrow(/INVOICE_QUOTE_ALREADY_INVOICED/)
})
})
it('locks the quote decision in accepted while a live kundorder exists (20260908165100)', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const orderId = await insertOrder(companyId, userId, customerId, quoteId)
await expect(
getPool().query(`UPDATE public.invoices SET quote_status = 'declined' WHERE id = $1`, [quoteId]),
).rejects.toThrow(/INVOICE_QUOTE_ALREADY_ORDERED/)
await expect(
getPool().query(`UPDATE public.invoices SET quote_status = 'open' WHERE id = $1`, [quoteId]),
).rejects.toThrow(/INVOICE_QUOTE_ALREADY_ORDERED/)
// Re-affirming accepted (what the conversions write) is not a decision change.
await getPool().query(`UPDATE public.invoices SET quote_status = 'accepted' WHERE id = $1`, [quoteId])
await getPool().query(`UPDATE public.sales_orders SET status = 'cancelled' WHERE id = $1`, [orderId])
await getPool().query(`UPDATE public.invoices SET quote_status = 'declined' WHERE id = $1`, [quoteId])
const { rows } = await getPool().query<{ quote_status: string }>(
'SELECT quote_status FROM public.invoices WHERE id = $1',
[quoteId],
)
expect(rows[0].quote_status).toBe('declined')
})
it('still guards a non-active company: the row lock runs as definer, not under the caller RLS (20260908165100)', async () => {
// One user, two companies, active company = A. The sales_orders insert
// policy admits every membership, but invoices_update (and so a FOR
// UPDATE under RLS) admits only the active company; without SECURITY
// DEFINER the guard saw no row for B and let the write through.
const { userId, companyId: companyA } = await seedCompany()
const companyB = await insertCompany({ createdBy: userId, name: 'Other AB' })
await insertCompanyMember({ companyId: companyB, userId, role: 'owner' })
await getPool().query(
`INSERT INTO public.user_preferences (user_id, active_company_id) VALUES ($1, $2)
ON CONFLICT (user_id) DO UPDATE SET active_company_id = EXCLUDED.active_company_id`,
[userId, companyA],
)
const customerB = await insertCustomer(companyB, userId)
const quoteB = await insertSource(companyB, userId, customerB, 'quote')
await insertConvertedInvoice(companyB, userId, customerB, quoteB)
await withUserContext(userId, async (client) => {
const { rows } = await client.query<{ active: string }>('SELECT public.current_active_company_id()::text AS active')
expect(rows[0].active).toBe(companyA)
await expect(
client.query(orderInsertSql(), [randomUUID(), companyB, userId, customerB, 'draft', quoteB]),
).rejects.toThrow(/INVOICE_QUOTE_ALREADY_INVOICED/)
})
})
it('refuses a source document from another company instead of inspecting it as definer (20260908165100)', async () => {
const { userId, companyId: companyA } = await seedCompany()
const { userId: otherUser, companyId: companyB } = await seedCompany()
const customerA = await insertCustomer(companyA, userId)
const customerB = await insertCustomer(companyB, otherUser)
const quoteB = await insertSource(companyB, otherUser, customerB, 'quote')
await expect(insertOrder(companyA, userId, customerA, quoteB)).rejects.toThrow(
/SALES_ORDER_SOURCE_COMPANY_MISMATCH/,
)
await expect(insertConvertedInvoice(companyA, userId, customerA, quoteB)).rejects.toThrow(
/INVOICE_CONVERT_SOURCE_COMPANY_MISMATCH/,
)
// A cancelled row points nowhere live and is not inspected either way.
await expect(insertOrder(companyA, userId, customerA, quoteB, 'cancelled')).resolves.toBeTruthy()
})
it('serializes a concurrent order + invoice conversion on the quote row so only the first lands', async () => {
const { userId, companyId } = await seedCompany()
const customerId = await insertCustomer(companyId, userId)
const quoteId = await insertSource(companyId, userId, customerId, 'quote')
const a = await getClient()
const b = await getClient()
try {
await a.query('BEGIN')
await b.query('BEGIN')
// A: the order insert takes the quote row lock and sees no invoice.
await a.query(orderInsertSql(), [randomUUID(), companyId, userId, customerId, 'draft', quoteId])
// B: the invoice insert queues behind A's lock instead of passing its
// own (stale) check.
const bInsert = b.query(convertedInvoiceSql(), [randomUUID(), userId, companyId, customerId, 'draft', quoteId])
const settledEarly = await Promise.race([
bInsert.then(() => 'settled', () => 'settled'),
new Promise<string>((resolve) => setTimeout(() => resolve('blocked'), 300)),
])
expect(settledEarly).toBe('blocked')
await a.query('COMMIT')
await expect(bInsert).rejects.toThrow(/INVOICE_QUOTE_ALREADY_ORDERED/)
await b.query('ROLLBACK')
} finally {
a.release()
b.release()
}
const { rows } = await getPool().query<{ n: string }>(
`SELECT count(*)::text AS n FROM public.sales_orders WHERE source_invoice_id = $1 AND status <> 'cancelled'`,
[quoteId],
)
expect(rows[0].n).toBe('1')
})
})