Files
SupplierSystem/server/scripts/repair-misbound-cover-sku.ts
T
Ubuntu f3bdd94ffb
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(加工口径): 修「二刀肉被改绑到糯玉米棒」的存量错映射 + 记录开发者第二轮澄清
一、存量修复(开发者批准「甲」):新增 server/scripts/repair-misbound-cover-sku.ts(默认干跑)
  现场:改绑弹窗在 14:13:01 写下别名 customer_sku_aliases(MAIN_BR002,'二刀肉') → SKU94157921772,
  而该 SKU 主数据是**糯玉米棒** ⇒ ORD_API_20261014_BR002_0002 的二刀肉行被绑到糯玉米棒并抵扣 5 斤。
  脚本只动**行名 == 别名**的行(不碰"本来就用这个 SKU"的行,如 ORD_WEB_..._0002 的米糯玉米棒)。
  改前 → 改后(实测):
    别名 MAIN_BR002/二刀肉          1 条 → 0 条
    该行 sku_code                   SKU94157921772 → SKU94149529222(二刀肉)
    该行 stock_cover_qty            5 斤 → 0
    该(订单×SKU94149529222)cover成本 ¥30.00 → ¥0.00(已作废)
  成本行粒度只到(订单×SKU)⇒ 同单同 SKU 有别的活行时不整体作废(打印告警留人工)。

二、设计文补「开发者第二轮澄清」并据此修正口径:
  D1 澄清原话:「成品就是我们的加工的商品…我选择了仓内加工后 先去领取仓库的土豆 然后加工好
  然后我们的去皮土豆丝入库 记录数量 回写成本价 待分拣」⇒ 成品不需另定义,由加工流程产出并入库;
  由此 N3 的结论改为"加工产出尚未入库",「只列成品 SKU」顺延到加工产出可入库之后再落。
  D2 澄清原话:「不需要新增一列了 相当于配送系统的加工方式 +备注 一起放到我们的订单详情的备注里面就行」
  ⇒ ①由"加列"改为"导入时把 processingMethod + 其备注并入商品行备注",**零新增文案**。
  仍待确认:D2'「是否加工」控件形态(复用现有两态按钮 vs 改三态,后者需 2 个新标签)、
  D2'' processingLocked 现值「以主系统为准」与新口径相反需改措辞或删。

门禁:run-all.sh --verify 8 通过 / 1 已知红(check-ai-cost) / 1 未执行,与基线一致。
2026-10-14 15:13:16 +08:00

150 lines
7.0 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.
/**
* 修复:**「选择抵扣商品」把某行改绑到了不相干的 SKU**(2026-10-14 真库事故)。
*
* 现场(`tenant_br002` / `ORD_API_20261014_BR002_0002`):
* · 订单行 `二刀肉` 的 `sku_code` 被改成 `SKU94157921772`,而该 SKU 的主数据是 **糯玉米棒**;
* · 改绑弹窗同时写下别名 `customer_sku_aliases(MAIN_BR002, '二刀肉') → SKU94157921772`
* —— 别名一旦存在会**长期自动复用**(下次同名商品还绑到糯玉米棒);
* · 该行 `stock_cover_qty=5`、并按 `二刀肉`(SKU94149529222) 结了 **¥30** 抵扣成本 ⇒
* 行指向糯玉米棒、账面却挂在二刀肉,字形/账形不一致。
*
* 本脚本做三件事(只动**行名 == 别名**的行,绝不动"本来就用这个 SKU"的行):
* ① 删掉错别名 `(customer_code, alias_name) → wrong_sku`;
* ② 把受影响行的 `sku_code` 改回 `right_sku`;
* ③ 撤销这些行的库存抵扣:`stock_cover_qty=0` + 释放预留(含清批次计划)+ 作废该(订单×SKU)的
* `inventory_cover` 成本行。
* ⚠️ 成本行粒度只到(订单×SKU)⇒ **同单同 SKU 还有别的活行时不整体作废**(打印告警,留人工)。
*
* 用法:
* cd server
* npx tsx --env-file=.env scripts/repair-misbound-cover-sku.ts # 干跑(默认 BR002 现场参数)
* npx tsx --env-file=.env scripts/repair-misbound-cover-sku.ts --apply
* # 参数可覆盖:<BRxxx> --alias=二刀肉 --wrong=SKU94157921772 --right=SKU94149529222
*
* 幂等:别名删掉、`sku_code` 改回、抵扣归零后判据不再命中 ⇒ 重跑无动作。
* 回滚:脚本逐行打印改前值(含成本行金额);回滚 = 恢复别名 + `sku_code` 改回 `wrong_sku`
* + 需要时由业务重新抵扣一次(成本按批次价重算)。
*/
import { pool } from '../src/db';
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
const APPLY = process.argv.includes('--apply');
const arg = (name: string, fallback: string) => {
const hit = process.argv.find((a) => a.startsWith(`--${name}=`));
return hit ? hit.split('=').slice(1).join('=') : fallback;
};
const BRANCH = (process.argv.filter((a) => /^BR\d+$/i.test(a)).map((a) => a.toUpperCase())[0]) || 'BR002';
const ALIAS_NAME = arg('alias', '二刀肉');
const WRONG_SKU = arg('wrong', 'SKU94157921772');
const RIGHT_SKU = arg('right', 'SKU94149529222');
const CUSTOMER_CODE = arg('customer', 'MAIN_BR002');
const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100;
type Row = {
id: string;
order_code: string;
item_name: string | null;
sku_code: string;
stock_cover_qty: number;
unit: string | null;
};
async function main(): Promise<void> {
const { releaseReservationsForOrderItem, voidInventoryCoverCostsForOrderSku, hasLiveSiblingRowForSku } =
await import('../src/services/inventoryStockCoverService');
console.log(
`\n模式:${APPLY ? '**执行**(写库)' : '干跑(不改数据)'}\n` +
`分公司 ${BRANCH}|别名 ${CUSTOMER_CODE}/${ALIAS_NAME} 现状指向 ${WRONG_SKU},应改回 ${RIGHT_SKU}`
);
await runWithTenantDbContext(BRANCH, async () => {
// ① 错别名
const alias = await pool.query<{ customer_code: string; sku_code: string; created_at: Date }>(
`SELECT customer_code, sku_code, created_at FROM customer_sku_aliases
WHERE customer_code = $1 AND alias_name = $2`,
[CUSTOMER_CODE, ALIAS_NAME]
);
console.log(`\n① 别名:命中 ${alias.rowCount} 条`);
for (const a of alias.rows) {
console.log(
` ${a.customer_code} / ${ALIAS_NAME} → ${a.sku_code}(建于 ${a.created_at?.toISOString?.() ?? a.created_at})` +
(a.sku_code === WRONG_SKU ? ' ⇒ 待删' : ' ⇒ 不是目标 SKU,跳过')
);
}
// ② 受影响的行:**行名 == 别名** 且当前绑着 wrong_sku(不碰"本来就用这个 SKU"的行)
const rows = await pool.query<Row>(
`SELECT id::text AS id, order_code, item_name, sku_code,
COALESCE(stock_cover_qty, 0)::float AS stock_cover_qty, unit
FROM order_items
WHERE item_name = $1 AND sku_code = $2
ORDER BY order_code`,
[ALIAS_NAME, WRONG_SKU]
);
console.log(`\n② 受影响的行:命中 ${rows.rowCount} 行`);
if (!rows.rowCount) {
console.log(' (无 —— 可能已修过)');
}
for (const row of rows.rows) {
const coverCost = await pool.query<{ total: number }>(
`SELECT COALESCE(SUM(amount), 0)::float AS total FROM cost_details
WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`,
[row.order_code, RIGHT_SKU]
);
const costTotal = round2(Number(coverCost.rows[0]?.total) || 0);
const liveSibling = await hasLiveSiblingRowForSku(pool as never, {
orderCode: row.order_code,
skuCode: RIGHT_SKU,
excludeItemId: row.id,
});
console.log(
`\n ${row.order_code}|${row.item_name}|${row.id}\n` +
` 现在:sku=${row.sku_code},抵扣量=${row.stock_cover_qty}${row.unit || ''}\n` +
` 应改:sku=${RIGHT_SKU};撤销抵扣(归零 + 释放预留 + 作废 ${RIGHT_SKU} 的抵扣成本 ¥${costTotal.toFixed(2)})` +
(liveSibling ? '\n ⚠️ 同单同 SKU 还有别的活行 ⇒ 成本行**不整体作废**,留人工' : '')
);
if (!APPLY) continue;
await pool.query(`UPDATE order_items SET sku_code = $2, stock_cover_qty = 0 WHERE id = $1::uuid`, [
row.id,
RIGHT_SKU,
]);
await releaseReservationsForOrderItem(pool as unknown as never, row.id);
if (!liveSibling && costTotal > 0) {
await voidInventoryCoverCostsForOrderSku(pool as never, {
orderCode: row.order_code,
skuCode: RIGHT_SKU,
remark: '改绑到不相干 SKU 的存量修复:撤销该行抵扣成本',
});
}
console.log(` → ✅ 已修(sku→${RIGHT_SKU}、抵扣归零、预留已释放${!liveSibling && costTotal > 0 ? '、成本已作废' : ''})`);
}
// ③ 删别名(放在行修好之后,避免中途失败留下"行没改、别名已删")
const wrongAliases = alias.rows.filter((a) => a.sku_code === WRONG_SKU);
if (APPLY && wrongAliases.length) {
const del = await pool.query(`DELETE FROM customer_sku_aliases WHERE customer_code = $1 AND alias_name = $2`, [
CUSTOMER_CODE,
ALIAS_NAME,
]);
console.log(`\n③ 已删错别名 ${del.rowCount} 条(${CUSTOMER_CODE}/${ALIAS_NAME})`);
} else if (wrongAliases.length) {
console.log(`\n③ 待删错别名 ${wrongAliases.length} 条(加 --apply 执行)`);
}
});
console.log(
`\n${APPLY ? '已执行' : '干跑(未改数据)'}。` +
(APPLY ? '' : '\n确认无误后加 `--apply`(幂等)。')
);
await pool.end();
}
main().catch(async (error) => {
console.error('[repair-misbound-cover-sku] 失败:', error);
await pool.end();
process.exit(1);
});