feat(sales-orders): kundorder with partial delivery and partial invoicing (#2166)
* 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>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
c40e63e3f7
commit
c0818bb2d2
@@ -0,0 +1,396 @@
|
||||
/**
|
||||
* Executor tests for the four staged kundorder (sales order) operations.
|
||||
* The executors are private to commit.ts and reached through
|
||||
* commitPendingOperation (same pattern as ignore-transaction-executor.test.ts).
|
||||
*
|
||||
* The lib/sales-orders services are mocked: the executors own only the
|
||||
* commit-boundary re-validation, the service call and the mapping of a
|
||||
* ServiceFailure onto the CommitResult contract. Totals, VAT and the state
|
||||
* machine are the services' business and are tested there.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { PendingOperation, SalesOrder } from '@/types'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sales-orders/write', () => ({
|
||||
createSalesOrder: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/transitions', () => ({
|
||||
transitionSalesOrder: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/register-delivery', () => ({
|
||||
registerSalesOrderDelivery: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/sales-orders/create-invoice-from-order', () => ({
|
||||
createInvoiceFromSalesOrder: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createSalesOrder } from '@/lib/sales-orders/write'
|
||||
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
|
||||
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
|
||||
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
const ORDER_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
const CUSTOMER_ID = '00000000-0000-4000-8000-0000000000bb'
|
||||
const ITEM_ID = '00000000-0000-4000-8000-0000000000cc'
|
||||
const INVOICE_ID = '00000000-0000-4000-8000-0000000000dd'
|
||||
|
||||
function makeOrder(overrides: Partial<SalesOrder> = {}): SalesOrder {
|
||||
return {
|
||||
id: ORDER_ID,
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
customer_id: CUSTOMER_ID,
|
||||
order_number: 'OR-7',
|
||||
status: 'draft',
|
||||
source_invoice_id: null,
|
||||
order_date: '2026-09-01',
|
||||
requested_delivery_date: null,
|
||||
last_delivery_date: null,
|
||||
currency: 'SEK',
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
your_reference: null,
|
||||
our_reference: null,
|
||||
notes: null,
|
||||
default_dimensions: {},
|
||||
confirmed_at: null,
|
||||
completed_at: null,
|
||||
cancelled_at: null,
|
||||
created_at: '2026-09-01T00:00:00Z',
|
||||
updated_at: '2026-09-01T00:00:00Z',
|
||||
items: [],
|
||||
delivery_progress: 'none',
|
||||
invoicing_progress: 'none',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'create_sales_order',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: {},
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'low',
|
||||
created_at: '2026-09-01T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-09-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
const CREATE_PARAMS = {
|
||||
customer_id: CUSTOMER_ID,
|
||||
order_date: '2026-09-01',
|
||||
currency: 'SEK',
|
||||
items: [{ description: 'Konsulttimmar', quantity: 10, unit: 'tim', unit_price: 100 }],
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: create_sales_order', () => {
|
||||
it('happy path: validates the staged params, calls the service and returns the order ids', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: true, order: makeOrder() })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, order_number: 'OR-7', status: 'draft', total: 1250 })
|
||||
expect(createSalesOrder).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
input: expect.objectContaining({ customer_id: CUSTOMER_ID, items: expect.any(Array) }),
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a coded service failure onto the structured error (CUSTOMER_NOT_FOUND -> 404 auto-reject)', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, code: 'CUSTOMER_NOT_FOUND', details: { customerId: CUSTOMER_ID } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // reject write
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(404)
|
||||
expect(result.code).toBe('CUSTOMER_NOT_FOUND')
|
||||
expect(result.data).toEqual({ customerId: CUSTOMER_ID })
|
||||
})
|
||||
|
||||
it('rejects tampered params at the commit boundary before the service runs', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // reject write
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: { ...CREATE_PARAMS, customer_id: 'not-a-uuid' } }),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(result.error).toMatch(/customer_id/)
|
||||
expect(createSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a raw DB failure as a 500 with the driver message', async () => {
|
||||
vi.mocked(createSalesOrder).mockResolvedValue({ ok: false, dbError: { message: 'connection reset' } })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_sales_order', params: CREATE_PARAMS }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(500)
|
||||
expect(result.error).toBe('connection reset')
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: transition_sales_order', () => {
|
||||
it('happy path: confirms through the service', async () => {
|
||||
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: true, order: makeOrder({ status: 'confirmed' }) })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'confirm' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, status: 'confirmed', action: 'confirm' })
|
||||
expect(transitionSalesOrder).toHaveBeenCalledWith(supabase, { companyId: 'company-1', orderId: ORDER_ID, action: 'confirm' })
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_HAS_INVOICES onto a 409 auto-reject', async () => {
|
||||
vi.mocked(transitionSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_HAS_INVOICES' })
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'cancel' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('SALES_ORDER_HAS_INVOICES')
|
||||
expect(result.error).toMatch(/fakturor/i)
|
||||
})
|
||||
|
||||
it('rejects an action outside the enum before the service runs', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'transition_sales_order', params: { sales_order_id: ORDER_ID, action: 'complete' } }),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.error).toMatch(/action/)
|
||||
expect(transitionSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: register_sales_order_delivery', () => {
|
||||
const params = {
|
||||
sales_order_id: ORDER_ID,
|
||||
delivery_date: '2026-09-02',
|
||||
lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }],
|
||||
}
|
||||
|
||||
it('happy path: passes the cumulative quantities to the service', async () => {
|
||||
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
|
||||
ok: true,
|
||||
order: makeOrder({ status: 'confirmed', last_delivery_date: '2026-09-02', delivery_progress: 'partial' }),
|
||||
})
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ sales_order_id: ORDER_ID, last_delivery_date: '2026-09-02', delivery_progress: 'partial' })
|
||||
expect(registerSalesOrderDelivery).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
orderId: ORDER_ID,
|
||||
input: { delivery_date: '2026-09-02', lines: [{ sales_order_item_id: ITEM_ID, delivered_qty: 4 }] },
|
||||
})
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_OVER_DELIVERED (400) onto a failed op with the line details', async () => {
|
||||
vi.mocked(registerSalesOrderDelivery).mockResolvedValue({
|
||||
ok: false,
|
||||
code: 'SALES_ORDER_OVER_DELIVERED',
|
||||
details: { sales_order_item_id: ITEM_ID, quantity: 3, delivered_qty: 4 },
|
||||
})
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'register_sales_order_delivery', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(400)
|
||||
expect(result.code).toBe('SALES_ORDER_OVER_DELIVERED')
|
||||
expect(result.data).toMatchObject({ sales_order_item_id: ITEM_ID, quantity: 3 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: create_invoice_from_sales_order', () => {
|
||||
const params = { sales_order_id: ORDER_ID, mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' }
|
||||
const invoice = { id: INVOICE_ID, invoice_number: null, status: 'draft', total: 1250, currency: 'SEK' }
|
||||
|
||||
it('happy path: creates the draft through the service and emits invoice.created', async () => {
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
|
||||
ok: true,
|
||||
invoice: invoice as never,
|
||||
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
|
||||
})
|
||||
const handler = vi.fn()
|
||||
eventBus.on('invoice.created', handler)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({
|
||||
invoice_id: INVOICE_ID,
|
||||
invoice_number: null,
|
||||
sales_order_id: ORDER_ID,
|
||||
order_status: 'completed',
|
||||
invoicing_progress: 'full',
|
||||
})
|
||||
expect(createInvoiceFromSalesOrder).toHaveBeenCalledWith(supabase, {
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
orderId: ORDER_ID,
|
||||
input: { mode: 'remaining', invoice_date: '2026-09-02', due_date: '2026-10-02' },
|
||||
})
|
||||
expect(handler).toHaveBeenCalledTimes(1)
|
||||
// Handlers receive the payload, not the envelope.
|
||||
expect(handler.mock.calls[0][0]).toMatchObject({
|
||||
invoice: expect.objectContaining({ id: INVOICE_ID }),
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('still commits when the invoice.created emit rejects (the draft already exists)', async () => {
|
||||
// eventBus.emit settles handler failures itself, so the only way the emit
|
||||
// can reject is the bus throwing; the executor must treat that as a
|
||||
// post-commit notification failure, not as a failed operation.
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({
|
||||
ok: true,
|
||||
invoice: invoice as never,
|
||||
order: makeOrder({ status: 'completed', invoicing_progress: 'full' }),
|
||||
})
|
||||
const emitSpy = vi.spyOn(eventBus, 'emit').mockRejectedValueOnce(new Error('bus down'))
|
||||
try {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { ...invoice, items: [], customer: null } }) // complete-invoice select for the event
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ invoice_id: INVOICE_ID, sales_order_id: ORDER_ID })
|
||||
expect(emitSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'invoice.created' }),
|
||||
)
|
||||
} finally {
|
||||
emitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('maps SALES_ORDER_NOTHING_TO_INVOICE onto a 409 auto-reject and emits nothing', async () => {
|
||||
vi.mocked(createInvoiceFromSalesOrder).mockResolvedValue({ ok: false, code: 'SALES_ORDER_NOTHING_TO_INVOICE' })
|
||||
const handler = vi.fn()
|
||||
eventBus.on('invoice.created', handler)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ operation_type: 'create_invoice_from_sales_order', params }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('SALES_ORDER_NOTHING_TO_INVOICE')
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a non-positive explicit pick at the commit boundary', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } })
|
||||
enqueue({ data: null })
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({
|
||||
operation_type: 'create_invoice_from_sales_order',
|
||||
params: { sales_order_id: ORDER_ID, lines: [{ sales_order_item_id: ITEM_ID, quantity: 0 }] },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.error).toMatch(/lines\.0\.quantity/)
|
||||
expect(createInvoiceFromSalesOrder).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { commitPendingOperation } from '../commit'
|
||||
|
||||
const INVOICE_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const CUSTOMER_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const SALES_ORDER_ITEM_ID = 'd1000000-0000-4000-8000-000000000001'
|
||||
|
||||
function makePendingOp(params: Record<string, unknown>): PendingOperation {
|
||||
return {
|
||||
@@ -88,6 +89,7 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings (builder VAT gate)
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (draft-guarded)
|
||||
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no prior rows)
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // pending_operations final status update
|
||||
@@ -110,8 +112,10 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
items_replaced: true,
|
||||
})
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(2, 'invoices')
|
||||
// snapshot, delete, insert
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(6, 'invoice_items')
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(7, 'invoice_items')
|
||||
expect(supabase.from).toHaveBeenNthCalledWith(8, 'invoice_items')
|
||||
})
|
||||
|
||||
it('keeps the existing lines on a header-only edit (no full replace staged)', async () => {
|
||||
@@ -146,6 +150,7 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
})
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
|
||||
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems, no order links)
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // final status update
|
||||
@@ -306,6 +311,96 @@ describe('commitPendingOperation: update_invoice', () => {
|
||||
expect(findCall('invoice_items', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('auto-rejects with INVOICE_UPDATE_DROPS_ORDER_LINK when replaced lines drop a kundorder link', async () => {
|
||||
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
||||
enqueue({ data: existingDraft() }) // invoices: existing draft (created from an order)
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (header)
|
||||
enqueue({
|
||||
// invoice_items snapshot (replaceInvoiceItems): the stored row is linked
|
||||
// to an order line; the staged items carry no sales_order_item_id.
|
||||
data: [{ id: 'item-old-1', invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID, description: 'Orderrad' }],
|
||||
})
|
||||
enqueue({ data: null }) // pending_operations final status update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp({ invoice_id: INVOICE_ID, changes: { items: NEW_ITEMS } }),
|
||||
)
|
||||
|
||||
// 409 from the executor: auto-rejected with the structured code so the
|
||||
// approver sees WHY, same as the cookie and v1 PATCH routes.
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.auto_rejected).toBe(true)
|
||||
expect(result.http_status).toBe(409)
|
||||
expect(result.code).toBe('INVOICE_UPDATE_DROPS_ORDER_LINK')
|
||||
expect(result.error).toMatch(/kundorder/)
|
||||
// The guard fires before the delete: the lines are untouched.
|
||||
expect(findCall('invoice_items', 'delete')).toBeUndefined()
|
||||
expect(findCall('invoice_items', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the kundorder link on a header-only edit (re-fetch carries sales_order_item_id)', async () => {
|
||||
const { supabase, enqueue, findCall, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
||||
enqueue({ data: existingDraft() }) // invoices
|
||||
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
||||
enqueue({
|
||||
// invoice_items re-fetch for the header-only edit
|
||||
data: [
|
||||
{
|
||||
line_type: 'product',
|
||||
description: 'Orderrad',
|
||||
quantity: 4,
|
||||
unit: 'h',
|
||||
unit_price: 100,
|
||||
discount_percent: null,
|
||||
vat_rate: 25,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
sales_order_item_id: SALES_ORDER_ITEM_ID,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
housing_designation: null,
|
||||
apartment_number: null,
|
||||
brf_org_number: null,
|
||||
accrual_period_start: null,
|
||||
accrual_period_end: null,
|
||||
accrual_balance_account: null,
|
||||
dimensions: {},
|
||||
},
|
||||
],
|
||||
})
|
||||
enqueue({ data: { vat_registered: true } }) // company_settings
|
||||
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update
|
||||
enqueue({ data: [{ id: 'item-old-1', sales_order_item_id: SALES_ORDER_ITEM_ID }] }) // snapshot
|
||||
enqueue({ data: null }) // invoice_items delete
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: null }) // final status update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'Ny anteckning' } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ items_replaced: false, item_count: 1 })
|
||||
// The narrow re-fetch must include the link column, or the guard would
|
||||
// refuse every header-only edit of an order-created draft.
|
||||
const refetchColumns = findCalls('invoice_items', 'select')[0][0] as string
|
||||
expect(refetchColumns.split(',').map((c) => c.trim())).toContain('sales_order_item_id')
|
||||
const inserted = findCall('invoice_items', 'insert')![0] as Array<Record<string, unknown>>
|
||||
expect(inserted).toHaveLength(1)
|
||||
expect(inserted[0]).toMatchObject({ invoice_id: INVOICE_ID, sales_order_item_id: SALES_ORDER_ITEM_ID })
|
||||
})
|
||||
|
||||
it('rejects tampered staged params before reading the invoice', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-invoice-1' } })
|
||||
|
||||
@@ -156,6 +156,17 @@ import { defaultRateForVatTreatment } from '@/lib/vat/account-vat-treatment'
|
||||
import { SetVoucherNoteParamsSchema } from '@/lib/pending-operations/schemas/voucher-note'
|
||||
import { IgnoreTransactionParamsSchema } from '@/lib/pending-operations/schemas/ignore-transaction'
|
||||
import { setTransactionIgnored } from '@/lib/transactions/ignore'
|
||||
import {
|
||||
CreateInvoiceFromSalesOrderParamsSchema,
|
||||
CreateSalesOrderParamsSchema,
|
||||
RegisterSalesOrderDeliveryParamsSchema,
|
||||
TransitionSalesOrderParamsSchema,
|
||||
} from '@/lib/pending-operations/schemas/sales-order'
|
||||
import { createSalesOrder } from '@/lib/sales-orders/write'
|
||||
import { transitionSalesOrder } from '@/lib/sales-orders/transitions'
|
||||
import { registerSalesOrderDelivery } from '@/lib/sales-orders/register-delivery'
|
||||
import { createInvoiceFromSalesOrder } from '@/lib/sales-orders/create-invoice-from-order'
|
||||
import type { ServiceFailure } from '@/lib/sales-orders/result'
|
||||
import { UpdateCompanySettingsParamsSchema } from '@/lib/pending-operations/schemas/company-settings'
|
||||
import { UpdateCustomerParamsSchema } from '@/lib/pending-operations/schemas/customer'
|
||||
import {
|
||||
@@ -1282,6 +1293,192 @@ async function commitIgnoreTransaction(
|
||||
}
|
||||
}
|
||||
|
||||
// ── Kundorder (sales orders) ────────────────────────────────────────
|
||||
//
|
||||
// The four executors below never touch totals, VAT or the order state
|
||||
// machine themselves: they re-validate the staged params (ASVS V4.5) and
|
||||
// hand them to the lib/sales-orders service the cookie routes use, so the
|
||||
// MCP door and the web door produce identical rows and identical refusals.
|
||||
|
||||
/** Zod failure on a staged row -> 400 with the first issue named. */
|
||||
function invalidStagedParams(err: unknown): ExecutorResult {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a lib/sales-orders ServiceFailure onto the ExecutorResult contract.
|
||||
* A coded failure carries the structured-error httpStatus (404/409 auto-
|
||||
* reject the op, 400 fails it) and its Swedish message, with the service's
|
||||
* details persisted so the approver sees WHICH line was refused; a raw DB
|
||||
* failure is a 500 with the driver message.
|
||||
*/
|
||||
function salesOrderFailure(failure: ServiceFailure): ExecutorResult {
|
||||
if ('code' in failure) {
|
||||
const entry = getErrorEntry(failure.code)
|
||||
return {
|
||||
error: entry?.message_sv ?? failure.code,
|
||||
errorCode: failure.code,
|
||||
status: entry?.httpStatus ?? 400,
|
||||
...(failure.details ? { data: failure.details } : {}),
|
||||
}
|
||||
}
|
||||
const dbMessage =
|
||||
typeof failure.dbError === 'object' && failure.dbError !== null && 'message' in failure.dbError
|
||||
? String((failure.dbError as { message: unknown }).message)
|
||||
: null
|
||||
return { error: dbMessage || getErrorEntry('SALES_ORDER_CREATE_FAILED')?.message_sv || 'Kundordern kunde inte sparas.', status: 500 }
|
||||
}
|
||||
|
||||
async function commitCreateSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = CreateSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
const result = await createSalesOrder(supabase, { companyId, userId, input: validated })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
total: order.total,
|
||||
currency: order.currency,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitTransitionSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = TransitionSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
// The service re-reads the order and refuses a transition the current
|
||||
// status does not allow (compare-and-set), so an order that moved between
|
||||
// staging and approval lands as SALES_ORDER_INVALID_STATE, never as a
|
||||
// silent overwrite.
|
||||
const result = await transitionSalesOrder(supabase, {
|
||||
companyId,
|
||||
orderId: validated.sales_order_id,
|
||||
action: validated.action,
|
||||
})
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
action: validated.action,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitRegisterSalesOrderDelivery(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = RegisterSalesOrderDeliveryParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
const { sales_order_id: orderId, ...input } = validated
|
||||
const result = await registerSalesOrderDelivery(supabase, { companyId, orderId, input })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { order } = result
|
||||
return {
|
||||
data: {
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
status: order.status,
|
||||
last_delivery_date: order.last_delivery_date,
|
||||
delivery_progress: order.delivery_progress ?? null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCreateInvoiceFromSalesOrder(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = CreateInvoiceFromSalesOrderParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
return invalidStagedParams(err)
|
||||
}
|
||||
|
||||
// The service re-reads the order, re-picks the lines against the CURRENT
|
||||
// invoiced quantities and builds the draft through buildInvoiceWriteData,
|
||||
// so a line invoiced elsewhere between staging and approval is refused
|
||||
// (SALES_ORDER_OVER_INVOICED / NOTHING_TO_INVOICE) instead of double-billed.
|
||||
const { sales_order_id: orderId, ...input } = validated
|
||||
const result = await createInvoiceFromSalesOrder(supabase, { companyId, userId, orderId, input })
|
||||
if (!result.ok) return salesOrderFailure(result)
|
||||
|
||||
const { invoice, order } = result
|
||||
|
||||
// Same event the direct create_invoice executor emits, so extension
|
||||
// handlers (webhooks, digests) see order-born drafts too.
|
||||
const { data: completeInvoice } = await supabase
|
||||
.from('invoices')
|
||||
.select('*, customer:customers(*), items:invoice_items(*)')
|
||||
.eq('id', invoice.id)
|
||||
.single()
|
||||
// Post-commit notification only: the draft already exists, so an event
|
||||
// failure must not reject an operation whose write succeeded.
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
payload: { invoice: (completeInvoice ?? invoice) as Invoice, userId, companyId },
|
||||
})
|
||||
} catch {
|
||||
// Non-critical
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
invoice_id: invoice.id,
|
||||
// Unnumbered draft: the F-series number is assigned on send.
|
||||
invoice_number: invoice.invoice_number ?? null,
|
||||
sales_order_id: order.id,
|
||||
order_number: order.order_number,
|
||||
order_status: order.status,
|
||||
invoicing_progress: order.invoicing_progress ?? null,
|
||||
total: invoice.total,
|
||||
currency: invoice.currency,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCreateSupplier(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -2061,7 +2258,7 @@ async function commitUpdateInvoice(
|
||||
const { data: itemRows, error: itemsFetchError } = await supabase
|
||||
.from('invoice_items')
|
||||
.select(
|
||||
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
|
||||
'line_type, description, quantity, unit, unit_price, discount_percent, vat_rate, article_id, revenue_account, sales_order_item_id, deduction_type, labor_hours, work_type, housing_designation, apartment_number, brf_org_number, accrual_period_start, accrual_period_end, accrual_balance_account, dimensions',
|
||||
)
|
||||
.eq('invoice_id', invoiceId)
|
||||
.order('sort_order', { ascending: true })
|
||||
@@ -2150,6 +2347,9 @@ async function commitUpdateInvoice(
|
||||
|
||||
const replaced = await replaceInvoiceItems(supabase, invoiceId, build.items)
|
||||
if (!replaced.ok) {
|
||||
if (replaced.stage === 'guard') {
|
||||
return { error: replaced.messageSv, errorCode: replaced.code, status: 409 }
|
||||
}
|
||||
return {
|
||||
error: `Fakturaraderna kunde inte skrivas om (${replaced.stage}): ${replaced.error.message}`,
|
||||
status: 500,
|
||||
@@ -6759,6 +6959,18 @@ async function commitPendingOperationInner(
|
||||
case 'ignore_transaction':
|
||||
result = await commitIgnoreTransaction(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_sales_order':
|
||||
result = await commitCreateSalesOrder(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'transition_sales_order':
|
||||
result = await commitTransitionSalesOrder(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'register_sales_order_delivery':
|
||||
result = await commitRegisterSalesOrderDelivery(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_invoice_from_sales_order':
|
||||
result = await commitCreateInvoiceFromSalesOrder(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_dimension_value':
|
||||
result = await commitCreateDimensionValue(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -51,6 +51,15 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// and the executor's isTransactionBooked() refusal keep it off booked rows,
|
||||
// so the op cannot hide a booking even if tampered with (issue #1661).
|
||||
ignore_transaction: 'low',
|
||||
// Kundorder (sales orders) never book: an order is the non-ledger document
|
||||
// between agreement and invoice. Creating one, moving it through its
|
||||
// header state machine (confirm / cancel / reopen) and registering
|
||||
// delivered quantities write only sales_orders / sales_order_items, no
|
||||
// verifikat and no external side-effect, and all three are re-editable
|
||||
// (cancel is refused while invoices exist, reopen undoes it).
|
||||
create_sales_order: 'low',
|
||||
transition_sales_order: 'low',
|
||||
register_sales_order_delivery: 'low',
|
||||
|
||||
// ── Medium: reversible booking ─────────────────────────────────────
|
||||
categorize_transaction: 'medium',
|
||||
@@ -70,6 +79,10 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// create_invoice: the target has no verifikat yet (isEditableInvoiceDraft
|
||||
// is re-checked at commit), so the edit is fully reversible by editing again.
|
||||
update_invoice: 'medium',
|
||||
// Creates an unnumbered DRAFT kundfaktura from a confirmed order through
|
||||
// the same builder as create_invoice (nothing is booked or sent at commit;
|
||||
// the draft can be deleted). Same tier as create_invoice.
|
||||
create_invoice_from_sales_order: 'medium',
|
||||
// Recurring invoice schedules: the commit only creates/edits the monthly
|
||||
// template (nothing is booked or sent at commit time), and the schedule is
|
||||
// pausable/deletable before the next cron run. Not 'low' because an
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
CreateInvoiceFromSalesOrderSchema,
|
||||
CreateSalesOrderSchema,
|
||||
RegisterSalesOrderDeliverySchema,
|
||||
SalesOrderTransitionSchema,
|
||||
} from '@/lib/api/schemas'
|
||||
|
||||
// Commit-boundary re-validation for the staged kundorder (sales order)
|
||||
// operations. A staged pending_operations row is re-parsed here before the
|
||||
// lib/sales-orders service runs so a tampered row cannot inject unexpected
|
||||
// fields or malformed data (defense in depth, ASVS V4.5): mirrors
|
||||
// lib/pending-operations/schemas/article.ts.
|
||||
//
|
||||
// The shapes are the same Zod schemas the cookie routes under
|
||||
// app/api/sales-orders validate with, so the MCP door and the web door
|
||||
// accept exactly the same payloads. Every executor also needs the target
|
||||
// order, which the route carries in the URL and the staged params carry as
|
||||
// sales_order_id.
|
||||
|
||||
const salesOrderId = z.string().uuid()
|
||||
|
||||
export const CreateSalesOrderParamsSchema = CreateSalesOrderSchema
|
||||
|
||||
export const TransitionSalesOrderParamsSchema = SalesOrderTransitionSchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
|
||||
export const RegisterSalesOrderDeliveryParamsSchema = RegisterSalesOrderDeliverySchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
|
||||
export const CreateInvoiceFromSalesOrderParamsSchema = CreateInvoiceFromSalesOrderSchema.extend({
|
||||
sales_order_id: salesOrderId,
|
||||
})
|
||||
Reference in New Issue
Block a user