c0818bb2d2
* 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>
425 lines
16 KiB
TypeScript
425 lines
16 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import type { PendingOperation } from '@/types'
|
|
import { createQueuedMockSupabase, makeCustomer } from '@/tests/helpers'
|
|
import { eventBus } from '@/lib/events'
|
|
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 {
|
|
id: 'op-invoice-1',
|
|
user_id: 'user-1',
|
|
company_id: 'company-1',
|
|
operation_type: 'update_invoice',
|
|
status: 'pending',
|
|
title: 'Update invoice draft',
|
|
params,
|
|
preview_data: {},
|
|
result_data: null,
|
|
actor_type: 'api_key',
|
|
actor_id: 'key-1',
|
|
actor_label: 'Test key',
|
|
risk_level: 'medium',
|
|
agent_metadata: null,
|
|
rejection_category: null,
|
|
rejection_reason: null,
|
|
created_at: '2026-07-27T00:00:00Z',
|
|
resolved_at: null,
|
|
updated_at: '2026-07-27T00:00:00Z',
|
|
} as PendingOperation
|
|
}
|
|
|
|
function existingDraft(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: INVOICE_ID,
|
|
status: 'draft',
|
|
invoice_number: null,
|
|
journal_entry_id: null,
|
|
is_self_billed: false,
|
|
credited_invoice_id: null,
|
|
customer_id: CUSTOMER_ID,
|
|
document_type: 'invoice',
|
|
invoice_date: '2026-07-01',
|
|
due_date: '2026-07-31',
|
|
delivery_date: null,
|
|
currency: 'SEK',
|
|
your_reference: null,
|
|
our_reference: null,
|
|
notes: null,
|
|
payment_link_url: null,
|
|
payment_link_auto: true,
|
|
ore_rounding: null,
|
|
default_dimensions: {},
|
|
deduction_personnummer_encrypted: null,
|
|
deduction_personnummer_last4: null,
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
const NEW_ITEMS = [
|
|
{ description: 'Konsultation', quantity: 2, unit: 'tim', unit_price: 1000, vat_rate: 25 },
|
|
]
|
|
|
|
const ARTICLE_ID = '44444444-4444-4444-8444-444444444444'
|
|
const ARTICLE_ITEMS = [
|
|
{
|
|
description: 'Konsulttimme',
|
|
quantity: 3,
|
|
unit: 'tim',
|
|
unit_price: 1200,
|
|
vat_rate: 25,
|
|
article_id: ARTICLE_ID,
|
|
revenue_account: '3041',
|
|
},
|
|
]
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
eventBus.clear()
|
|
})
|
|
|
|
describe('commitPendingOperation: update_invoice', () => {
|
|
it('replaces the items, recomputes VAT/totals, and returns qualified ids', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim pending -> committing
|
|
enqueue({ data: existingDraft() }) // invoices: existing draft
|
|
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
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { items: NEW_ITEMS } }),
|
|
)
|
|
|
|
expect(result.status).toBe('committed')
|
|
// Money math: 2 x 1000 = 2000 net, 25% VAT = 500, total 2500.
|
|
expect(result.data).toMatchObject({
|
|
invoice_id: INVOICE_ID,
|
|
subtotal: 2000,
|
|
vat_amount: 500,
|
|
total: 2500,
|
|
item_count: 1,
|
|
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 () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
|
enqueue({ data: existingDraft() }) // invoices: existing draft
|
|
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
|
enqueue({
|
|
// invoice_items: current rows fed back through the builder
|
|
data: [
|
|
{
|
|
line_type: 'product',
|
|
description: 'Befintlig rad',
|
|
quantity: 1,
|
|
unit: 'st',
|
|
unit_price: 100,
|
|
vat_rate: 25,
|
|
article_id: null,
|
|
revenue_account: null,
|
|
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: [] }) // 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
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'Uppdaterad anteckning' } }),
|
|
)
|
|
|
|
expect(result.status).toBe('committed')
|
|
expect(result.data).toMatchObject({
|
|
invoice_id: INVOICE_ID,
|
|
subtotal: 100,
|
|
vat_amount: 25,
|
|
total: 125,
|
|
item_count: 1,
|
|
items_replaced: false,
|
|
})
|
|
})
|
|
|
|
it('re-checks the editable-draft gate at commit time (sent between staging and approval)', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
|
enqueue({ data: existingDraft({ status: 'sent', invoice_number: '2026-0042' }) })
|
|
enqueue({ data: null }) // final status update (auto-reject)
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'x' } }),
|
|
)
|
|
|
|
expect(result.status).toBe('rejected')
|
|
expect(result.auto_rejected).toBe(true)
|
|
expect(result.http_status).toBe(409)
|
|
// Only claim + invoice fetch + status update: the write never ran.
|
|
expect(supabase.from).toHaveBeenCalledTimes(3)
|
|
})
|
|
|
|
it('re-checks the gate for a draft that gained a verifikat', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } })
|
|
enqueue({ data: existingDraft({ journal_entry_id: 'je-1' }) })
|
|
enqueue({ data: null })
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'x' } }),
|
|
)
|
|
|
|
expect(result.status).toBe('rejected')
|
|
expect(result.auto_rejected).toBe(true)
|
|
expect(result.http_status).toBe(409)
|
|
})
|
|
|
|
it('auto-rejects when the invoice no longer exists', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } })
|
|
enqueue({ data: null }) // invoices: gone
|
|
enqueue({ data: null }) // final status update
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { notes: 'x' } }),
|
|
)
|
|
|
|
expect(result.status).toBe('rejected')
|
|
expect(result.auto_rejected).toBe(true)
|
|
expect(result.http_status).toBe(404)
|
|
})
|
|
|
|
it('enforces the VAT rate gate on replaced items', async () => {
|
|
const { supabase, enqueue } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
|
enqueue({ data: existingDraft() }) // invoices
|
|
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
|
enqueue({ data: { vat_registered: true } }) // company_settings
|
|
enqueue({ data: null }) // final status update
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({
|
|
invoice_id: INVOICE_ID,
|
|
// 19% is not a Swedish VAT rate: the builder must refuse it.
|
|
changes: { items: [{ description: 'Rad', quantity: 1, unit: 'st', unit_price: 100, vat_rate: 19 }] },
|
|
}),
|
|
)
|
|
|
|
expect(result.status).toBe('failed')
|
|
expect(result.http_status).toBe(400)
|
|
})
|
|
|
|
it('keeps article_id and revenue_account on replaced items (issue #1642)', async () => {
|
|
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim pending -> committing
|
|
enqueue({ data: existingDraft() }) // invoices: existing draft
|
|
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
|
enqueue({ data: [{ id: ARTICLE_ID }] }) // articles: company-scope gate
|
|
enqueue({ data: { vat_registered: true } }) // company_settings (builder VAT gate)
|
|
enqueue({ data: [{ account_number: '3041' }] }) // chart_of_accounts: override account
|
|
enqueue({ data: [{ id: INVOICE_ID }] }) // invoices update (draft-guarded)
|
|
enqueue({ data: [] }) // invoice_items snapshot (replaceInvoiceItems)
|
|
enqueue({ data: null }) // invoice_items delete
|
|
enqueue({ data: null }) // invoice_items insert
|
|
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: ARTICLE_ITEMS } }),
|
|
)
|
|
|
|
expect(result.status).toBe('committed')
|
|
expect(result.data).toMatchObject({ subtotal: 3600, vat_amount: 900, total: 4500, items_replaced: true })
|
|
expect(supabase.from).toHaveBeenNthCalledWith(4, 'articles')
|
|
// The rewritten line keeps its article linkage and the 3041 override:
|
|
// the quantity fix must not rebook revenue to the VAT-derived default.
|
|
const inserted = findCall('invoice_items', 'insert')?.[0] as Array<Record<string, unknown>>
|
|
expect(inserted).toHaveLength(1)
|
|
expect(inserted[0]).toMatchObject({
|
|
invoice_id: INVOICE_ID,
|
|
article_id: ARTICLE_ID,
|
|
revenue_account: '3041',
|
|
quantity: 3,
|
|
vat_rate: 25,
|
|
})
|
|
})
|
|
|
|
it('rejects a staged article outside the company before writing anything', async () => {
|
|
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
|
|
enqueue({ data: { id: 'op-invoice-1' } }) // claim
|
|
enqueue({ data: existingDraft() }) // invoices
|
|
enqueue({ data: makeCustomer({ id: CUSTOMER_ID }) }) // customers
|
|
enqueue({ data: [] }) // articles: no company-scoped hit
|
|
enqueue({ data: null }) // final status update
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({ invoice_id: INVOICE_ID, changes: { items: ARTICLE_ITEMS } }),
|
|
)
|
|
|
|
expect(result.status).toBe('failed')
|
|
expect(result.http_status).toBe(400)
|
|
expect(result.error).toMatch(/finns inte i företaget/)
|
|
expect(findCall('invoices', 'update')).toBeUndefined()
|
|
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' } })
|
|
enqueue({ data: null }) // final status update
|
|
|
|
const result = await commitPendingOperation(
|
|
supabase as never,
|
|
'user-1',
|
|
'company-1',
|
|
makePendingOp({
|
|
invoice_id: INVOICE_ID,
|
|
changes: { status: 'paid', notes: 'x' },
|
|
}),
|
|
)
|
|
|
|
expect(result.status).toBe('failed')
|
|
expect(result.http_status).toBe(400)
|
|
expect(result.error).toMatch(/unrecognized key|invalid/i)
|
|
expect(supabase.from).toHaveBeenCalledTimes(2)
|
|
})
|
|
})
|