diff --git a/docs/migrations.md b/docs/migrations.md index 849b952..8261600 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -16,3 +16,5 @@ Phase 1D appends checkout tables, reservation ownership, immutable snapshot guar Phase 1E adds pricing policies, immutable final-price snapshots and commerce events with leased delivery state in two further timestamped migrations. All eleven preceding migrations remain unchanged. Phase 2A appends supplier, material and supplier-material compatibility tables. It grants procurement permissions to existing system roles; custom roles must be updated through the RBAC API. Phase 2B appends purchase-order headers and immutable line snapshots. No existing migration is modified. +The subsequent purchase-order integrity migration adds database guards for header state changes and line snapshot edits; historical migrations remain unchanged. +The next reconciliation migration checks line arithmetic and the order total at transaction commit, including nested line creation. diff --git a/docs/procurement-api.md b/docs/procurement-api.md index 1d30fec..fcc5517 100644 --- a/docs/procurement-api.md +++ b/docs/procurement-api.md @@ -12,5 +12,6 @@ This phase introduces private, organization-scoped supplier and material master | PUT | /suppliers/:supplierId/materials/:materialId | procurement.manage | Create or replace compatibility, commercial lead time and quote | Supplier and material codes are uppercase, organization-unique identifiers. Materials use a fixed kind and unit to avoid ambiguous procurement and BOM quantities. Compatibility records hold a supplier SKU, lead time, minimum quantity, price, currency, and active status. A future purchase order must snapshot these values rather than rely on a later edit. +The `active` list filter accepts only `true` or `false`; `active=false` returns inactive records. All endpoints require a session and enforce a permission again inside write transactions. Missing suppliers and materials produce distinct scoped errors. Create, update, and compatibility actions are audit-recorded without arbitrary payloads. The migration is append-only and grants the new permissions only to existing system roles; custom roles require an explicit update. diff --git a/docs/purchase-orders-api.md b/docs/purchase-orders-api.md index 9293082..826a791 100644 --- a/docs/purchase-orders-api.md +++ b/docs/purchase-orders-api.md @@ -11,5 +11,6 @@ Purchase orders turn active supplier-material quotes into private, organization- | POST | /purchase-orders/:id/cancel | procurement.manage | Cancel a draft order | Each line snapshots the material name, code, unit, supplier SKU, unit price, and line total. The header snapshots its currency and total. One currency is accepted per order, and quantities below the supplier's configured minimum are rejected. +Quote sources are loaded in one scoped query. Totals use exact decimal arithmetic and are rejected before persistence if they exceed the database money column. Database triggers protect existing line snapshots and restrict header updates to a valid draft transition. Orders begin as `DRAFT`. They can become `ISSUED` or `CANCELLED` exactly once, with an audit record for each transition. Issued orders cannot be changed or cancelled in this phase. Partial goods receipts will be designed separately before any stock movement is introduced. diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 7a2fc56..6dd620f 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -13,5 +13,7 @@ "20260911110906_pricing_events": "60a4a5a0a05821c2a9785496cd2e9bc0f839e5fb2ae3c59275655481c96eb66b", "20260911111403_operations_integrity": "f40bddf9e29d6518bc765cbaca7688c04cb95d5ff729c52e7dc775eefa1e521e", "20260913140451_supplier_materials": "c1f59e082ddf97443c17d52745068d9e6cbafb3d4e1088126a150f555c1cf0a1", - "20260913173146_purchase_orders": "1e226f158e57af94c03b8f749349d06a874a8e82c32094ebd638d0ec41dc762a" + "20260913173146_purchase_orders": "1e226f158e57af94c03b8f749349d06a874a8e82c32094ebd638d0ec41dc762a", + "20260923000116_purchase_order_integrity": "ed14ce76d1b29c8de890a89c8dd84216edd002e43732b75d0cdeab4fd8f51fb8", + "20260923001040_purchase_order_reconciliation": "63ddf7618ff14916512597cc16af2de07e0c093d345bb35e607ed830d3ef067e" } diff --git a/prisma/migrations/20260923000116_purchase_order_integrity/migration.sql b/prisma/migrations/20260923000116_purchase_order_integrity/migration.sql new file mode 100644 index 0000000..6965412 --- /dev/null +++ b/prisma/migrations/20260923000116_purchase_order_integrity/migration.sql @@ -0,0 +1,30 @@ +CREATE FUNCTION protect_purchase_order() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Purchase orders cannot be deleted'; + END IF; + IF OLD.status <> 'DRAFT' OR NEW.status NOT IN ('ISSUED', 'CANCELLED') + OR (to_jsonb(NEW) - 'status' - 'issued_at' - 'cancelled_at') + IS DISTINCT FROM (to_jsonb(OLD) - 'status' - 'issued_at' - 'cancelled_at') THEN + RAISE EXCEPTION 'Purchase order snapshot or state cannot be changed'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER purchase_order_protected BEFORE UPDATE OR DELETE ON purchase_orders +FOR EACH ROW EXECUTE FUNCTION protect_purchase_order(); + +CREATE FUNCTION protect_purchase_order_line() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Purchase order line snapshots cannot be changed'; + END IF; + IF NOT EXISTS (SELECT 1 FROM purchase_orders WHERE id = NEW.purchase_order_id + AND organization_id = NEW.organization_id AND status = 'DRAFT') THEN + RAISE EXCEPTION 'Purchase order lines require a draft order'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER purchase_order_line_protected BEFORE INSERT OR UPDATE OR DELETE ON purchase_order_lines +FOR EACH ROW EXECUTE FUNCTION protect_purchase_order_line(); diff --git a/prisma/migrations/20260923001040_purchase_order_reconciliation/migration.sql b/prisma/migrations/20260923001040_purchase_order_reconciliation/migration.sql new file mode 100644 index 0000000..341e8c0 --- /dev/null +++ b/prisma/migrations/20260923001040_purchase_order_reconciliation/migration.sql @@ -0,0 +1,26 @@ +ALTER TABLE purchase_order_lines ADD CONSTRAINT purchase_order_line_total_valid +CHECK (line_total = ROUND(quantity * unit_price, 2)); + +CREATE FUNCTION reconcile_purchase_order_lines() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + target_id UUID; + expected NUMERIC; + actual NUMERIC; + line_count INTEGER; +BEGIN + IF TG_TABLE_NAME = 'purchase_orders' THEN target_id := NEW.id; + ELSE target_id := NEW.purchase_order_id; + END IF; + SELECT merchandise_total INTO expected FROM purchase_orders WHERE id = target_id; + SELECT COALESCE(SUM(line_total), 0), COUNT(*) INTO actual, line_count + FROM purchase_order_lines WHERE purchase_order_id = target_id; + IF expected IS DISTINCT FROM actual OR line_count = 0 THEN + RAISE EXCEPTION 'Purchase order total does not match lines'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER purchase_orders_reconcile_lines AFTER INSERT ON purchase_orders +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_purchase_order_lines(); +CREATE CONSTRAINT TRIGGER purchase_order_lines_reconcile_total AFTER INSERT ON purchase_order_lines +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reconcile_purchase_order_lines(); diff --git a/src/procurement/procurement.schemas.ts b/src/procurement/procurement.schemas.ts index 771989b..b3bc4ce 100644 --- a/src/procurement/procurement.schemas.ts +++ b/src/procurement/procurement.schemas.ts @@ -66,7 +66,10 @@ export const supplierMaterialSchema = z .strict(); export const procurementQuery = pageSchema .extend({ - active: z.coerce.boolean().optional(), + active: z + .enum(['true', 'false']) + .transform((value) => value === 'true') + .optional(), search: text(100).optional(), }) .strict(); diff --git a/src/procurement/purchase-order-money.ts b/src/procurement/purchase-order-money.ts index c14ed08..f27a85a 100644 --- a/src/procurement/purchase-order-money.ts +++ b/src/procurement/purchase-order-money.ts @@ -8,7 +8,7 @@ function scaled(value: string, scale: number): bigint { } export function lineTotal(quantity: string, unitPrice: string): string { const total = (scaled(quantity, 3) * scaled(unitPrice, 2) + 500n) / 1000n; - if (total > 99999999999999n) throw new AppError('DATA_CONSTRAINT'); + if (total > 999999999999n) throw new AppError('DATA_CONSTRAINT'); return `${total / 100n}.${(total % 100n).toString().padStart(2, '0')}`; } export function totalOf(lines: readonly { lineTotal: string }[]): string { @@ -16,6 +16,6 @@ export function totalOf(lines: readonly { lineTotal: string }[]): string { (sum, line) => sum + scaled(line.lineTotal, 2), 0n, ); - if (total > 99999999999999n) throw new AppError('DATA_CONSTRAINT'); + if (total > 999999999999n) throw new AppError('DATA_CONSTRAINT'); return `${total / 100n}.${(total % 100n).toString().padStart(2, '0')}`; } diff --git a/src/procurement/purchase-order.store.ts b/src/procurement/purchase-order.store.ts index 8002eea..0fefee8 100644 --- a/src/procurement/purchase-order.store.ts +++ b/src/procurement/purchase-order.store.ts @@ -54,31 +54,33 @@ export class PurchaseOrderStore { }, }); if (!supplier) throw new AppError('SUPPLIER_NOT_FOUND'); - const sources = await Promise.all( - input.lines.map(async (line) => { - const source = await tx.supplierMaterial.findFirst({ - where: { - supplierId: input.supplierId, - materialId: line.materialId, - organizationId: actor.organizationId, - active: true, - }, - include: { material: true }, - }); - if (!source || !source.material.active) - throw new AppError('SUPPLIER_MATERIAL_NOT_FOUND'); - if ( - BigInt(line.quantity.replace('.', '')) < - BigInt(source.minOrderQuantity.toFixed(3).replace('.', '')) - ) - throw new AppError('PURCHASE_ORDER_MINIMUM'); - return { - source, - quantity: line.quantity, - lineTotal: lineTotal(line.quantity, source.unitPrice.toFixed(2)), - }; - }), + const quotes = await tx.supplierMaterial.findMany({ + where: { + supplierId: input.supplierId, + materialId: { in: input.lines.map(({ materialId }) => materialId) }, + organizationId: actor.organizationId, + active: true, + }, + include: { material: true }, + }); + const quoteByMaterial = new Map( + quotes.map((quote) => [quote.materialId, quote]), ); + const sources = input.lines.map((line) => { + const source = quoteByMaterial.get(line.materialId); + if (!source || !source.material.active) + throw new AppError('SUPPLIER_MATERIAL_NOT_FOUND'); + if ( + BigInt(line.quantity.replace('.', '')) < + BigInt(source.minOrderQuantity.toFixed(3).replace('.', '')) + ) + throw new AppError('PURCHASE_ORDER_MINIMUM'); + return { + source, + quantity: line.quantity, + lineTotal: lineTotal(line.quantity, source.unitPrice.toFixed(2)), + }; + }); const currency = sources[0]?.source.currency; if ( !currency || diff --git a/test/procurement.spec.ts b/test/procurement.spec.ts index aab13b6..ae6b90f 100644 --- a/test/procurement.spec.ts +++ b/test/procurement.spec.ts @@ -87,6 +87,19 @@ describe('supplier and material API', () => { .auth(ctx.token, auth) .expect(200); expect(activeOnly.body).toHaveLength(0); + const inactiveOnly = await ctx + .api() + .get('/api/v1/suppliers?active=false') + .auth(ctx.token, auth) + .expect(200); + expect(inactiveOnly.body.map((row: { id: string }) => row.id)).toContain( + supplier.body.id, + ); + await ctx + .api() + .get('/api/v1/suppliers?active=not-a-boolean') + .auth(ctx.token, auth) + .expect(400); expect( await ctx.db.auditEvent.count({ where: { diff --git a/test/purchase-order-money.spec.ts b/test/purchase-order-money.spec.ts new file mode 100644 index 0000000..14bb331 --- /dev/null +++ b/test/purchase-order-money.spec.ts @@ -0,0 +1,13 @@ +import { lineTotal, totalOf } from '../src/procurement/purchase-order-money'; + +describe('purchase order money bounds', () => { + it('rounds the third fractional minor unit only once per line', () => { + expect(lineTotal('1.005', '1.01')).toBe('1.02'); + }); + it('rejects totals exceeding the database decimal precision', () => { + expect(() => lineTotal('999999999.999', '999999999.99')).toThrow(); + expect(() => + totalOf([{ lineTotal: '9999999999.99' }, { lineTotal: '0.01' }]), + ).toThrow(); + }); +}); diff --git a/test/purchase-orders.spec.ts b/test/purchase-orders.spec.ts index 6ca043a..0b3aa23 100644 --- a/test/purchase-orders.spec.ts +++ b/test/purchase-orders.spec.ts @@ -94,12 +94,65 @@ describe('purchase-order API', () => { .auth(ctx.token, auth) .expect(200); expect(detail.body.lines[0].unitPrice).toBe('120'); + await expect( + ctx.db.purchaseOrderLine.update({ + where: { id: detail.body.lines[0].id }, + data: { unitPrice: '1.00' }, + }), + ).rejects.toThrow(); + await expect( + ctx.db.purchaseOrder.update({ + where: { id: created.body.id }, + data: { merchandiseTotal: '1.00' }, + }), + ).rejects.toThrow(); + const extraMaterial = await ctx.db.material.create({ + data: { + organizationId: ctx.owner.organizationId, + name: 'Unquoted material', + code: `EXTRA-${randomUUID().slice(0, 8)}`, + kind: 'WAX', + unit: 'KILOGRAM', + }, + }); + await expect( + ctx.db.purchaseOrderLine.create({ + data: { + purchaseOrderId: created.body.id, + organizationId: ctx.owner.organizationId, + materialId: extraMaterial.id, + materialName: extraMaterial.name, + materialCode: extraMaterial.code, + unit: extraMaterial.unit, + supplierSku: 'EXTRA', + quantity: '1.000', + unitPrice: '1.00', + lineTotal: '1.00', + }, + }), + ).rejects.toThrow(); const issued = await ctx .api() .post(`/api/v1/purchase-orders/${created.body.id}/issue`) .auth(ctx.token, auth) .expect(201); expect(issued.body).toMatchObject({ status: 'ISSUED' }); + await expect( + ctx.db.purchaseOrderLine.create({ + data: { + purchaseOrderId: created.body.id, + organizationId: ctx.owner.organizationId, + materialId: first.material.id, + materialName: 'Late edit', + materialCode: 'LATE', + unit: 'KILOGRAM', + supplierSku: 'LATE', + quantity: '1.000', + unitPrice: '1.00', + lineTotal: '1.00', + }, + }), + ).rejects.toThrow(); const invalid = await ctx .api() .post(`/api/v1/purchase-orders/${created.body.id}/cancel`)