Files
accounted/components/pending-operations/vocabulary.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

164 lines
9.5 KiB
TypeScript

// Shared vocabulary for pending_operations rendering: labels, warnings and
// rejection categories used by every surface that shows a staged operation
// (/pending, the chat approval card, future flow-run views). Moved here from
// app/(dashboard)/pending/page.tsx so the vocabulary has exactly one owner.
import type { PendingOperationRejectionCategory } from '@/types'
// Short human label (i18n key in the "pending" namespace) for each staged
// operation_type. Keep in sync with OPERATION_RISK_TIERS in
// lib/pending-operations/risk-tiers.ts: every operation an agent can stage
// needs a label here, otherwise the Granskning list falls back to the raw
// snake_case tool name (e.g. "create_supplier_invoice_from_inbox"), which is
// long and pushes the meta row to wrap awkwardly on mobile.
export const OPERATION_LABEL_KEYS: Record<string, string> = {
categorize_transaction: 'type_categorize_transaction',
create_customer: 'type_create_customer',
create_invoice: 'type_create_invoice',
create_transaction: 'type_create_transaction',
create_voucher: 'type_create_voucher',
correct_entry: 'type_correct_entry',
reverse_entry: 'type_reverse_entry',
mark_invoice_paid: 'type_mark_invoice_paid',
send_invoice: 'type_send_invoice',
mark_invoice_sent: 'type_mark_invoice_sent',
match_transaction_invoice: 'type_match_transaction_invoice',
// Master data
create_supplier: 'type_create_supplier',
create_article: 'type_create_article',
update_article: 'type_update_article',
create_account: 'type_create_account',
update_account: 'type_update_account',
create_dimension_value: 'type_create_dimension_value',
// Supplier invoices
create_supplier_invoice_from_inbox: 'type_create_supplier_invoice_from_inbox',
create_self_billed_supplier_invoice: 'type_create_self_billed_supplier_invoice',
approve_supplier_invoice: 'type_approve_supplier_invoice',
credit_supplier_invoice: 'type_credit_supplier_invoice',
// Invoices
credit_invoice: 'type_credit_invoice',
convert_invoice: 'type_convert_invoice',
delete_draft_invoice: 'type_delete_draft_invoice',
// Documents & links
attach_document_to_transaction: 'type_attach_document_to_transaction',
link_document_to_voucher: 'type_link_document_to_voucher',
link_documents_to_vouchers: 'type_link_documents_to_vouchers',
link_invoice_voucher: 'type_link_invoice_voucher',
link_supplier_invoice_voucher: 'type_link_supplier_invoice_voucher',
link_transaction_journal_entry: 'type_link_transaction_journal_entry',
uncategorize_transaction: 'type_uncategorize_transaction',
ignore_transaction: 'type_ignore_transaction',
retag_line_dimensions: 'type_retag_line_dimensions',
set_voucher_note: 'type_set_voucher_note',
// Bulk booking / allocation
match_batch_allocate: 'type_match_batch_allocate',
bulk_book_transactions: 'type_bulk_book_transactions',
bulk_book_inbox_items: 'type_bulk_book_inbox_items',
// Skattekonto row booking
book_skattekonto_row: 'type_book_skattekonto_row',
book_skattekonto_rows: 'type_book_skattekonto_rows',
// Periods, year-end, depreciation
close_period: 'type_close_period',
lock_period: 'type_lock_period',
unlock_period: 'type_unlock_period',
set_opening_balances: 'type_set_opening_balances',
run_year_end: 'type_run_year_end',
run_currency_revaluation: 'type_run_currency_revaluation',
post_annual_depreciation: 'type_post_annual_depreciation',
explain_voucher_gap: 'type_explain_voucher_gap',
// SIE
import_sie: 'type_import_sie',
undo_sie_import: 'type_undo_sie_import',
// Payroll & Skatteverket filings
create_salary_run: 'type_create_salary_run',
book_salary_run: 'type_book_salary_run',
generate_agi: 'type_generate_agi',
update_payslip_line: 'type_update_payslip_line',
set_run_salary: 'type_set_run_salary',
register_absence: 'type_register_absence',
delete_absence: 'type_delete_absence',
create_employee: 'type_create_employee',
update_employee: 'type_update_employee',
set_employee_opening_balances: 'type_set_employee_opening_balances',
vacation_year_close: 'type_vacation_year_close',
submit_vat_declaration: 'type_submit_vat_declaration',
submit_agi: 'type_submit_agi',
}
// Fallback for an operation_type with no entry above (e.g. a newly added op
// not yet given a label): turn "create_supplier_invoice_from_inbox" into
// "Create supplier invoice from inbox" so it never surfaces as raw snake_case.
export function humanizeOperationType(operationType: string): string {
const spaced = operationType.replace(/_/g, ' ')
return spaced.charAt(0).toUpperCase() + spaced.slice(1)
}
export function operationLabel(operationType: string, t: (key: string) => string): string {
const labelKey = OPERATION_LABEL_KEYS[operationType]
return labelKey ? t(labelKey) : humanizeOperationType(operationType)
}
// Full-sentence warning for the single-op confirmation dialog AND the inline
// list-view warning when risk is medium/high. The list-view truncates beyond
// one line; the dialog shows it in full. Order roughly low → high risk so
// reviewers scanning the source see the destructive paths grouped together.
export const singleActionWarnings: Record<string, string> = {
// Low/medium risk: light verifikation work
create_transaction: 'Genom att klicka godkänn så skapar du en transaktion.',
create_customer: 'Genom att klicka godkänn så skapar du en kund.',
create_invoice: 'Genom att klicka godkänn så skapas ett fakturautkast (det skickas inte).',
categorize_transaction: 'Genom att klicka godkänn så kategoriseras transaktionen och en verifikation skapas.',
match_transaction_invoice: 'Genom att klicka godkänn så matchas transaktionen mot fakturan.',
attach_document_to_transaction: 'Genom att klicka godkänn så bifogas dokumentet till transaktionen.',
uncategorize_transaction: 'Genom att klicka godkänn så tas kategoriseringen bort.',
send_invoice: 'Genom att klicka godkänn så skickas fakturan till kunden.',
mark_invoice_paid: 'Genom att klicka godkänn så bokförs en betalning på fakturan.',
mark_invoice_sent: 'Genom att klicka godkänn så märks fakturan som skickad och en verifikation skapas.',
// High risk: period/year-end/voucher edits. These are the ones the reviewer
// really needs the warning for, so we keep them concrete: name the
// irreversibility or compliance consequence, not the generic risk-level.
lock_period: 'Genom att klicka godkänn så låses perioden: inga nya verifikationer kan bokföras tills den låses upp.',
unlock_period: 'Genom att klicka godkänn så låses perioden upp. Använd endast för rättelser; lås igen efter.',
close_period: 'Genom att klicka godkänn så stängs perioden permanent (BFL). Stängningen kan inte ångras.',
run_year_end: 'Genom att klicka godkänn så körs bokslut: resultatkonton nollställs, perioden låses, nästa period skapas.',
set_opening_balances: 'Genom att klicka godkänn så bokförs ingående balans i nästa period.',
run_currency_revaluation: 'Genom att klicka godkänn så bokförs valutaomvärdering (3960/7960).',
create_voucher: 'Genom att klicka godkänn så bokförs verifikationen med ett nytt löpnummer.',
correct_entry: 'Genom att klicka godkänn så stornas originalverifikationen och en rättelse bokförs (BFL 5 kap 5§).',
reverse_entry: 'Genom att klicka godkänn så stornas verifikationen: originalet behålls synligt (BFL 5 kap).',
credit_invoice: 'Genom att klicka godkänn så skapas en kreditfaktura och originalverifikationen stornas.',
delete_draft_invoice: 'Genom att klicka godkänn så tas utkastet bort: onumrerade utkast raderas permanent, numrerade makuleras med bevarat fakturanummer.',
credit_supplier_invoice: 'Genom att klicka godkänn så krediteras leverantörsfakturan och registreringsverifikationen stornas.',
approve_supplier_invoice: 'Genom att klicka godkänn så attesteras leverantörsfakturan och blir betalningsbar.',
convert_invoice: 'Genom att klicka godkänn så konverteras proforman eller offerten till en riktig faktura med F-nummer.',
import_sie: 'Genom att klicka godkänn så importeras SIE-filen: räkenskapsperiod, ingående balans och verifikationer skapas.',
explain_voucher_gap: 'Genom att klicka godkänn så dokumenteras förklaringen för verifikationsluckan (BFNAR 2013:2).',
post_annual_depreciation: 'Genom att klicka godkänn så bokförs planenlig avskrivning: en verifikation per tillgång.',
}
/**
* The consequence sentence the approver consents to. Keyed on the operation
* type; the one type whose outcome depends on its params (convert_invoice
* with target 'order' creates a draft kundorder, no F-number, nothing
* booked) reads the params so the dialog never promises a faktura that the
* approval will not create.
*/
export function singleActionWarning(operationType: string, params?: Record<string, unknown> | null): string {
if (operationType === 'convert_invoice' && params?.target === 'order') {
return 'Genom att klicka godkänn så skapas en kundorder (utkast, OR-nummer) från proforman eller offerten. Ingen faktura skapas och inget bokförs; fakturan skapas senare från kundordern.'
}
return singleActionWarnings[operationType] ?? ''
}
// Structured rejection categories. One canonical list: /pending's reject
// dialog and the chat approval card's reject form render the same options
// and store the same values (surfaced back to the agent via
// gnubok_get_recent_rejections).
export const REJECTION_CATEGORY_LABELS: Record<PendingOperationRejectionCategory, string> = {
wrong_category: 'Fel kategori / konto',
wrong_amount: 'Fel belopp',
duplicate: 'Dubblett',
wrong_period: 'Fel period',
other: 'Annat',
}