import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; const read = (relative: string) => readFileSync(new URL(relative, import.meta.url), 'utf8'); describe('P0 order list readonly contract', () => { it('returns persisted status and contains no write SQL', () => { const source = read('../src/services/orderManagementQueryService.ts'); expect(source).toContain('order_status: storedStatus'); expect(source).not.toMatch(/\b(?:INSERT|UPDATE|DELETE)\b/i); expect(source).not.toContain('toPersist'); }); it('removes the unused display side-effect resolver', () => { const source = read('../src/services/orderStatusDisplayService.ts'); expect(source).not.toContain('resolveDisplayOrderStatuses'); expect(source).not.toContain('prunePrematurePendingInspectionsForIncompletePreps'); }); it('locks and audits explicit reconciliation changes', () => { const source = read('../src/services/orderStatusReconcileService.ts'); expect(source).toContain('withOrderAdvisoryLock(code'); expect(source).toContain("operationType: 'order_status_reconcile'"); expect(source).toContain("operatorName: 'system'"); }); }); describe('P0 tenant referential integrity contract', () => { it('keeps the orphan audit script read-only and fail-closed', () => { const source = read('../scripts/audit-tenant-referential-integrity.mjs'); expect(source).toContain("await client.query('BEGIN READ ONLY')"); expect(source).toContain('process.exitCode = report.violations > 0'); expect(source).not.toMatch(/\b(?:INSERT|UPDATE|DELETE)\s+(?:INTO|FROM|\w)/i); }); it('purges order tree children before deleting the order', () => { const source = read('../src/services/orderDeleteService.ts'); const picking = source.indexOf("deleteOrderItemDependants(client, 'picking_items'"); const fulfillments = source.indexOf("'order_item_fulfillments'"); const returns = source.indexOf("'order_item_returns'", fulfillments); const items = source.indexOf("deleteByOrderCode(client, 'order_items'"); const order = source.indexOf('DELETE FROM orders WHERE order_code'); expect(picking).toBeGreaterThan(0); expect(fulfillments).toBeGreaterThan(picking); expect(returns).toBeGreaterThan(fulfillments); expect(items).toBeGreaterThan(returns); expect(order).toBeGreaterThan(items); }); it('adds only the three same-schema core FKs as NOT VALID', () => { const migration = read('../../migrations/20260908_tenant_core_foreign_keys.sql'); expect(migration.match(/FOREIGN KEY \(/g)).toHaveLength(3); expect(migration.match(/ON DELETE CASCADE NOT VALID/g)).toHaveLength(3); expect(migration).toContain('REFERENCES %I.orders(order_code)'); expect(migration).toContain('REFERENCES %I.order_items(id)'); expect(migration).toContain('REFERENCES %I.picking_tasks(pick_code)'); expect(migration).toContain('ensure_tenant_core_foreign_keys(v_schema)'); expect(migration).not.toMatch(/REFERENCES\s+(?:public|legacy_public)\./); }); });