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('启动自检名单含三张审计表(名单漏一张 ⇒ 缺 RLS 也会报 ok)', () => { expect(guard).toContain("'inventory_reservations',"); expect(guard).toContain("'picking_items',"); expect(guard).toContain("'picking_tasks',"); // P0-2b:出库/入库事实台账 expect(guard).toContain("'inventory_logs',"); }); 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)"); }); it('两份名单必须一致:两份迁移的 core_tables 并集 与 守卫 CORE_TABLES 逐项对齐', () => { // P0-2 在 20261014 迁移里扩了三张审计表;P0-2b 在 20261015 迁移里补了 inventory_logs const migrationB = readFileSync( path.join(__dirname, '../../migrations/20261015_tenant_inventory_logs_rls.sql'), 'utf8' ); const allMigrations = `${migration}\n${migrationB}`; const tables = ['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']; for (const t of tables) { expect(allMigrations, `迁移(两份并集)缺 ${t}`).toContain(`'${t}'`); expect(guard, `自检名单缺 ${t}`).toContain(`'${t}',`); } }); }); 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); }); });