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;盘点单据化。
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
# 库存审计面收口:网关禁写 + 审计表 RLS + 出库逐 SKU 判据(2026-10-14)
|
||||
|
||||
- 日期:2026-10-14
|
||||
- 状态:**已实现**(开发者批准:「可以」——针对 8 维度多 agent 审计给出的 P0 三条)
|
||||
- 关联:[20261013-分拣完毕即出库扣库存(全单统一).md](./20261013-分拣完毕即出库扣库存(全单统一).md)、
|
||||
[20260910-tenant-clone-rls.md](./20260910-tenant-clone-rls.md)、
|
||||
[20260920-inventory-freeze.md](./20260920-inventory-freeze.md)
|
||||
|
||||
## 1. 审计结论(8 维度 × 对抗复核,真库核查)
|
||||
|
||||
| 维度 | 结论 |
|
||||
| ---- | ---- |
|
||||
| 入库链路 / 出库链路 / 台账一致性 / 预留 / 成本 / 盘点调整 / 批次效期 / 可用性 | 全部「**基本可用有缺口**」,无一「不可用」 |
|
||||
|
||||
主链路闭合(写入点逐点核对:改库存的服务层写入点都同事务写流水;BR002 逐批次完全对平),
|
||||
**4 条高优先级缺口**:
|
||||
|
||||
| # | 缺口 | 现状 |
|
||||
| - | ---- | ---- |
|
||||
| P0-1 | `/api/data` 可裸写 `inventory` / `inventory_logs` | 绕过备注必填 + 双日志 + FIFO/预留;真库已有 3 个批次「有量零流水」(37.50,无法追溯) |
|
||||
| P0-2 | 审计面零 RLS | `inventory_reservations` / `picking_items` / `picking_tasks` 实测 `relrowsecurity=false`;而自检 `CORE_TABLES` 恰好也不含它们 ⇒ 缺了也报 ok |
|
||||
| P0-3 | 出库幂等是**整单级** | 分拣软扣跳过的 SKU,之后发车/结案/兜底全被守卫短路 ⇒ **永久漏扣**;`softSkipped` 算了没人读 |
|
||||
| P1-4 | 已结案(90)单的历史漏扣 | 兜底只扫 50–89 ⇒ 够不到(真库现存 1 张:4 行 29 斤无出库流水);待批准 |
|
||||
|
||||
## 2. 本次落地
|
||||
|
||||
### P0-1 网关禁写(`accessPolicy.ts`)
|
||||
|
||||
`inventory` / `inventory_logs` 加入 `DENY_WRITE_TABLES`:写入必须走受控路由(验收、独立入库、自采入库、
|
||||
`POST /inventory/adjust`、出库)。**读取不受影响**(两张表仍在 `ALLOWED_TABLES`;前端对它们只有 SELECT,
|
||||
已 grep 核对无 insert/update/upsert/delete)。`routeLayerBoundary.test.ts` 的方向本就是「可写表只能缩小」。
|
||||
|
||||
### 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 ⇒ 无损开启),再 `ensure_all_tenant_core_rls()` 幂等重放;
|
||||
- `tenantRlsGuard.CORE_TABLES` 同步扩到 14 张,并在注释里写明「必须与迁移保持一致,否则缺 RLS 也会报 ok」;
|
||||
- 实测(迁移后):`tenant_br003` 有 RLS 的表 11 → **14**;设对分支能读到 12 行分拣行、设错分支(BR999)读到 **0 行**。
|
||||
|
||||
**未做(下一步 P0-2b)**:`inventory_logs` 没有 `branch_code` 列(40 行 + 17 处服务端写入点 + 多个 `prod-*` 脚本写入),
|
||||
需要「加列 + 回填 + 逐写入点补 branch_code + 收紧策略」一起做,属于库存冻结范围,单独一轮实施。
|
||||
|
||||
### P0-3 出库幂等:整单 → 逐 SKU(`inventoryOutboundService.ts`)
|
||||
|
||||
| 改动 | 说明 |
|
||||
| ---- | ---- |
|
||||
| 删除整单守卫 `orderHasOutboundOnClient` | 改为 `loadOutboundSkuSetOnClient`(`SELECT DISTINCT sku_code ...`)+ `orderHasPendingOutboundOnClient`(逐 SKU 是否有缺) |
|
||||
| 计划过滤 | `deductLines = allLines.filter((line) => !outboundSkus.has(line.sku))`;全扣过才返回 `already_outbound` |
|
||||
| 并发纪律保留 | 仍先 `orders ... FOR UPDATE` 独占锁,再读流水集合(串行进入,后到者能看见先到者) |
|
||||
| `deducted` 说真话 | 结案兜底段只有 `settledAny` 为真才置 `deducted = true`(原先无条件置真 ⇒ 全行软扣失败也报"补扣成功") |
|
||||
| `softSkipped` 被消费 | `ensureOrderInventorySettledOnComplete` 返回它;分拣漏斗(`tryAdvanceOrderToDelivery`)逐行 `console.warn` 缺口,提示稍后自动补扣 |
|
||||
| 兜底取数改逐 SKU | `listOrdersMissingOutboundSettlement` 判据从「整单没有任何出库流水」改为「存在某行有实物动作但其 SKU 没有出库流水」⇒ **部分扣过的单也会被 10 分钟任务重扫** |
|
||||
|
||||
运行时验证(BR003,只读/幂等路径):
|
||||
|
||||
1. `listOrdersMissingOutboundSettlement()` = `[]`,真库「部分缺流水」的单 = 0 张(当前无待补扣);
|
||||
2. 已全扣的单再跑:`{deducted:false, reason:'already_outbound'}`,出库流水 4 条/63.00 **不变**(不重复扣);
|
||||
3. 90 状态的历史缺口单仍在(1 张 / 4 行 / 29 斤)——属 P1-4,等批准后单独处理。
|
||||
|
||||
## 3. 验收标准
|
||||
|
||||
1. `inventory` / `inventory_logs` 在 `DENY_WRITE_TABLES`,且仍在 `ALLOWED_TABLES`(只拦写不拦读);
|
||||
2. 迁移与 `tenantRlsGuard.CORE_TABLES` 两份名单逐项一致(测试钉住 14 张);
|
||||
3. 真库 RLS 生效:正确分支可读、错误分支 0 行;
|
||||
4. 出库逐 SKU 幂等:已扣不重扣、缺的能被兜底重扫;`softSkipped` 出现在返回值与分拣漏斗日志;
|
||||
5. 回归与基线一致(改动前 `25 failed / 393 passed`)。
|
||||
|
||||
## 4. 回滚
|
||||
|
||||
- P0-1:从 `DENY_WRITE_TABLES` 移除两行即恢复(不涉及数据);
|
||||
- P0-2:迁移只做 `ENABLE/FORCE RLS` + 策略,回滚=对新迁移写一份 `DISABLE`/`NO FORCE`(不建议);
|
||||
- P0-3:`git revert` 即回到整单守卫(注意:会恢复"整单短路"这一漏扣面)。
|
||||
|
||||
## 5. 影响面(文件)
|
||||
|
||||
| 文件 | 改动 |
|
||||
| ---- | ---- |
|
||||
| `server/src/services/accessPolicy.ts` | 两表进 `DENY_WRITE_TABLES` |
|
||||
| `migrations/20261014_tenant_inventory_audit_rls.sql` | **新增**:`apply_tenant_core_rls` 扩表 + 幂等重放 |
|
||||
| `server/src/services/tenantRlsGuard.ts` | 自检名单 11 → 14 张 |
|
||||
| `server/src/services/inventoryOutboundService.ts` | 逐 SKU 幂等 + `softSkipped` 上抛 + 兜底取数改逐 SKU |
|
||||
| `server/src/services/orderWorkflowFulfillmentService.ts` | 分拣漏斗消费 `softSkipped`(逐行告警) |
|
||||
| `server/tests/inventoryAuditHardening.test.ts` | **新增**:P0-1/P0-2/P0-3 共 9 例 |
|
||||
| `server/tests/pickingCompleteDeductsInventory.test.ts` | ① 断言窗口扩到软扣告警段 |
|
||||
@@ -0,0 +1,90 @@
|
||||
-- 库存审计面补齐 RLS(2026-10-14 多 agent 审计 P0-2)
|
||||
--
|
||||
-- 背景:`apply_tenant_core_rls` 原先只覆盖 11 张核心表,而库存审计面的
|
||||
-- `inventory_reservations` / `picking_items` / `picking_tasks` **零 RLS**(真库 pg_class 实测
|
||||
-- relrowsecurity = false),`inventory_logs` 另外还缺 `branch_code` 列(见下一支迁移)。
|
||||
-- 网关连接上 RLS 是唯一的库层防线;这三张表都已有 `branch_code` 且真库 0 行 NULL ⇒ 可无损开启。
|
||||
--
|
||||
-- 做法:`CREATE OR REPLACE` 覆盖 `apply_tenant_core_rls`(扩展 core_tables 数组),
|
||||
-- 再对全部 `tenant_*`(含 `tenant_template`)幂等重放一遍。与既有迁移同形,
|
||||
-- 新克隆的租户 schema 依旧由 `migrate.ts` 阶段 5 每次调用 `ensure_all_tenant_core_rls()` 补齐。
|
||||
--
|
||||
-- 设计:docs/design/20261014-库存审计面收口(网关禁写+审计表RLS+出库逐SKU判据).md
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.apply_tenant_core_rls(p_schema text)
|
||||
RETURNS void
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
tbl text;
|
||||
policy_name text;
|
||||
core_tables text[] := ARRAY[
|
||||
'orders',
|
||||
'order_items',
|
||||
'customers',
|
||||
'customer_skus',
|
||||
'cost_details',
|
||||
'customer_statements',
|
||||
'inspections',
|
||||
'delivery_tasks',
|
||||
'purchase_orders',
|
||||
'supplier_preparations',
|
||||
'inventory',
|
||||
-- 2026-10-14 扩容:库存审计面(审计 P0-2)
|
||||
'inventory_reservations',
|
||||
'picking_items',
|
||||
'picking_tasks'
|
||||
];
|
||||
BEGIN
|
||||
IF p_schema IS NULL OR p_schema NOT LIKE 'tenant_%' THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
IF to_regnamespace(p_schema) IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
FOREACH tbl IN ARRAY core_tables
|
||||
LOOP
|
||||
IF to_regclass(format('%I.%I', p_schema, tbl)) IS NULL THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = p_schema
|
||||
AND table_name = tbl
|
||||
AND column_name = 'branch_code'
|
||||
) THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
|
||||
EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', p_schema, tbl);
|
||||
|
||||
policy_name := 'tenant_isolation_' || tbl;
|
||||
EXECUTE format('DROP POLICY IF EXISTS %I ON %I.%I', policy_name, p_schema, tbl);
|
||||
EXECUTE format(
|
||||
'CREATE POLICY %I ON %I.%I FOR ALL
|
||||
USING (branch_code::text = current_setting(''app.branch_code'', true))
|
||||
WITH CHECK (branch_code::text = current_setting(''app.branch_code'', true))',
|
||||
policy_name,
|
||||
p_schema,
|
||||
tbl
|
||||
);
|
||||
END LOOP;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN
|
||||
EXECUTE format('GRANT USAGE ON SCHEMA %I TO canteen_app_rls', p_schema);
|
||||
EXECUTE format(
|
||||
'GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO canteen_app_rls',
|
||||
p_schema
|
||||
);
|
||||
EXECUTE format(
|
||||
'GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA %I TO canteen_app_rls',
|
||||
p_schema
|
||||
);
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
SELECT public.ensure_all_tenant_core_rls() AS tenant_schemas_rls_applied;
|
||||
@@ -99,6 +99,12 @@ const DENY_WRITE_TABLES = new Set([
|
||||
'fixed_costs',
|
||||
'after_sale_returns',
|
||||
'order_item_returns',
|
||||
// 库存台账(2026-10-14 多 agent 审计 P0-1 收口):写入必须走受控路由
|
||||
// (验收 / 独立入库 / 自采入库 / 库存调整 / 出库);**网关裸写会绕过**
|
||||
// 「备注必填 + 双日志 + FIFO/预留保护」,且真库已出现「有库存、零流水」批次(3 批 37.50,无法追溯)。
|
||||
// 读取不受影响:库存查询与库存流水页签照旧(前端对这两张表只有 SELECT)。
|
||||
'inventory',
|
||||
'inventory_logs',
|
||||
]);
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,12 +16,51 @@ export interface InventoryDeductBatch {
|
||||
costPrice: number;
|
||||
}
|
||||
|
||||
async function orderHasOutboundOnClient(client: PoolClient, orderCode: string): Promise<boolean> {
|
||||
/**
|
||||
* 本单**已有出库流水**的 SKU 集合(出库事实只认 `inventory_logs`)。
|
||||
*
|
||||
* 为什么要逐 SKU(2026-10-14 多 agent 审计 P0-3):出库幂等原先按**整单**判
|
||||
* (只要有一行扣成,整单就短路)。而分拣完毕(45→50)是**软扣**:
|
||||
* 某 SKU 库存不足时该行被 `continue` 跳过、订单照样推进到 50,之后发车/结案/10 分钟兜底
|
||||
* 全被整单守卫挡住 ⇒ **那个 SKU 永远漏扣**(库存长期虚高、账面与实物不符)。
|
||||
* 现在改成"**哪个 SKU 没扣过就补哪个**":已扣的跳过,未扣的继续扣。
|
||||
*/
|
||||
async function loadOutboundStateOnClient(
|
||||
client: PoolClient,
|
||||
orderCode: string
|
||||
): Promise<{ skus: Set<string>; hasAny: boolean }> {
|
||||
const result = await client.query(
|
||||
`SELECT 1 FROM inventory_logs
|
||||
WHERE related_order_code = $1
|
||||
AND operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
LIMIT 1`,
|
||||
`SELECT DISTINCT sku_code FROM inventory_logs
|
||||
WHERE related_order_code = $1
|
||||
AND operation_type IN ('picking_out', 'delivery_loading_out')`,
|
||||
[orderCode]
|
||||
);
|
||||
const skus = new Set(
|
||||
result.rows.map((row) => trimSku((row as { sku_code?: unknown }).sku_code)).filter(Boolean)
|
||||
);
|
||||
return { skus, hasAny: (result.rowCount || 0) > 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 本单是否还有「有实物动作、却没有出库流水」的行(逐 SKU 判据)。
|
||||
* 与 `listOrdersMissingOutboundSettlement` 的取数判据同口径:用于结案兜底与定时补扣。
|
||||
*/
|
||||
async function orderHasPendingOutboundOnClient(
|
||||
client: PoolClient,
|
||||
orderCode: string
|
||||
): Promise<boolean> {
|
||||
const result = await client.query(
|
||||
`SELECT 1
|
||||
FROM picking_items pi
|
||||
WHERE pi.order_code = $1
|
||||
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.loaded_qty, 0) > 0)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM inventory_logs il
|
||||
WHERE il.related_order_code = $1
|
||||
AND il.sku_code = pi.sku_code
|
||||
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
)
|
||||
LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
return (result.rowCount || 0) > 0;
|
||||
@@ -372,10 +411,6 @@ export async function deductInventoryForOrderDeparture(
|
||||
const softInventory = options?.softInventory === true;
|
||||
|
||||
const external = options?.client;
|
||||
if (!external && (await orderHasInventoryOutbound(code))) {
|
||||
return { deducted: false, skipped: true, reason: 'already_outbound' };
|
||||
}
|
||||
|
||||
const ownsTxn = !external;
|
||||
const client = external || (await pool.connect());
|
||||
try {
|
||||
@@ -400,18 +435,28 @@ export async function deductInventoryForOrderDeparture(
|
||||
}
|
||||
const branchCode = order.branch_code ? String(order.branch_code) : null;
|
||||
|
||||
const again = await client.query(
|
||||
`SELECT 1 FROM inventory_logs
|
||||
WHERE related_order_code = $1
|
||||
AND operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
LIMIT 1
|
||||
FOR SHARE`,
|
||||
[code]
|
||||
);
|
||||
if (again.rowCount) {
|
||||
/**
|
||||
* **逐 SKU 幂等**(2026-10-14 审计 P0-3):先取"本单已扣过的 SKU",
|
||||
* 后面只扣**还没扣过**的行。整单守卫已废弃 —— 它会把"分拣时库存不足被软扣跳过"的 SKU 永久漏掉。
|
||||
* 仍持 `orders ... FOR UPDATE` 独占锁:并发两路(分拣完成 / 15 分钟对账)串行进入,后到者能看见先到者的流水。
|
||||
*/
|
||||
const outboundSkus = await loadOutboundStateOnClient(client, code);
|
||||
/**
|
||||
* 快路径(保留旧契约 + 省一次计划查询):**已有出库流水、且已经没有任何"有实物动作却没流水"的行**
|
||||
* ⇒ 本单无事可做,直接 `already_outbound`。
|
||||
* 注意判据是"逐 SKU 是否还有缺",不是"整单有没有流水"——后者会把分拣软扣跳过的 SKU 永久漏掉(P0-3)。
|
||||
*
|
||||
* ⚠️ 老数据里出库流水可能没有 `sku_code`(`hasAny` 为真但 SKU 集合为空)⇒ 无法逐 SKU 归因,
|
||||
* 此时**退回旧的整单语义**(宁可少扣一次,也不能凭"归因不了"再扣一遍)。
|
||||
*/
|
||||
if (
|
||||
outboundSkus.hasAny &&
|
||||
(outboundSkus.skus.size === 0 || !(await orderHasPendingOutboundOnClient(client, code)))
|
||||
) {
|
||||
if (ownsTxn) await client.query('COMMIT');
|
||||
return { deducted: false, skipped: true, reason: 'already_outbound' };
|
||||
}
|
||||
const outboundSkuSet = outboundSkus.skus;
|
||||
|
||||
const itemsResult = await client.query(
|
||||
`SELECT pi.id, pi.order_item_id, pi.pick_code, pi.item_name, pi.sku_code, pi.unit,
|
||||
@@ -503,8 +548,8 @@ export async function deductInventoryForOrderDeparture(
|
||||
});
|
||||
}
|
||||
|
||||
const deductLines = [...bestByItem.values()];
|
||||
if (!deductLines.length) {
|
||||
const allLines = [...bestByItem.values()];
|
||||
if (!allLines.length) {
|
||||
// 有明细但无实装/实拣:软模式下不拦发车(品类闸门在装车完成)
|
||||
await consumeReservationsForOrder(client, code);
|
||||
if (ownsTxn) await client.query('COMMIT');
|
||||
@@ -514,6 +559,13 @@ export async function deductInventoryForOrderDeparture(
|
||||
reason: softInventory ? 'no_settlement_qty' : 'no_loading_items',
|
||||
};
|
||||
}
|
||||
/** 逐 SKU 幂等:已扣过的行跳过,只扣"还没扣过"的(P0-3) */
|
||||
const deductLines = allLines.filter((line) => !outboundSkuSet.has(line.sku));
|
||||
if (!deductLines.length) {
|
||||
await consumeReservationsForOrder(client, code);
|
||||
if (ownsTxn) await client.query('COMMIT');
|
||||
return { deducted: false, skipped: true, reason: 'already_outbound' };
|
||||
}
|
||||
|
||||
const pickCode =
|
||||
deductLines[0].pick_code ||
|
||||
@@ -1242,11 +1294,14 @@ export async function listOrdersMissingOutboundSettlement(limit = 30): Promise<s
|
||||
SELECT 1 FROM picking_items pi
|
||||
WHERE pi.order_code = o.order_code
|
||||
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.loaded_qty, 0) > 0)
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM inventory_logs il
|
||||
WHERE il.related_order_code = o.order_code
|
||||
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
-- **逐 SKU** 判据(2026-10-14 审计 P0-3):只要还有一个 SKU 没出库流水就捞它。
|
||||
-- 原先按"整单有没有流水"判 ⇒ 分拣时被软扣跳过的 SKU 永远进不了兜底扫描。
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM inventory_logs il
|
||||
WHERE il.related_order_code = o.order_code
|
||||
AND il.sku_code = pi.sku_code
|
||||
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
)
|
||||
)
|
||||
ORDER BY o.updated_at DESC NULLS LAST
|
||||
LIMIT $1`,
|
||||
@@ -1264,7 +1319,13 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
/** 默认 `delivery_loading_out`(发车/结案口径);分拣完毕即出库传 `picking_out`(见上) */
|
||||
operationType?: 'picking_out' | 'delivery_loading_out';
|
||||
}
|
||||
): Promise<{ deducted: boolean; consumed_reservations: boolean; reason?: string }> {
|
||||
): Promise<{
|
||||
deducted: boolean;
|
||||
consumed_reservations: boolean;
|
||||
reason?: string;
|
||||
/** 软扣下因库存不足**没扣成**的行(P0-3:原先是"算了不报",调用方看不到缺口) */
|
||||
softSkipped?: Array<{ sku: string; itemName: string | null; qty: number; message: string }>;
|
||||
}> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return { deducted: false, consumed_reservations: false, reason: 'missing_order' };
|
||||
|
||||
@@ -1276,25 +1337,30 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
|
||||
let deducted = false;
|
||||
let reason: string | undefined;
|
||||
let softSkipped: Array<{ sku: string; itemName: string | null; qty: number; message: string }> = [];
|
||||
|
||||
if (!(await orderHasOutboundOnClient(client, code))) {
|
||||
const depart = await deductInventoryForOrderDeparture(code, {
|
||||
client,
|
||||
operatorId: options?.operatorId || null,
|
||||
softInventory: options?.softInventory === true,
|
||||
operationType: options?.operationType || 'delivery_loading_out',
|
||||
});
|
||||
if (depart.deducted) {
|
||||
deducted = true;
|
||||
reason = 'delivery_loading_out';
|
||||
} else {
|
||||
reason = depart.reason;
|
||||
}
|
||||
} else {
|
||||
reason = 'already_outbound';
|
||||
/**
|
||||
* **逐 SKU 幂等**(2026-10-14 审计 P0-3):不再用"整单有没有出库流水"一票否决 ——
|
||||
* 由 `deductInventoryForOrderDeparture` 内部按 SKU 跳过已扣的、补扣没扣的。
|
||||
* 整单守卫的后果是「分拣软扣跳过的 SKU 在发车/结案/兜底三处全被挡住 ⇒ 永久漏扣」。
|
||||
*/
|
||||
const depart = await deductInventoryForOrderDeparture(code, {
|
||||
client,
|
||||
operatorId: options?.operatorId || null,
|
||||
softInventory: options?.softInventory === true,
|
||||
operationType: options?.operationType || 'delivery_loading_out',
|
||||
});
|
||||
deducted = depart.deducted;
|
||||
softSkipped = depart.softSkipped || [];
|
||||
reason = depart.deducted
|
||||
? options?.operationType || 'delivery_loading_out'
|
||||
: depart.reason;
|
||||
if (softSkipped.length) {
|
||||
reason = `partial_soft_skip:${depart.reason || reason || ''}`;
|
||||
}
|
||||
|
||||
if (!(await orderHasOutboundOnClient(client, code))) {
|
||||
// 兜底:仍存在「有实物动作、却没有出库流水」的行(逐 SKU 判据)才进第二段(结案前硬扣口径)
|
||||
if (await orderHasPendingOutboundOnClient(client, code)) {
|
||||
const orderResult = await client.query(
|
||||
`SELECT branch_code FROM orders WHERE order_code = $1 FOR SHARE`,
|
||||
[code]
|
||||
@@ -1303,9 +1369,13 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
? String(orderResult.rows[0].branch_code)
|
||||
: null;
|
||||
const plan = await planDeductLinesForOrder(client, code, branchCode);
|
||||
if (plan.lines.length) {
|
||||
const outboundState = await loadOutboundStateOnClient(client, code);
|
||||
const pendingPlanLines = plan.lines.filter(
|
||||
(line) => !outboundState.skus.has(String(line.sku_code))
|
||||
);
|
||||
if (pendingPlanLines.length) {
|
||||
const soft = options?.softInventory === true;
|
||||
const short = plan.lines.filter((line) => line.available_qty + 1e-6 < line.qty);
|
||||
const short = pendingPlanLines.filter((line) => line.available_qty + 1e-6 < line.qty);
|
||||
if (short.length && !soft) {
|
||||
const msg = short
|
||||
.map(
|
||||
@@ -1319,9 +1389,10 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
// 结案补扣同样按「手选批次计划」扣(此前漏了 ⇒ 与界面/报告口径不一致)
|
||||
const settlePlanById = await loadPickItemBatchPlans(
|
||||
client,
|
||||
plan.lines.map((line) => line.pick_item_id)
|
||||
pendingPlanLines.map((line) => line.pick_item_id)
|
||||
);
|
||||
for (const line of plan.lines) {
|
||||
let settledAny = false;
|
||||
for (const line of pendingPlanLines) {
|
||||
try {
|
||||
await fifoDeductInventory(client, {
|
||||
skuCode: line.sku_code,
|
||||
@@ -1336,13 +1407,23 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
remark: `订单结案补扣出库 ${code}`,
|
||||
batchPlan: settlePlanById.get(String(line.pick_item_id || '')) || undefined,
|
||||
});
|
||||
settledAny = true;
|
||||
} catch (error: any) {
|
||||
// 软扣(骑手上门取货收口):库存不足只记缺口、不阻断收口(与发车软扣一致)
|
||||
if (soft && (error?.code === 'inventory_outbound' || error?.status === 400)) continue;
|
||||
if (soft && (error?.code === 'inventory_outbound' || error?.status === 400)) {
|
||||
softSkipped.push({
|
||||
sku: line.sku_code,
|
||||
itemName: line.item_name ?? null,
|
||||
qty: line.qty,
|
||||
message: String(error?.message || '库存不足'),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
deducted = true;
|
||||
// ⚠️ 只有**真的扣成功**才算 deducted(P0-3:原先无条件置 true ⇒ 全行软扣失败也报"补扣成功")
|
||||
if (settledAny) deducted = true;
|
||||
reason = `complete_${plan.source}`;
|
||||
}
|
||||
}
|
||||
@@ -1360,7 +1441,12 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
}
|
||||
|
||||
if (ownsTxn) await client.query('COMMIT');
|
||||
return { deducted, consumed_reservations: true, reason };
|
||||
return {
|
||||
deducted,
|
||||
consumed_reservations: true,
|
||||
reason,
|
||||
softSkipped: softSkipped.length ? softSkipped : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
if (ownsTxn) await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
|
||||
@@ -212,12 +212,26 @@ export async function tryAdvanceOrderToDelivery(orderCode: string): Promise<{ ad
|
||||
* 直送 / 本地免入库 / 极简直供 / 加菜行本就在扣库计划里被跳过(且它们没有拣货行)。
|
||||
*/
|
||||
try {
|
||||
await ensureOrderInventorySettledOnComplete(orderCode, {
|
||||
const settled = await ensureOrderInventorySettledOnComplete(orderCode, {
|
||||
softInventory: true,
|
||||
// 分拣出库口径:`picking_out` —— 发车失败回补只回补 delivery_loading_out,
|
||||
// 用 delivery_loading_out 会被它误加回来 ⇒ 后续发车又被幂等守卫挡住 ⇒ 净漏扣(见函数注释)
|
||||
operationType: 'picking_out',
|
||||
});
|
||||
/**
|
||||
* **软扣缺口必须被看见**(2026-10-14 审计 P0-3):库存不足的行不会拦「进入待配送」,
|
||||
* 但以前连日志都不留(`softSkipped` 算了没人读)⇒ 账面虚高且无人知道。
|
||||
* 现在逐行告警;这些行会在发车/结案/10 分钟兜底里按**逐 SKU 判据**继续尝试补扣
|
||||
* (`listOrdersMissingOutboundSettlement` 已改为按 SKU 判)。
|
||||
*/
|
||||
if (settled?.softSkipped?.length) {
|
||||
console.warn(
|
||||
`[picking-outbound] 分拣完毕软扣缺口 ${settled.softSkipped.length} 行(不拦进入待配送,稍后自动补扣)order=${orderCode}:`,
|
||||
settled.softSkipped
|
||||
.map((row) => `${row.sku}/${row.itemName || ''} 需${row.qty}:${row.message}`)
|
||||
.join(';')
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[picking-outbound] 分拣完毕扣库存失败(不拦进入待配送)order=${orderCode}:`,
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { getRawPoolQuery } from '../db';
|
||||
|
||||
/**
|
||||
* 启动自检必须覆盖的表。
|
||||
*
|
||||
* ⚠️ 这份名单必须与 `migrations/20260910_tenant_core_rls_on_clone.sql` +
|
||||
* `migrations/20261014_tenant_inventory_audit_rls.sql` 里 `apply_tenant_core_rls` 的
|
||||
* `core_tables` **保持一致** —— 名单漏一张,自检就会在缺 RLS 的情况下照样报
|
||||
* `[rls] tenant FORCE RLS ok`(2026-10-14 审计发现:库存审计面三张表正是这样漏掉的)。
|
||||
*/
|
||||
const CORE_TABLES = [
|
||||
'orders',
|
||||
'order_items',
|
||||
@@ -12,6 +20,10 @@ const CORE_TABLES = [
|
||||
'purchase_orders',
|
||||
'supplier_preparations',
|
||||
'inventory',
|
||||
// 2026-10-14:库存审计面(审计 P0-2)
|
||||
'inventory_reservations',
|
||||
'picking_items',
|
||||
'picking_tasks',
|
||||
] as const;
|
||||
|
||||
export type TenantRlsStatus = {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
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',");
|
||||
});
|
||||
|
||||
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 逐项对齐', () => {
|
||||
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'];
|
||||
for (const t of tables) {
|
||||
expect(migration, `迁移缺 ${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);
|
||||
});
|
||||
});
|
||||
@@ -36,9 +36,10 @@ describe('分拣完毕即出库扣库存', () => {
|
||||
expect(src.slice(settleIdx, settleIdx + 400)).toContain("operationType: 'picking_out'");
|
||||
expect(pickingPathReturnIdx).toBeGreaterThan(-1);
|
||||
expect(settleIdx).toBeLessThan(pickingPathReturnIdx);
|
||||
// 失败只告警、不拦进入待配送(软扣纪律)
|
||||
const around = src.slice(settleIdx - 600, settleIdx + 400);
|
||||
// 失败只告警、不拦进入待配送(软扣纪律);2026-10-14 起同处还要把软扣缺口打进日志
|
||||
const around = src.slice(settleIdx - 900, settleIdx + 900);
|
||||
expect(around).toContain('不拦进入待配送');
|
||||
expect(around).toContain('softSkipped');
|
||||
});
|
||||
|
||||
it('② 核货差额不回补:发车/结案再扣时靠 already_outbound 守卫短路', () => {
|
||||
|
||||
@@ -67,8 +67,12 @@ describe('结案补扣:软扣语义(不足不抛、逐行容错)', () => {
|
||||
it('软扣时「计划补扣」分支不因缺口抛错,且逐行容错', () => {
|
||||
expect(outbound).toContain('const soft = options?.softInventory === true;');
|
||||
expect(outbound).toContain('if (short.length && !soft)');
|
||||
// 2026-10-14(P0-3):软扣跳过的行不再"算了不报",改为记入 softSkipped 上抛 + 日志;
|
||||
// 语义不变:软扣下库存缺口不抛错、逐行容错、且只有真扣成功才置 deducted。
|
||||
expect(outbound).toContain(
|
||||
"if (soft && (error?.code === 'inventory_outbound' || error?.status === 400)) continue;"
|
||||
"if (soft && (error?.code === 'inventory_outbound' || error?.status === 400)) {"
|
||||
);
|
||||
expect(outbound).toContain('softSkipped.push({');
|
||||
expect(outbound).toContain('if (settledAny) deducted = true;');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user