* 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>
212 lines
8.8 KiB
TypeScript
212 lines
8.8 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { UpdateInvoiceSchema } from '@/lib/api/schemas'
|
|
import { buildInvoiceWriteData } from '@/lib/invoices/build-invoice-write'
|
|
import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
|
|
import { deleteDraftInvoice } from '@/lib/invoices/delete-draft-invoice'
|
|
import { replaceInvoiceItems } from '@/lib/invoices/replace-invoice-items'
|
|
import type { InvoiceDocumentType } from '@/types'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
ensureInitialized() // Module-level: wires the audit-log handler for invoice.draft_deleted.
|
|
|
|
/**
|
|
* DELETE /api/invoices/[id]
|
|
*
|
|
* Removes a draft invoice. Behaviour depends on whether a number was issued:
|
|
*
|
|
* - Unnumbered draft (saved via "Spara som utkast", never finalized): hard
|
|
* deleted. No F-series number was consumed, so there is no gap to document
|
|
* (ML 17 kap 24§). invoice_items cascade via the FK.
|
|
* - Numbered draft (created directly, or finalized via "Granska och skapa"):
|
|
* makulerad: the row and its number are retained and status flips to
|
|
* 'cancelled', keeping the F-series gap-free per ML 17 kap 24§ / BFNAR 2013:2.
|
|
*
|
|
* Only drafts may be removed either way. Sent / paid invoices are immutable per
|
|
* BFL and must be reversed via a credit note instead.
|
|
*
|
|
* The fetch / guard / delete-or-cancel logic lives in
|
|
* lib/invoices/delete-draft-invoice.ts, shared with the v1 API-key route and
|
|
* the MCP delete_draft_invoice executor. This handler only maps the result to
|
|
* the cookie-session response envelope.
|
|
*/
|
|
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
|
|
'invoice.delete',
|
|
async (_request, { user, supabase, companyId, log, requestId }, { params }) => {
|
|
const { id } = await params
|
|
const opLog = log.child({ invoiceId: id })
|
|
|
|
const result = await deleteDraftInvoice({
|
|
supabase,
|
|
companyId,
|
|
userId: user.id,
|
|
invoiceId: id,
|
|
log: opLog,
|
|
})
|
|
|
|
if (!result.ok) {
|
|
return errorResponseFromCode(result.code, opLog, { requestId })
|
|
}
|
|
|
|
if (result.outcome === 'deleted') {
|
|
return NextResponse.json({ data: { deleted: true } })
|
|
}
|
|
|
|
return NextResponse.json({ data: { cancelled: true, invoice_number: result.invoiceNumber } })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|
|
|
|
/**
|
|
* PATCH /api/invoices/[id]
|
|
*
|
|
* Edit a DRAFT invoice (or proforma / delivery note) in place: header fields
|
|
* AND line items. Only drafts are editable: a journal entry (verifikat) is
|
|
* created when an invoice is sent (mark-sent / send) or, for kontantmetoden, at
|
|
* payment, so a draft has no committed entry and BFL immutability (guard rail #1)
|
|
* does not yet apply. Sent / paid / cancelled / credited invoices are immutable
|
|
* and must be reversed via a credit note instead.
|
|
*
|
|
* The invoice's number and status are preserved: editing never (re)allocates a
|
|
* number nor changes lifecycle state, and never emits invoice.created (numbered
|
|
* drafts already emitted it at create; unnumbered ones emit on finalize). The
|
|
* validation + computation is shared with POST /api/invoices via
|
|
* buildInvoiceWriteData so VAT rules, ROT/RUT, accruals and totals stay identical.
|
|
*/
|
|
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
|
'invoice.update',
|
|
async (request, { supabase, companyId, log: ctxLog, requestId }, { params }) => {
|
|
const { id } = await params
|
|
|
|
const validation = await validateBody(request, UpdateInvoiceSchema, {
|
|
log: ctxLog,
|
|
operation: 'invoice.update',
|
|
})
|
|
if (!validation.success) return validation.response
|
|
const input = validation.data
|
|
const documentType: InvoiceDocumentType = input.document_type || 'invoice'
|
|
|
|
// Fetch the target. Only drafts (not sent, no committed verifikat, not a
|
|
// received self-billing document) may be edited.
|
|
const { data: existing, error: fetchError } = await supabase
|
|
.from('invoices')
|
|
.select('id, status, invoice_number, journal_entry_id, is_self_billed, credited_invoice_id, deduction_personnummer_encrypted, deduction_personnummer_last4')
|
|
.eq('id', id)
|
|
.eq('company_id', companyId!)
|
|
.single()
|
|
|
|
if (fetchError || !existing) {
|
|
return errorResponseFromCode('INVOICE_NOT_FOUND', ctxLog, { requestId })
|
|
}
|
|
|
|
// journal_entry_id is belt-and-suspenders: a draft shouldn't carry one,
|
|
// but if some flow ever booked it, refuse the edit (the entry is immutable).
|
|
// Shared predicate (lib/invoices/is-editable-draft): the single source of
|
|
// truth the detail and edit pages also gate on, so the rule can't drift.
|
|
if (!isEditableInvoiceDraft(existing)) {
|
|
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
|
|
}
|
|
|
|
// Resolve the (possibly changed) customer.
|
|
const { data: customer, error: customerError } = await supabase
|
|
.from('customers')
|
|
.select('*')
|
|
.eq('id', input.customer_id)
|
|
.eq('company_id', companyId!)
|
|
.single()
|
|
|
|
if (customerError || !customer) {
|
|
return errorResponseFromCode('INVOICE_CUSTOMER_NOT_FOUND', ctxLog, {
|
|
requestId,
|
|
details: { customerId: input.customer_id },
|
|
})
|
|
}
|
|
|
|
const build = await buildInvoiceWriteData({
|
|
supabase,
|
|
companyId: companyId!,
|
|
customer,
|
|
documentType,
|
|
input,
|
|
// The stored personnummer exists only as ciphertext (client sees _last4
|
|
// at most), so an edit that leaves the field empty keeps it rather than
|
|
// failing ROT/RUT validation (issue #1175).
|
|
existingPersonnummer: existing.deduction_personnummer_encrypted
|
|
? {
|
|
encrypted: existing.deduction_personnummer_encrypted,
|
|
last4: existing.deduction_personnummer_last4 ?? null,
|
|
}
|
|
: null,
|
|
})
|
|
if (!build.ok) {
|
|
if ('dbError' in build) {
|
|
ctxLog.error('invoice write build failed on a DB lookup', build.dbError as Error)
|
|
return errorResponse(build.dbError, ctxLog, { requestId })
|
|
}
|
|
return errorResponseFromCode(build.code, ctxLog, { requestId, details: build.details })
|
|
}
|
|
|
|
// Update the draft row. invoice_number + status are intentionally NOT in
|
|
// build.invoiceFields, so they are preserved. The .eq('status','draft')
|
|
// guard turns a concurrent send/finalize into a 0-row update (race), rather
|
|
// than silently rewriting a now-issued invoice.
|
|
// Öresavrundning is display-only and optional in the update body. Persist
|
|
// it when the editor sent a value; otherwise strip it so a partial update
|
|
// can't reset a draft's stored flag (build defaults an absent flag to null).
|
|
const updateFields =
|
|
input.ore_rounding === undefined
|
|
? (() => {
|
|
const { ore_rounding: _oreRounding, ...rest } = build.invoiceFields
|
|
return rest
|
|
})()
|
|
: build.invoiceFields
|
|
const { data: updated, error: updateError } = await supabase
|
|
.from('invoices')
|
|
.update({ ...updateFields, updated_at: new Date().toISOString() })
|
|
.eq('id', id)
|
|
.eq('company_id', companyId!)
|
|
.eq('status', 'draft')
|
|
.select('id')
|
|
|
|
if (updateError) {
|
|
ctxLog.error('invoice update failed', updateError, { invoiceId: id })
|
|
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', ctxLog, {
|
|
requestId,
|
|
details: { pgCode: updateError.code, pgMessage: getUserErrorMessage(updateError) },
|
|
})
|
|
}
|
|
if (!updated || updated.length === 0) {
|
|
return errorResponseFromCode('INVOICE_UPDATE_NOT_DRAFT', ctxLog, { requestId })
|
|
}
|
|
|
|
// Replace line items wholesale (shared helper: the v1 REST route and the
|
|
// update_invoice commit executor use the same delete + reinsert). A draft
|
|
// has no journal entry or linked docs, so full replace is safe and lets
|
|
// the user add / remove / reorder rows freely. invoice_items cascade
|
|
// nothing else.
|
|
const replaced = await replaceInvoiceItems(supabase, id, build.items)
|
|
if (!replaced.ok) {
|
|
if (replaced.stage === 'guard') {
|
|
return errorResponseFromCode(replaced.code, ctxLog, { requestId })
|
|
}
|
|
ctxLog.error(`invoice items ${replaced.stage} failed on update`, replaced.error, { invoiceId: id })
|
|
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', ctxLog, {
|
|
requestId,
|
|
details: { pgCode: replaced.error.code, pgMessage: getUserErrorMessage(replaced.error) },
|
|
})
|
|
}
|
|
|
|
const { data: completeInvoice } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.eq('id', id)
|
|
.single()
|
|
|
|
return NextResponse.json({ data: completeInvoice })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|