Files
SupplierSystem/server/scripts/repair-holding-cycle-code.ts
T
Ubuntu b9774bc451 feat(库存审计面): P0-2b 台账 RLS + P1-4 历史缺口收口 + P1-5 账期口径修复
一、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。
2026-10-14 11:16:25 +08:00

90 lines
3.6 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.
/**
* 修复:**账外持有成本的账期口径**(2026-10-14 多 agent 审计 P1-5 第三处)。
*
* 背景:`cost_details.cycle_code` 是**账期**(产品侧 `currentCycleCodeChina()` = `YYYYMM`,如 `202610`)。
* 但 2026-10-13 那批修复脚本写成了 `YYYYMMDD`(`new Date().toISOString().slice(0,10)`),
* 真库 BR003 实测:`inventory_holding` 里 9 行 / **¥1,146.90** 落在 `20261013`,占桶余额 91%
* ⇒ 按账期(`cycle_code='202610'`)取数时这块账外持有**整块看不见**,跨月对账与净利都少一块。
* 脚本本身的写法已在同一次改动里修正(改用 `currentCycleCodeChina()`),本脚本负责**存量数据**。
*
* 口径:把 `inventory_holding` 里形如 8 位日期的 `cycle_code` 改写成该行 `created_at`
* (Asia/Shanghai)所属的 `YYYYMM`。只动这一种形态,其它值(`202610` / 业务自定义)一律不碰。
*
* 用法(默认干跑):
* cd server && npx tsx --env-file=.env scripts/repair-holding-cycle-code.ts
* cd server && npx tsx --env-file=.env scripts/repair-holding-cycle-code.ts --apply
* cd server && npx tsx --env-file=.env scripts/repair-holding-cycle-code.ts --apply BR002 BR003
*/
import { pool } from '../src/db';
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
const APPLY = process.argv.includes('--apply');
const BRANCH_ARGS = process.argv.filter((a) => /^BR\d+$/i.test(a)).map((a) => a.toUpperCase());
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 totalRows = 0;
let totalAmount = 0;
for (const branch of branches) {
await runWithTenantDbContext(branch, async () => {
const bad = await pool.query<{
cycle_code: string;
n: string;
amount: string;
target: string;
}>(
`SELECT cycle_code,
COUNT(*)::text AS n,
COALESCE(SUM(amount), 0)::text AS amount,
to_char((MIN(created_at) AT TIME ZONE 'Asia/Shanghai'), 'YYYYMM') AS target
FROM cost_details
WHERE cost_type = 'inventory_holding'
AND cycle_code ~ '^[0-9]{8}$'
GROUP BY cycle_code
ORDER BY cycle_code`
);
if (!bad.rowCount) {
console.log(`${branch}: 无需修复(无 8 位日期形态的账期)`);
return;
}
for (const row of bad.rows) {
console.log(
`${branch}: cycle_code=${row.cycle_code} → ${row.target}(${row.n} 行 / ¥${row.amount})`
);
totalRows += Number(row.n) || 0;
totalAmount += Number(row.amount) || 0;
}
if (!APPLY) return;
const updated = await pool.query(
`UPDATE cost_details
SET cycle_code = to_char((created_at AT TIME ZONE 'Asia/Shanghai'), 'YYYYMM')
WHERE cost_type = 'inventory_holding'
AND cycle_code ~ '^[0-9]{8}$'`
);
console.log(`${branch}: 已改写 ${updated.rowCount} 行`);
});
}
console.log(
`\n${APPLY ? '已执行' : '干跑(未改数据)'}:命中 ${totalRows} 行 / ¥${totalAmount.toFixed(2)}。` +
(APPLY ? '' : '\n确认无误后加 `--apply` 执行(幂等)。')
);
await pool.end();
}
main().catch(async (error) => {
console.error('[repair-holding-cycle-code] 失败:', error);
await pool.end();
process.exit(1);
});