一、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。
186 lines
8.8 KiB
TypeScript
186 lines
8.8 KiB
TypeScript
/**
|
||
* 冲销脚本:抵扣成本"多记一遍"的纠正(2026-10-13 真库缺陷的存量部分)。
|
||
*
|
||
* 背景:`applyStockCoverForOrderItem` 之前把**累计** `cover` 传给成本结转
|
||
* (应传增量),于是补齐抵扣时会把已结转的部分再结转一次。真库实例
|
||
* `ORD_API_20261013_BR003_0003`(4 行全额抵扣后):
|
||
* 苹果 记 513.00(正确 30×11.10 = 333.00,多 180.00)
|
||
* 抄手皮 记 127.20(正确 8×9.90 = 79.20,多 48.00)
|
||
* 土豆 记 69.00(正确 10×2.30 = 23.00,多 46.00)
|
||
* ⇒ 多记合计 ¥274.00,且这笔钱是从**账外持有桶**多取的。
|
||
*
|
||
* 纠正:把该单该 SKU 的抵扣成本改成"FIFO 第一批单价 × 当前抵扣量"(与首次结转同口径),
|
||
* 多记部分**退回账外持有桶**。只处理「当前抵扣量 ≤ FIFO 第一批在库量」的行(可精确折算),
|
||
* 其余只报告。幂等(改完后 posted == correct,不再命中)。
|
||
*
|
||
* 用法:默认 dry-run;`--apply` 执行。
|
||
*/
|
||
import { pool } from '../src/db';
|
||
import { currentCycleCodeChina } from '../src/services/fixedCostService';
|
||
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
|
||
import { upsertInventoryHoldingCost } from '../src/services/inventorySurplusCostService';
|
||
import { writeAuditLog } from '../src/services/auditService';
|
||
|
||
const BRANCH = process.argv.find((a) => /^BR\d+$/.test(a)) || 'BR003';
|
||
const APPLY = process.argv.includes('--apply');
|
||
/**
|
||
* ⚠️ **必须显式圈定订单**:本脚本的"应记金额 = 当前抵扣量 × FIFO 首批单价"只对
|
||
* 「成本是本次抵扣写的、且抵扣量与成本同源」的行成立。历史行可能是
|
||
* 「先抵扣 15 斤、后来行量缩到 3 斤」(成本没跟着退)或旧实现"按 SKU 冲别的批次"的产物,
|
||
* 用本判据去改它们会把**没多记的也当多记**。所以默认只报告、不动手,
|
||
* 要动必须点名订单:`--order=ORD_xxx`(可重复)。
|
||
*/
|
||
const ORDER_FILTER = process.argv
|
||
.filter((a) => a.startsWith('--order='))
|
||
.map((a) => a.slice('--order='.length).trim())
|
||
.filter(Boolean);
|
||
const ACTOR = '1c4d09fd-6bb5-46da-b1a5-90f9ae67b8e0';
|
||
const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100;
|
||
|
||
async function main() {
|
||
await runWithTenantDbContext(BRANCH, async () => {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query(`SET search_path TO tenant_${BRANCH.toLowerCase()}, public`);
|
||
await client.query(`SELECT set_config('app.branch_code', $1, false)`, [BRANCH]);
|
||
|
||
const rows = await client.query<{
|
||
order_code: string;
|
||
sku_code: string;
|
||
posted: string;
|
||
row_count: string;
|
||
cover_qty: string;
|
||
batch_no: string | null;
|
||
batch_cost: string | null;
|
||
batch_qty: string | null;
|
||
}>(
|
||
`SELECT cd.order_code,
|
||
cd.sku_code,
|
||
ROUND(SUM(cd.amount)::numeric, 2) AS posted,
|
||
COUNT(*) AS row_count,
|
||
MAX(COALESCE(oi.stock_cover_qty, 0))::numeric AS cover_qty,
|
||
(SELECT i.batch_no FROM inventory i
|
||
WHERE i.sku_code = cd.sku_code AND COALESCE(i.available_qty, 0) > 0
|
||
ORDER BY i.created_at ASC LIMIT 1) AS batch_no,
|
||
(SELECT i.cost_price::numeric FROM inventory i
|
||
WHERE i.sku_code = cd.sku_code AND COALESCE(i.available_qty, 0) > 0
|
||
ORDER BY i.created_at ASC LIMIT 1) AS batch_cost,
|
||
(SELECT i.available_qty::numeric FROM inventory i
|
||
WHERE i.sku_code = cd.sku_code AND COALESCE(i.available_qty, 0) > 0
|
||
ORDER BY i.created_at ASC LIMIT 1) AS batch_qty
|
||
FROM cost_details cd
|
||
JOIN orders o ON o.order_code = cd.order_code AND o.deleted_at IS NULL
|
||
LEFT JOIN order_items oi ON oi.order_code = cd.order_code AND oi.sku_code = cd.sku_code
|
||
WHERE cd.cost_source = 'inventory_cover'
|
||
GROUP BY cd.order_code, cd.sku_code
|
||
ORDER BY cd.order_code, cd.sku_code`
|
||
);
|
||
|
||
console.log('=== 抵扣成本增量核对 ===');
|
||
let totalExcess = 0;
|
||
const plan: Array<{ order: string; sku: string; posted: number; correct: number; excess: number }> = [];
|
||
for (const row of rows.rows) {
|
||
const posted = round2(Number(row.posted));
|
||
const coverQty = Number(row.cover_qty) || 0;
|
||
const batchQty = row.batch_qty === null ? null : Number(row.batch_qty);
|
||
const batchCost = row.batch_cost === null ? null : Number(row.batch_cost);
|
||
if (!coverQty || batchCost === null || batchQty === null) {
|
||
console.log(` ${row.order_code} ${row.sku_code}:抵扣 ${posted}(抵扣量 ${coverQty})—— 信息不足,跳过`);
|
||
continue;
|
||
}
|
||
if (coverQty > batchQty + 1e-9) {
|
||
console.log(
|
||
` ${row.order_code} ${row.sku_code}:抵扣 ${posted},抵扣量 ${coverQty} > 首批在库 ${batchQty} ⇒ 跨批次,跳过`
|
||
);
|
||
continue;
|
||
}
|
||
const correct = round2(coverQty * batchCost);
|
||
const excess = round2(posted - correct);
|
||
console.log(
|
||
` ${row.order_code} ${row.sku_code}:记 ${posted},应记 ${correct}` +
|
||
`(${coverQty} × FIFO首批 ${row.batch_no} ¥${batchCost})` +
|
||
(excess > 0.005 ? ` ⇒ **多记 ¥${excess}**` : ' ✅')
|
||
);
|
||
const inScope = ORDER_FILTER.length === 0 ? false : ORDER_FILTER.includes(String(row.order_code));
|
||
if (excess > 0.005 && Number(row.row_count) === 1 && inScope) {
|
||
plan.push({ order: String(row.order_code), sku: String(row.sku_code), posted, correct, excess });
|
||
totalExcess = round2(totalExcess + excess);
|
||
}
|
||
}
|
||
|
||
const reported = round2(
|
||
rows.rows.reduce((acc, row) => {
|
||
const posted = round2(Number(row.posted));
|
||
const coverQty = Number(row.cover_qty) || 0;
|
||
const batchCost = row.batch_cost === null ? null : Number(row.batch_cost);
|
||
const batchQty = row.batch_qty === null ? null : Number(row.batch_qty);
|
||
if (!coverQty || batchCost === null || batchQty === null) return acc;
|
||
if (coverQty > batchQty + 1e-9) return acc;
|
||
const excess = round2(posted - round2(coverQty * batchCost));
|
||
return excess > 0.005 ? round2(acc + excess) : acc;
|
||
}, 0)
|
||
);
|
||
console.log(
|
||
`\n点名订单内合计需退回:¥${totalExcess}` +
|
||
(reported !== totalExcess
|
||
? `;其余 ${ORDER_FILTER.length ? '未点名' : '全部'}行差额合计 ¥${round2(reported - totalExcess)} 只报告、不动(历史口径差异,需另案核对)`
|
||
: '')
|
||
);
|
||
if (!APPLY || !plan.length) {
|
||
console.log(APPLY ? '(无需处理)' : '(dry-run;加 --apply 执行)');
|
||
return;
|
||
}
|
||
|
||
// 账期口径 = YYYYMM(Asia/Shanghai),与产品侧 currentCycleCodeChina 一致。
|
||
// ⚠️ 2026-10-14 修:原先写的是 YYYYMMDD ⇒ 按账期(202610)取数时这块账外持有整块看不见
|
||
// (真库 BR003 实测 9 行 / ¥1,146.90,占桶余额 91%)。见 docs/design/20261014-成本口径对齐.md
|
||
const cycleCode = currentCycleCodeChina();
|
||
for (const item of plan) {
|
||
await client.query(
|
||
`UPDATE cost_details
|
||
SET amount = $3,
|
||
remark = COALESCE(remark, '') || ';[修复] 抵扣成本多记冲销 ¥' || $4::text
|
||
WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`,
|
||
[item.order, item.sku, item.correct, item.excess]
|
||
);
|
||
await upsertInventoryHoldingCost(client, {
|
||
cycleCode,
|
||
branchCode: BRANCH,
|
||
skuCode: item.sku,
|
||
amount: item.excess,
|
||
referenceId: `cover-overpost-revert:${item.order}:${item.sku}`,
|
||
costSource: 'cover_revert',
|
||
referenceType: 'cover_overpost_revert',
|
||
costSubtype: 'cover_overpost_revert',
|
||
remarkPrefix: `抵扣成本多记冲销(单 ${item.order})`,
|
||
operatorId: ACTOR,
|
||
});
|
||
await writeAuditLog({
|
||
operatorId: ACTOR,
|
||
operatorRole: 'admin',
|
||
operationType: 'cover_cost_overpost_revert',
|
||
targetTable: 'cost_details',
|
||
targetId: `${item.order}|${item.sku}`,
|
||
oldValue: { posted: item.posted },
|
||
newValue: { corrected: item.correct, returned_to_holding: item.excess },
|
||
actionCategory: 'finance',
|
||
branchCode: BRANCH,
|
||
}).catch(() => undefined);
|
||
console.log(` 已纠正 ${item.order} ${item.sku}:${item.posted} → ${item.correct}(退回 ¥${item.excess})`);
|
||
}
|
||
console.log(`已退回账外持有 ¥${totalExcess}`);
|
||
} finally {
|
||
client.release();
|
||
}
|
||
});
|
||
await pool.end();
|
||
}
|
||
|
||
main().then(
|
||
() => process.exit(0),
|
||
(error) => {
|
||
console.error('FAILED', error);
|
||
process.exit(1);
|
||
}
|
||
);
|