一、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。
165 lines
7.3 KiB
TypeScript
165 lines
7.3 KiB
TypeScript
/**
|
||
* 修复:**已结案订单的历史出库缺口**(2026-10-14 多 agent 审计 P1-4)。
|
||
*
|
||
* 背景:`runOutboundSettleBackfill`(10 分钟兜底)按设计只扫 `order_status BETWEEN 50 AND 89`
|
||
* —— 已结案(90)的单**永远够不到**。而 2026-10-13 之前那批单(出库留痕 SQL 报 `p.name` 不存在,
|
||
* 把整个扣库事务 abort)货已随配送交付、库存却从未扣减,真库存量:
|
||
* `ORD_API_20261012_BR003_0002`(90 状态、4 行、29 斤、出库流水 0)。
|
||
*
|
||
* 因此这里给一个**显式、可审计、幂等**的人工出口(不改兜底窗口——90 状态的历史单属冻结范围,
|
||
* 是否自动重扫是产品决定,不由脚本擅自扩大):
|
||
* · 默认 **dry-run**:只列出「已结案 + 有实物动作 + 该 SKU 无出库流水」的行与可用库存;
|
||
* · `--apply` 才真扣:复用既有出库口径(FIFO + 批次行锁 + 手选批次计划 + 流水 + 幂等守卫),
|
||
* 走 `ensureOrderInventorySettledOnComplete({ operationType: 'picking_out' })`(**逐 SKU 判据**,只补缺的);
|
||
* · 审计留痕由扣库路径自己写(`operation_logs.operation_type='picking_outbound'`,含逐批次明细),
|
||
* 本脚本不重复写,避免造出无操作人的噪声行。
|
||
* · 幂等:补过的 SKU 有流水,再跑不会被选中。
|
||
*
|
||
* 用法:
|
||
* cd server && npx tsx --env-file=.env scripts/repair-closed-order-outbound-gap.ts # 干跑全部已登记分公司
|
||
* cd server && npx tsx --env-file=.env scripts/repair-closed-order-outbound-gap.ts BR003 # 指定分公司
|
||
* cd server && npx tsx --env-file=.env scripts/repair-closed-order-outbound-gap.ts --apply BR003
|
||
* cd server && npx tsx --env-file=.env scripts/repair-closed-order-outbound-gap.ts --apply --order=ORD_X
|
||
*/
|
||
import { pool } from '../src/db';
|
||
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
|
||
import { ensureOrderInventorySettledOnComplete } from '../src/services/inventoryOutboundService';
|
||
|
||
const APPLY = process.argv.includes('--apply');
|
||
const ORDER_FILTER = process.argv
|
||
.filter((a) => a.startsWith('--order='))
|
||
.map((a) => a.slice('--order='.length).trim())
|
||
.filter(Boolean);
|
||
const BRANCH_ARGS = process.argv.filter((a) => /^BR\d+$/i.test(a)).map((a) => a.toUpperCase());
|
||
const ACTOR = '1c4d09fd-6bb5-46da-b1a5-90f9ae67b8e0';
|
||
|
||
type GapLine = {
|
||
sku_code: string;
|
||
item_name: string | null;
|
||
qty: number;
|
||
available_qty: number;
|
||
};
|
||
|
||
/** 已结案(≥90) 且仍有「有实物动作、却无出库流水」的行的单(逐 SKU 判据,与兜底同口径) */
|
||
async function listClosedOrderGaps(): Promise<
|
||
Array<{ order_code: string; order_status: number; lines: GapLine[] }>
|
||
> {
|
||
const rows = await pool.query<{
|
||
order_code: string;
|
||
order_status: number;
|
||
sku_code: string;
|
||
item_name: string | null;
|
||
qty: string;
|
||
available_qty: string;
|
||
}>(
|
||
`SELECT o.order_code, o.order_status, pi.sku_code, pi.item_name,
|
||
GREATEST(COALESCE(pi.loaded_qty, 0), COALESCE(pi.picked_qty, 0))::numeric AS qty,
|
||
COALESCE((
|
||
SELECT SUM(inv.available_qty) FROM inventory inv
|
||
WHERE inv.sku_code = pi.sku_code AND inv.available_qty > 0
|
||
), 0)::numeric AS available_qty
|
||
FROM orders o
|
||
JOIN picking_items pi ON pi.order_code = o.order_code
|
||
WHERE o.deleted_at IS NULL
|
||
AND o.order_status >= 90
|
||
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.sku_code = pi.sku_code
|
||
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
|
||
)
|
||
${ORDER_FILTER.length ? 'AND o.order_code = ANY($1::text[])' : ''}
|
||
ORDER BY o.order_code, pi.sku_code`,
|
||
ORDER_FILTER.length ? [ORDER_FILTER] : []
|
||
);
|
||
|
||
const byOrder = new Map<string, { order_code: string; order_status: number; lines: GapLine[] }>();
|
||
for (const row of rows.rows) {
|
||
const key = String(row.order_code);
|
||
const bucket =
|
||
byOrder.get(key) || { order_code: key, order_status: Number(row.order_status) || 0, lines: [] };
|
||
bucket.lines.push({
|
||
sku_code: String(row.sku_code || ''),
|
||
item_name: row.item_name ? String(row.item_name) : null,
|
||
qty: Number(row.qty) || 0,
|
||
available_qty: Number(row.available_qty) || 0,
|
||
});
|
||
byOrder.set(key, bucket);
|
||
}
|
||
return [...byOrder.values()];
|
||
}
|
||
|
||
async function resolveBranches(): Promise<string[]> {
|
||
if (BRANCH_ARGS.length) return BRANCH_ARGS;
|
||
const r = await pool.query<{ branch_code: string }>(
|
||
`SELECT branch_code FROM public.branches ORDER BY branch_code`
|
||
);
|
||
return r.rows.map((row) => String(row.branch_code)).filter(Boolean);
|
||
}
|
||
|
||
async function main() {
|
||
const branches = await resolveBranches();
|
||
let totalOrders = 0;
|
||
let totalApplied = 0;
|
||
|
||
for (const branch of branches) {
|
||
await runWithTenantDbContext(branch, async () => {
|
||
const gaps = await listClosedOrderGaps();
|
||
console.log(`\n════════ ${branch}:已结案缺口 ${gaps.length} 张单 ════════`);
|
||
for (const gap of gaps) {
|
||
const qty = gap.lines.reduce((sum, line) => sum + line.qty, 0);
|
||
const shortLines = gap.lines.filter((line) => line.available_qty + 1e-6 < line.qty);
|
||
console.log(
|
||
` ${gap.order_code}(状态 ${gap.order_status})待扣 ${qty} 斤 / ${gap.lines.length} 行` +
|
||
(shortLines.length ? ` ⚠️ 其中 ${shortLines.length} 行库存不足` : ' ✅ 库存充足')
|
||
);
|
||
for (const line of gap.lines) {
|
||
console.log(
|
||
` ${line.sku_code} ${line.item_name || ''} 应扣 ${line.qty},可用 ${line.available_qty}`
|
||
);
|
||
}
|
||
totalOrders += 1;
|
||
if (!APPLY) continue;
|
||
|
||
try {
|
||
const result = await ensureOrderInventorySettledOnComplete(gap.order_code, {
|
||
operatorId: ACTOR,
|
||
// 与分拣口径一致:这批货是分拣时就离仓的
|
||
operationType: 'picking_out',
|
||
});
|
||
const logs = await pool.query<{ n: string }>(
|
||
`SELECT COUNT(*)::text AS n FROM inventory_logs
|
||
WHERE related_order_code = $1 AND operation_type IN ('picking_out', 'delivery_loading_out')`,
|
||
[gap.order_code]
|
||
);
|
||
console.log(
|
||
` → 补扣结果 deducted=${result.deducted} reason=${result.reason || ''} ` +
|
||
`软扣缺口=${result.softSkipped?.length || 0} 现有出库流水=${logs.rows[0]?.n}`
|
||
);
|
||
console.log(
|
||
` → 审计留痕:operation_logs(picking_outbound, ${gap.order_code}) 已由扣库路径写入`
|
||
);
|
||
if (result.deducted) totalApplied += 1;
|
||
} catch (error) {
|
||
console.error(
|
||
` → ❌ 补扣失败(未改动):${(error as Error)?.message || error}`
|
||
);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
console.log(
|
||
`\n${APPLY ? '已执行' : '干跑(未改数据)'}:命中 ${totalOrders} 张单,补扣成功 ${totalApplied} 张。` +
|
||
(APPLY ? '' : '\n确认无误后加 `--apply` 执行(幂等,可重复跑)。')
|
||
);
|
||
await pool.end();
|
||
}
|
||
|
||
main().catch(async (error) => {
|
||
console.error('[repair-closed-order-outbound-gap] 失败:', error);
|
||
await pool.end();
|
||
process.exit(1);
|
||
});
|