Files
SupplierSystem/server/tests/pickingCompleteDeductsInventory.test.ts
T
Ubuntu 42c5cb8332 fix(库存审计面): P0 三条收口 —— 网关禁写库存台账 / 审计表补 RLS / 出库幂等改逐 SKU
8 维度多 agent 审计(含真库核查 + 对抗复核)结论:进销存主链路可用,库存管理体系 4 条高危缺口。
本次落地 P0 三条(开发者批准「可以」):

P0-1 通用数据网关禁写 `inventory` / `inventory_logs`(accessPolicy.DENY_WRITE_TABLES):
  裸写会绕过「备注必填 + 双日志 + FIFO/预留保护」;读取不受影响(两表仍在 ALLOWED_TABLES,
  前端对它们只有 SELECT,已 grep 核对)。台账写入必须走验收/独立入库/自采入库/调整/出库受控路由。

P0-2 审计面补 RLS(迁移 20261014_tenant_inventory_audit_rls.sql):
  apply_tenant_core_rls 的 core_tables 11 → 14 张,新增 inventory_reservations / picking_items /
  picking_tasks(三张都有 branch_code、真库 0 行 NULL),并幂等重放到全部 tenant_*;
  tenantRlsGuard.CORE_TABLES 同步扩到 14 张(名单漏一张 ⇒ 缺 RLS 也会报 ok,这正是本次缺口成因)。
  实测:tenant_br003 有 RLS 的表 11 → 14;正确分支可读 12 行分拣行,错误分支读到 0 行。
  ⚠️ inventory_logs 无 branch_code 列(40 行 + 17 处服务端写入点 + prod-* 脚本),
  需「加列+回填+逐写入点补列+收紧策略」整体做,列下一轮 P0-2b。

P0-3 出库幂等:整单 → **逐 SKU**(inventoryOutboundService + 分拣漏斗):
  · 删掉整单守卫 orderHasOutboundOnClient,改 loadOutboundStateOnClient(DISTINCT sku_code)
    + orderHasPendingOutboundOnClient(逐 SKU 是否仍有"有实物动作却没流水"的行);
  · 计划按已扣 SKU 过滤;全扣过才 already_outbound;流水缺 sku_code 的老数据退回整单语义;
  · 结案兜底只有真扣成功才置 deducted(原先无条件 true ⇒ 全行软扣失败也报"补扣成功");
  · softSkipped 被消费:结案口径上抛 + 分拣漏斗逐行告警(原来算了没人读);
  · listOrdersMissingOutboundSettlement 判据改逐 SKU ⇒ 部分扣过的单也会被 10 分钟任务重扫。
  真库验证:listOrdersMissingOutboundSettlement()=[](无待补扣);已全扣的单再跑返回
  already_outbound 且出库流水 4 条/63.00 不变(不重复扣)。

测试:新增 inventoryAuditHardening.test.ts(9 例:P0-1/P0-2 名单与迁移一致、P0-3 逐 SKU + softSkipped);
更新 pickingCompleteDeductsInventory / pickupSettleInventoryOnClose 两处断言到新代码形状。
回归:server 25 failed / 396 passed(失败文件集与基线逐一比对一致,无新增失败);root tsc 0;
门禁 8 通过 / 1 已知红 / 1 未执行。

待批准(P1):90 状态历史缺口单 1 张(4 行/29 斤)的收口或兜底上延;成本口径三处对齐(财务冻结);
整单抵扣入口补直送/免入库闸门;效期闸门 + 验收写 expiry_date;盘点单据化。
2026-10-14 10:43:26 +08:00

153 lines
9.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* **分拣完毕 = 出库 = 扣库存**(开发者 2026-10-13 口径,全单统一)。
*
* 设计:docs/design/20261013-分拣完毕即出库扣库存(全单统一).md
*
* 背景(真库实证):`ORD_API_20261012_BR003_0002` 的 `preparations.picked_up` 收口成功(status=done),
* 但该单批次**只有入库流水、没有出库流水** ⇒ 骑手上门取货单永久漏扣。扣库触发权在主系统事件 +
* 时点要求在发车,两条都不由我方掌控。
*
* 这里钉住三件事:
* ① 分拣完成(`tryAdvanceOrderToDelivery` 置 50 之前)必须软扣一次库存;
* ② 核货差额**不回补**(发车命中 `already_outbound` 守卫 ⇒ 不二次扣、不回冲);
* ③ 软扣语义与冻结项不变(库存不足不拦;发车仍只拦「无核货明细」)。
*/
const FILE = path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts');
const OUTBOUND = path.join(__dirname, '../src/services/inventoryOutboundService.ts');
const src = readFileSync(FILE, 'utf8');
const outbound = readFileSync(OUTBOUND, 'utf8');
describe('分拣完毕即出库扣库存', () => {
it('① 置 50 之前调用软扣(ensureOrderInventorySettledOnComplete + softInventory)', () => {
const settleIdx = src.indexOf('await ensureOrderInventorySettledOnComplete(orderCode, {');
// 分拣路径的收尾(picker 路径专属文案)——扣库必须发生在它之前,
// 否则会出现「已待配送但库存没扣」的窗口。⚠️ 不能用文件里第一处 `UPDATE ... order_status = 50`:
// 那是「未启用分拣」分支的,位置在本段之前。
const pickingPathReturnIdx = src.indexOf(
"return { advanced: true, message: '分拣已完成,订单进入待配送' };"
);
expect(settleIdx, '未找到分拣完毕的扣库调用').toBeGreaterThan(-1);
// 软扣 + 分拣出库口径(picking_out)
expect(src.slice(settleIdx, settleIdx + 400)).toContain('softInventory: true');
expect(src.slice(settleIdx, settleIdx + 400)).toContain("operationType: 'picking_out'");
expect(pickingPathReturnIdx).toBeGreaterThan(-1);
expect(settleIdx).toBeLessThan(pickingPathReturnIdx);
// 失败只告警、不拦进入待配送(软扣纪律);2026-10-14 起同处还要把软扣缺口打进日志
const around = src.slice(settleIdx - 900, settleIdx + 900);
expect(around).toContain('不拦进入待配送');
expect(around).toContain('softSkipped');
});
it('② 核货差额不回补:发车/结案再扣时靠 already_outbound 守卫短路', () => {
expect(outbound).toContain("reason: 'already_outbound'");
// 守卫按流水判定(picking_out / delivery_loading_out 都算已出库)
expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')");
// 发车仍是原来的软扣调用(未改成硬拦、未加二次扣)
expect(src).toContain('softInventory: true,');
expect(src).toContain("deduct = await deductInventoryForOrderDeparture(orderCode, {");
});
it('③ 冻结项不变:发车只拦「无核货明细」,库存不足不拦', () => {
expect(src).toContain("if (deduct.reason === 'no_loading_items')");
expect(src).toContain('缺少核货/分拣明细');
expect(src).toContain("reason: 'soft_inventory_skip'");
// 状态链常量不在本文件里改
expect(src).not.toContain('ORDER_STATUS_ALLOWED =');
});
});
/**
* 出库扣库"从来没成功过"的真根因(2026-10-13 真库事故):
* 扣库事务里的**留痕查询**写成 `SELECT ... p.name FROM public.profiles p`,
* 而 `public.profiles` 只有 `full_name`(列清单:id/username/full_name/phone/avatar_url/department/status/…)
* ⇒ `column p.name does not exist` ⇒ **事务 abort** ⇒ 后面扣库语句全被拒 ⇒ 回滚;
* 错误被 catch 吞掉,只留一行日志 ⇒ 现象="库存就是扣不掉"。
* 真库实证:BR003 `inventory_logs` 里 `delivery_loading_out`/`picking_out` **0 条**。
*/
describe('出库留痕不得拖垮扣库事务', () => {
it('④ 审计查询用 full_name;整段留痕用 SAVEPOINT 隔离', () => {
expect(outbound).toContain('p.full_name AS name');
expect(outbound).not.toMatch(/SELECT DISTINCT pt\.uid, p\.name/);
// SAVEPOINT 三件套:建、释放、失败回滚
expect(outbound).toContain('SAVEPOINT ${outboundAuditSavepoint}');
expect(outbound).toContain('RELEASE SAVEPOINT ${outboundAuditSavepoint}');
expect(outbound).toContain('ROLLBACK TO SAVEPOINT ${outboundAuditSavepoint}');
});
});
/**
* 存量兜底:扣库时点前移到「分拣完成」**之前**就已经越过该时点的单,靠调度器捞出来补扣
* (2026-10-13 开发者要求)。真库实证:BR003 有两张单(`…_0002` 米块 8 斤、`…_0003` 四行 63 斤)
* 「状态 50、已出库、却无任何出库流水」,本轮已用同一函数补扣完成。
*/
describe('出库扣库兜底(存量单)', () => {
const jobs = readFileSync(path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8');
it('⑤ 调度器注册了兜底任务,取数在 service、只覆盖未结案的单', () => {
expect(jobs).toContain('runOutboundSettleBackfill()');
expect(jobs).toContain('listOrdersMissingOutboundSettlement');
// 节流 10 分钟(与批次计划兜底同款)
expect(jobs).toContain('lastOutboundSettleBackfillAt');
// 取数谓词:50–89、近 45 天、有实拣量、无出库流水
expect(outbound).toContain('o.order_status BETWEEN 50 AND 89');
expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')");
// ⚠️ 不得把已结案(90)的单也捞进来:历史结案白名单是有意跳过 FIFO 扣库的
expect(outbound).not.toContain('o.order_status >= 50');
});
});
/**
* 分拣出库扣库的**正确性**(2026-10-13 开发者要求逐条核查)。
*
* 真库实测(临时单,跑完即清理):
* ① 分拣完成 ⇒ 流水 `picking_out` 6.00,批次 22 → 16;
* ② 发车再扣(`deductInventoryForOrderDeparture`)⇒ `already_outbound`、批次不变;
* ③ 别单挂 6 斤活跃预留后,扣 20 斤被拦:`库存不足,缺少 10(扣除他单预留后可用 10)`。
*
* ⚠️ 2026-10-13 变化:`restoreInventoryForOrderDeparture`(发车失败回补)在生产代码里**没有调用方**,
* 已按开发者指示作为死代码删除;原先"回补只认 delivery_loading_out"的断言随之移除,
* 改为断言"该函数确实不存在",并保留"分拣/核货两种出库类型分开记"的口径。
*/
describe('分拣出库扣库:不重复扣 / 不吃他单预留 / 出库必扣', () => {
it('⑧ 分拣出库写 picking_out;发车失败回补(死代码)已清理', () => {
const funnel = readFileSync(path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8');
const idx = funnel.indexOf('await ensureOrderInventorySettledOnComplete(orderCode, {');
expect(idx).toBeGreaterThan(-1);
expect(funnel.slice(idx, idx + 400)).toContain("operationType: 'picking_out'");
// 死代码清理:回补函数不再存在,其 unique 流水类型也没有写入方(历史数据展示文案保留)
expect(outbound).not.toContain('export async function restoreInventoryForOrderDeparture');
expect(outbound).not.toContain("'delivery_loading_restore'");
// 两种出库类型仍分开记(备注据此区分:分拣出库 / 配送核货出库)
expect(outbound).toContain('分拣出库 ${input.pickCode}');
expect(outbound).toContain('配送核货出库 ${input.pickCode}');
});
it('⑧b 10 分钟兜底补写同样按「分拣出库(picking_out)」记', () => {
const jobs = readFileSync(path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8');
const fn = jobs.slice(jobs.indexOf('async function runOutboundSettleBackfill'));
expect(fn).toContain("operationType: 'picking_out'");
expect(fn).toContain('ensureOrderInventorySettledOnComplete(orderCode, {');
});
it('⑨ 幂等守卫认两种出库类型 ⇒ 分拣/发车/结案三条路互不重复扣', () => {
expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')");
// 三条会扣库的入口都走带守卫的函数
const funnel = readFileSync(path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8');
expect(funnel).toContain('ensureOrderInventorySettledOnComplete(orderCode');
expect(funnel).toContain('deductInventoryForOrderDeparture(orderCode');
expect(outbound).toContain('export async function ensureOrderInventorySettledOnComplete(');
});
it('⑩ 扣库不得吃他单活跃预留:先按「毛可用 − 他单预留」校验', () => {
const cover = readFileSync(path.join(__dirname, '../src/services/inventoryStockCoverService.ts'), 'utf8');
expect(cover).toContain('sumOtherOrderReservations');
expect(cover).toContain('export async function getClaimableStockQty(');
expect(outbound).toContain('respectOtherReservations');
expect(outbound).toContain('扣除他单预留后可用');
});
});