import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; /** * **库存审计面收口**(2026-10-14 多 agent 审计 P0 三条;开发者批准「可以」)。 * * 审计结论(8 维度、真库核查):进销存主链路可用,但库存管理体系有 4 条高优先级缺口。 * 本文件钉住已落地的三条: * P0-1 通用数据网关**禁写** `inventory` / `inventory_logs`(裸写会绕过备注必填+双日志+FIFO/预留); * P0-2 库存审计面补 RLS:`inventory_reservations` / `picking_items` / `picking_tasks` * (原先零 RLS、且启动自检的 CORE_TABLES 也不含它们 ⇒ 缺了也报 ok); * P0-3 出库幂等改为**逐 SKU**:整单守卫会让「分拣软扣跳过的 SKU」永久漏扣; * 同时把 `softSkipped`(算出来没人读)消费掉:分拣漏斗逐行告警、兜底按 SKU 重扫。 * * 设计:docs/design/20261014-库存审计面收口(网关禁写+审计表RLS+出库逐SKU判据).md */ const SRC = path.join(__dirname, '../src'); const read = (rel: string) => readFileSync(path.join(SRC, rel), 'utf8'); describe('P0-1 通用数据网关禁写库存台账', () => { const policy = read('services/accessPolicy.ts'); const denyBlock = policy.slice( policy.indexOf('const DENY_WRITE_TABLES'), policy.indexOf('const DENY_DELETE_TABLES') ); it('inventory / inventory_logs 在 DENY_WRITE_TABLES 里(仍允许读取)', () => { expect(denyBlock).toContain("'inventory',"); expect(denyBlock).toContain("'inventory_logs',"); }); it('两张表仍在 ALLOWED_TABLES(只拦写、不拦读)', () => { // 前端库存查询/库存流水页签走网关 SELECT,禁写不得影响读 const allowed = policy.slice(0, policy.indexOf('const DENY_WRITE_TABLES')); expect(allowed).toContain("'inventory'"); expect(allowed).toContain("'inventory_logs'"); }); }); describe('P0-2 库存审计面 RLS', () => { const guard = read('services/tenantRlsGuard.ts'); const migration = readFileSync( path.join(__dirname, '../../migrations/20261014_tenant_inventory_audit_rls.sql'), 'utf8' ); it('启动自检动态覆盖全部含 branch_code 的表(不再硬编码名单,防 15 vs 75 漂移)', () => { // T4-P2(2026-10-19):名单从真库动态取,三张审计表/库存流水自然被覆盖 expect(guard).toContain("column_name = 'branch_code'"); expect(guard).toContain('COUNT(DISTINCT c.oid)'); expect(guard).toContain("p.polname = 'tenant_isolation_' || c.relname"); expect(guard).not.toMatch(/const CORE_TABLES\b/); }); it('迁移把三张表加进 apply_tenant_core_rls 并重放全部租户', () => { expect(migration).toContain('CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls'); expect(migration).toContain("'inventory_reservations',"); expect(migration).toContain("'picking_items',"); // 数组最后一项没有尾逗号 expect(migration).toContain("'picking_tasks'"); // 幂等重放(新克隆租户由 migrate.ts 阶段 5 继续覆盖) expect(migration).toContain('SELECT public.ensure_all_tenant_core_rls()'); // 仍是「按 branch_code 隔离」的同一策略 expect(migration).toContain("current_setting(''app.branch_code'', true)"); }); // ── 数组解析(红队 #T7-1):从迁移 SQL 解析 core_tables 数组,而不是只查 4 个字符串 ── const migrationB = readFileSync( path.join(__dirname, '../../migrations/20261015_tenant_inventory_logs_rls.sql'), 'utf8' ); const migration63 = readFileSync( path.join(__dirname, '../../migrations/20261063_tenant_core_rls_batch1.sql'), 'utf8' ); const migration64 = readFileSync( path.join(__dirname, '../../migrations/20261064_tenant_core_rls_batch2.sql'), 'utf8' ); function parseCoreTables(sql: string, label: string): string[] { const m = /core_tables\s+text\[\]\s*:=\s*ARRAY\[([\s\S]*?)\];/.exec(sql); if (!m) throw new Error(`${label} 未找到 core_tables 数组`); const names = [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1]); if (!names.length) throw new Error(`${label} 的 core_tables 为空`); if (new Set(names).size !== names.length) throw new Error(`${label} core_tables 有重复项`); return names; } const AUDIT_UNION_15 = [ 'orders', 'order_items', 'customers', 'customer_skus', 'cost_details', 'customer_statements', 'inspections', 'delivery_tasks', 'purchase_orders', 'supplier_preparations', 'inventory', 'inventory_reservations', 'picking_items', 'picking_tasks', 'inventory_logs', ]; /** 两份审计迁移 core_tables 的并集必须 = 15 张(含 customer_statements/inventory_logs) */ function assertAuditUnion(sqlA: string, sqlB: string): Set { const a = parseCoreTables(sqlA, '20261014'); const b = parseCoreTables(sqlB, '20261015'); // 单份迁移的数组长度也必须精确(只删一份里的某张表,并集可能不变 ⇒ 必须按单份长度兜住) expect(a.length, '20261014 core_tables = 14').toBe(14); expect(b.length, '20261015 core_tables = 15').toBe(15); const union = new Set([...a, ...b]); expect(union.size, '两份审计迁移 core_tables 并集应 = 15 张').toBe(15); for (const t of AUDIT_UNION_15) expect(union.has(t), `并集缺 ${t}`).toBe(true); expect(a.includes('inventory_logs'), 'inventory_logs 应只由 20261015 加入').toBe(false); expect(b).toContain('inventory_logs'); return union; } /** RLS 批次:batch1=45、batch2=75,且必须覆盖 15 张审计表(15 vs 75 不得漂移) */ function assertBatchCoverage(sql63: string, sql64: string): { b1: string[]; b2: string[] } { const b1 = parseCoreTables(sql63, '20261063'); const b2 = parseCoreTables(sql64, '20261064'); expect(b1.length, 'batch1 core_tables = 45').toBe(45); expect(b2.length, 'batch2 core_tables = 75').toBe(75); const union = new Set([ ...parseCoreTables(migration, '20261014'), ...parseCoreTables(migrationB, '20261015'), ]); for (const t of union) expect(b2, `batch2 缺 ${t}`).toContain(t); return { b1, b2 }; } it('两份审计迁移 core_tables 并集 = 15 张,RLS 批次 45/75 覆盖且与守卫一致', () => { const union = assertAuditUnion(migration, migrationB); const { b2 } = assertBatchCoverage(migration63, migration64); // 15 张审计表必须全部在最终 75 张里(防「15 vs 75」漂移) for (const t of union) expect(b2).toContain(t); // 守卫(T4-P2)按真库动态判定,不再维护第二份硬编码名单 expect(guard).toContain("column_name = 'branch_code'"); expect(guard).toContain('COUNT(DISTINCT c.oid)'); expect(guard).toContain("p.polname = 'tenant_isolation_' || c.relname"); expect(guard).not.toMatch(/const CORE_TABLES\b/); }); it('变异自检:删除 customer_statements / inventory_logs ⇒ 同一断言函数必须抛错', () => { const del = (sql: string, name: string) => sql.replace(new RegExp(`\\s*'${name}',?`), ''); // ① 删 20261015(最终 15 张名单)的 customer_statements ⇒ 并集少一张,必须红 expect(() => assertAuditUnion(migration, del(migrationB, 'customer_statements'))).toThrow(); // ② 删 20261015 的 inventory_logs ⇒ 并集少一张,必须红 expect(() => assertAuditUnion(migration, del(migrationB, 'inventory_logs'))).toThrow(); // ③ 删 20261064 的 customer_statements ⇒ 75→74,批次断言必须红 expect(() => assertBatchCoverage(migration63, del(migration64, 'customer_statements'))).toThrow(); }); }); describe('P0-3 出库幂等:整单 → 逐 SKU', () => { const outbound = read('services/inventoryOutboundService.ts'); const funnel = read('services/orderWorkflowFulfillmentService.ts'); it('整单守卫函数已删除,改为按 SKU 集合逐行跳过', () => { expect(outbound).not.toContain('async function orderHasOutboundOnClient'); expect(outbound).toContain('async function loadOutboundStateOnClient'); expect(outbound).toContain('SELECT DISTINCT sku_code FROM inventory_logs'); // 流水缺 sku_code(老数据)时退回整单语义,宁可少扣不可重复扣 expect(outbound).toContain('outboundSkus.skus.size === 0'); // 计划里已扣过的 SKU 被过滤掉;全扣过才按 already_outbound 短路 expect(outbound).toContain('allLines.filter((line) => !outboundSkuSet.has(line.sku))'); }); it('10 分钟兜底取数改成逐 SKU 判据(部分扣过的单也会被重扫)', () => { const idx = outbound.indexOf('export async function listOrdersMissingOutboundSettlement'); const body = outbound.slice(idx, idx + 1600); expect(body).toContain('AND il.sku_code = pi.sku_code'); expect(body).toContain("il.operation_type IN ('picking_out', 'delivery_loading_out')"); }); it('softSkipped 不再"算了不报":结案口径返回它、分拣漏斗逐行告警', () => { // 返回值带 softSkipped,且 deducted 只在真的扣成功时置真 expect(outbound).toContain('softSkipped?: Array<{ sku: string; itemName: string | null; qty: number; message: string }>'); expect(outbound).toContain('if (settledAny) deducted = true;'); expect(outbound).toContain('softSkipped: softSkipped.length ? softSkipped : undefined,'); // 分拣漏斗消费它 expect(funnel).toContain('settled?.softSkipped?.length'); expect(funnel).toContain('分拣完毕软扣缺口'); }); it('并发纪律保留:仍先锁订单行(FOR UPDATE)再读流水', () => { const idx = outbound.indexOf('SELECT order_code, branch_code FROM orders WHERE order_code = $1 FOR UPDATE'); const setIdx = outbound.indexOf('const outboundSkus = await loadOutboundStateOnClient(client, code);'); expect(idx).toBeGreaterThan(-1); expect(setIdx).toBeGreaterThan(idx); }); }); /** * P0-2b:`inventory_logs` 是全系统出库/入库事实台账,必须与其余核心表同等隔离。 * 难点是它有 17 处服务端写入点 + 多个 `prod-*` 脚本 ⇒ 不改业务代码,改用 * **BEFORE INSERT 触发器自动盖分公司**,再上严格 RLS。 */ describe('P0-2b 台账 RLS:加列 + 触发器盖章 + 严格隔离', () => { const migration = readFileSync( path.join(__dirname, '../../migrations/20261015_tenant_inventory_logs_rls.sql'), 'utf8' ); it('迁移给 inventory_logs 加列并回填(订单分公司优先,其次按 schema 推导)', () => { expect(migration).toContain("ADD COLUMN IF NOT EXISTS branch_code text"); expect(migration).toContain('UPDATE %I.%I il'); expect(migration).toContain('SELECT o.branch_code FROM %I.orders o WHERE o.order_code = il.related_order_code'); expect(migration).toContain('public.tenant_branch_code_from_schema(%L)'); }); it('BEFORE INSERT 触发器:所有写入方(含脚本/网关)无需改代码即带对分公司', () => { expect(migration).toContain('CREATE OR REPLACE FUNCTION public.set_inventory_log_branch_code()'); expect(migration).toContain('BEFORE INSERT ON %I.%I'); expect(migration).toContain('trg_inventory_log_branch_code'); // 会话变量优先,缺省按 schema 推导(tenant_br003 → BR003) expect(migration).toContain("current_setting('app.branch_code', true)"); expect(migration).toContain("'^tenant_br[0-9]+$'"); }); it('inventory_logs 进 core_tables 并幂等重放(新克隆租户自动带上)', () => { expect(migration).toContain("'inventory_logs'"); expect(migration).toContain('CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls'); expect(migration).toContain('SELECT public.ensure_all_tenant_core_rls()'); // 触发器创建也必须放进 apply_tenant_core_rls(否则新租户只有 RLS、没有默认值) const applyIdx = migration.indexOf('CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls'); const triggerIdx = migration.indexOf('trg_inventory_log_branch_code'); expect(triggerIdx).toBeGreaterThan(applyIdx); }); });