一、P0-2b `inventory_logs` 补 branch_code + 触发器盖章 + 严格 RLS
迁移 20261015_tenant_inventory_logs_rls.sql:加列 → 回填(关联订单分公司优先,其次按 schema 推导)
→ BEFORE INSERT 触发器 trg_inventory_log_branch_code 自动盖章(会话 app.branch_code → schema 推导)
→ inventory_logs 进 core_tables(14→15)并幂等重放(触发器创建也在 apply_tenant_core_rls 内,
新克隆租户自动带上 RLS + 默认值)。
这样 17 处服务端 INSERT 与多处 prod-* 脚本**一行都不用改**。
实测:5 个 schema 全部 FORCE RLS + 列 + 触发器;BR003 台账 40 行全部回填 BR003;
不传 branch_code 的 INSERT 被盖 BR003、写错分公司被 RLS 拒;inspectTenantRls() 每租户 15/15、
assertTenantRlsReady() 通过。tenantRlsGuard.CORE_TABLES 同步 15 张(否则缺 RLS 也会报 ok)。
二、P1-4 已结案订单的历史出库缺口
新增 scripts/repair-closed-order-outbound-gap.ts(默认干跑、--order= 可圈定、--apply 才真扣):
复用既有出库口径 ensureOrderInventorySettledOnComplete({operationType:'picking_out'})(逐 SKU 只补缺的);
审计留痕由扣库路径写(operation_logs picking_outbound 含逐批次明细),脚本不重复写噪声行。
实测 BR003:ORD_API_20261012_BR003_0002(90 状态 / 4 行 / 29 斤 / 无出库流水)→ 干跑列出计划
→ --apply 补扣成功,生成 4 条 picking_out(5 / 13 / 9.90 / 1.00 = 28.90,海带丝按核货量 9.90,
符合「loaded 优先」口径),批次可用量同步下降;再跑命中 0 张(幂等)。
兜底窗口仍保持 50–89(90 属历史冻结范围,是否自动重扫是产品决定)。
三、P1-5 账期口径(第三处已修;前两处已量数待批)
① 账外持有 cycle_code 被修复脚本写成 YYYYMMDD(9 行 / ¥1,146.90,占桶余额 91%)⇒
3 个脚本改用 currentCycleCodeChina();存量由 scripts/repair-holding-cycle-code.ts 改写为 202610
(复跑:202610 共 12 行 / ¥1,260.90)。
② 看板 SUM(COALESCE(allocated_amount,amount))=¥3,797.40 vs 成本 KPI SUM(amount)=¥3,112.40,
差 ¥685.00,且看板把 inventory_holding ¥1,260.90 计入 totalCost(KPI 排除);
③ 移动端下单把 orders.cycle_code 写成 'MOBILE'(customerOrderSubmitService.ts:589)⇒
抵扣结转成本行 cycle_code='MOBILE' 12 行 / ¥1,285.70,月度账期取数看不到。
②③ 属财务冻结流程:已把改法与改前/改后数字写进 docs/design/20261014-成本口径对齐.md,等确认再动。
测试:inventoryAuditHardening.test.ts 12 例(新增 P0-2b 三条 + 名单 15 张并集校验)。
回归:server 25 failed / 397 passed(失败文件集与基线逐一比对一致);root tsc 0;门禁 8/1/1。
162 lines
8.4 KiB
TypeScript
162 lines
8.4 KiB
TypeScript
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);
|
||
});
|
||
});
|