/** * 一次性对齐:主系统「备货商品名」口径修正(主系统 `d304652f`,2026-10-14)之后, * 把我方**按旧名自动建档**的商品改成**档案名**,并把旧名写成**客户别名**(防止再建重复档案)。 * * 背景(真库 BR002 `ORD_API_20261014_BR002_0001`): * 主系统列表接口原取「备货行名」(`sp.item_name`)⇒ 传给我们的是 细的粉丝 / 生抽 / 豆瓣酱 / 黑胡椒汁; * 我们导入时没有别名映射,就按**传入的名字**自动建了 5 个 SKU。主系统已改成「档案名优先」, * 但**存量不会自愈**:下次导入带「粉丝」进来时,`findProductByName` 严格同名匹配 ⇒ 找不到 * 细的粉丝 ⇒ **新建第二个档案**(同一商品两个 SKU:库存/抵扣/成本各认各的)。 * * 本脚本做两件事(**只这两件**): * 1. 改名:`product_catalog.name` → 档案名(触发器 `sync_product_catalog_to_legacy` 同步 `skus.sku_name`; * 这里**两张表都显式写一次**,不依赖触发器存在) * 2. 旧名留客户别名:对**引用了该 SKU 的每个客户**写 `customer_sku_aliases`(旧名 → 该 SKU), * 与 `mainSystemItemSkuMappingService.upsertItemSkuAlias` 同一 ON CONFLICT 约定 * * 不动:订单行 `order_items.item_name`(历史单仍显示当时的名字)、成本、库存、绑定、任何金额。 * * 幂等:旧名找不到(已改过)⇒ 跳过;目标名已存在 ⇒ 跳过并告警(**不合并、不覆盖**)。 * 别名部分即使已改名也会补写(按目标名反查)。 * * 用法(**默认 dry-run,不写库**): * npx tsx --env-file=.env scripts/align-prep-sku-names.ts # 预览全部分公司 * npx tsx --env-file=.env scripts/align-prep-sku-names.ts --branch=BR002 # 只看一个分公司 * npx tsx --env-file=.env scripts/align-prep-sku-names.ts --apply # 落库 * * ⚠️ 生产库执行必须由开发者明确下令(见 AGENTS.md「未经直接命令不得部署」)。 */ import type { PoolClient } from 'pg'; import { pool } from '../src/db'; import { runWithTenantDataAccess } from '../src/services/tenantSchemaService'; /** 主系统档案名(`skus.sku_name`)与我们导入时用的备货行名 */ const MAPPING: Array<{ from: string; to: string }> = [ { from: '细的粉丝', to: '粉丝' }, { from: '生抽', to: '海天生抽' }, { from: '豆瓣酱', to: '红油豆瓣' }, { from: '黑胡椒汁', to: '黑胡椒酱' }, // 耗油:主系统档案名与我们一致,无需处理(留在这里说明为什么没有第 5 条) ]; const APPLY = process.argv.includes('--apply'); const BRANCH_ARG = (process.argv.find((a) => a.startsWith('--branch=')) || '').split('=')[1] || ''; type Row = { branch: string; from: string; to: string; sku: string; action: string; customers: string[] }; async function skuByName(client: PoolClient, name: string): Promise { const r = await client.query<{ sku_code: string }>( `SELECT sku_code FROM skus WHERE TRIM(sku_name) = TRIM($1) ORDER BY created_at NULLS LAST LIMIT 1`, [name] ); return r.rows[0]?.sku_code ?? null; } /** 引用了该 SKU 的客户(别名要按客户写) */ async function customersOfSku(client: PoolClient, skuCode: string): Promise { const r = await client.query<{ customer_code: string }>( `SELECT DISTINCT o.customer_code FROM order_items oi JOIN orders o ON o.order_code = oi.order_code WHERE oi.sku_code = $1 AND COALESCE(o.customer_code, '') <> '' ORDER BY 1`, [skuCode] ); return r.rows.map((x) => String(x.customer_code)); } async function aliasExists(client: PoolClient, customerCode: string, aliasName: string): Promise { const r = await client.query( `SELECT 1 FROM customer_sku_aliases WHERE customer_code = $1 AND alias_name = $2 AND COALESCE(status, 1) = 1 LIMIT 1`, [customerCode, aliasName] ); return r.rowCount > 0; } async function writeAlias(client: PoolClient, customerCode: string, aliasName: string, skuCode: string) { // 与 mainSystemItemSkuMappingService.upsertItemSkuAlias 同约定(唯一约束就是这两列) await client.query( `INSERT INTO customer_sku_aliases (customer_code, alias_name, sku_code, is_primary, confidence_score, usage_count, status) VALUES ($1, $2, $3, false, 1.00, 1, 1) ON CONFLICT (customer_code, alias_name) DO UPDATE SET sku_code = EXCLUDED.sku_code, status = 1, updated_at = NOW()`, [customerCode, aliasName, skuCode] ); } async function main() { const branches = BRANCH_ARG ? [{ branch_code: BRANCH_ARG }] : (await pool.query<{ branch_code: string }>(`SELECT branch_code FROM branches ORDER BY branch_code`)).rows; const report: Row[] = []; const aliasesWritten: string[] = []; for (const { branch_code: branch } of branches) { // 租户 schema + RLS 走全仓统一入口(`runWithTenantDataAccess`):不要自己 set_config(会落到 public) await runWithTenantDataAccess(branch, async (client) => { for (const { from, to } of MAPPING) { const target = await skuByName(client, to); const source = await skuByName(client, from); if (!source) { // 已改过名(幂等):若目标存在就只补别名 if (target) { const customers = await customersOfSku(client, target); for (const c of customers) { if (await aliasExists(client, c, from)) continue; if (APPLY) await writeAlias(client, c, from, target); aliasesWritten.push(`${branch} ${c} 「${from}」→ ${target}`); } report.push({ branch, from, to, sku: target, action: '已改名(只补别名)', customers }); } else { report.push({ branch, from, to, sku: '-', action: '未找到(跳过)', customers: [] }); } continue; } if (target && target !== source) { report.push({ branch, from, to, sku: source, action: `目标名已被 ${target} 占用 —— 跳过(不合并)`, customers: [], }); continue; } const customers = await customersOfSku(client, source); if (APPLY) { await client.query( `UPDATE product_catalog SET name = $2, updated_at = NOW() WHERE item_type = 'product' AND code = $1`, [source, to] ); await client.query(`UPDATE skus SET sku_name = $2 WHERE sku_code = $1`, [source, to]); for (const c of customers) { if (await aliasExists(client, c, from)) continue; await writeAlias(client, c, from, source); aliasesWritten.push(`${branch} ${c} 「${from}」→ ${source}`); } } else { for (const c of customers) { if (await aliasExists(client, c, from)) continue; aliasesWritten.push(`${branch} ${c} 「${from}」→ ${source}`); } } report.push({ branch, from, to, sku: source, action: APPLY ? '已改名' : '将改名', customers }); } }); } console.log(`\n${APPLY ? '已落库' : '预览(dry-run,未写库)'} · 分公司 ${branches.length} 个\n`); for (const r of report) { const cust = r.customers.length ? `客户 ${r.customers.join(',')}` : '无引用客户'; console.log(` ${r.branch} ${r.from} → ${r.to} [${r.sku}] ${r.action} (${cust})`); } console.log(`\n别名${APPLY ? '写入' : '待写入'} ${aliasesWritten.length} 条:`); for (const a of aliasesWritten) console.log(` ${a}`); if (!APPLY) console.log('\n(加 --apply 才落库)'); await pool.end(); } main().catch(async (error) => { console.error('[align-prep-sku-names] 失败:', error instanceof Error ? error.message : error); await pool.end().catch(() => {}); process.exit(1); });