/** * 手工验证:订单侧改成本价 → 回写自采单 / 备货行。 * * ⚠️ **只允许对本地库运行**(脚本会拒绝非 localhost 的 DATABASE_URL)。 * 脚本对每个用例都在 finally 里还原,并清理本次产生的审计行;退出码 0 = 全部符合预期。 * * 运行(server 目录): * npm run verify:cost-writeback * npm run verify:cost-writeback -- --branch BR004 * * 覆盖(对应 docs/design/20260922-order-cost-writeback-to-supply.md): * ① 备货行改写 + order_cost_writeback 审计 * ② 自采 status=10 → purchase_price(曾因 SELECT unit 报 column "unit" does not exist) * ③ 已结算 → skipped='settled',价格不动 * ④ 自采 status=20 → 走 amendPurchaseActual 只改 actual_price(事务内跑完 ROLLBACK) */ import pg from 'pg'; import { writeOrderEnteredCostToSupply } from '../src/services/orderEnteredCostWritebackService'; const { Pool } = pg; type Args = { branch: string }; function parseArgs(argv: string[]): Args { const out: Args = { branch: 'BR004' }; for (let i = 0; i < argv.length; i += 1) { if (argv[i] === '--branch' && argv[i + 1]) out.branch = String(argv[i + 1]).toUpperCase(); } return out; } const { branch } = parseArgs(process.argv.slice(2)); const schema = `tenant_${branch.toLowerCase()}`; /** 硬闸门:绝不连非本地库(仓库硬规则:本地脚本不得写线上) */ function assertLocalDatabase(url: string) { const host = (() => { try { return new URL(url).hostname; } catch { return ''; } })(); if (!['127.0.0.1', 'localhost', '::1'].includes(host)) { throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})`); } } const results: Array<[string, boolean, string]> = []; function check(name: string, ok: boolean, detail = '') { results.push([name, ok, detail]); console.log(` ${ok ? '✔' : '✘'} ${name}${detail ? ` — ${detail}` : ''}`); } async function main() { const url = String(process.env.DATABASE_URL || ''); if (!url) throw new Error('缺少 DATABASE_URL(用 npm run verify:cost-writeback 会带 --env-file=.env)'); assertLocalDatabase(url); const pool = new Pool({ connectionString: url, max: 2 }); const client = await pool.connect(); const watch = await pool.connect(); await client.query(`SET search_path TO ${schema}, public`); await watch.query(`SET search_path TO ${schema}, public`); // 还原用快照 const prepBackup = new Map(); const poBackup = new Map(); const touchedKeys = new Set(); const snapPrep = async (orderCode: string, skuCode: string) => { const r = await client.query( `SELECT id, purchase_price FROM supplier_preparations WHERE order_code = $1 AND sku_code = $2`, [orderCode, skuCode] ); for (const row of r.rows) if (!prepBackup.has(row.id)) prepBackup.set(row.id, row.purchase_price); return r.rows; }; const snapPo = async (purchaseCode: string) => { if (poBackup.has(purchaseCode)) return; const r = await client.query( `SELECT purchase_price, actual_price FROM purchase_orders WHERE purchase_code = $1`, [purchaseCode] ); if (r.rows[0]) poBackup.set(purchaseCode, r.rows[0]); }; const auditCount = async (orderCode: string, skuCode: string) => ( await client.query( `SELECT count(*)::int c FROM operation_logs WHERE operation_type = 'order_cost_writeback' AND target_id = $1`, [`${orderCode}:${skuCode}`] ) ).rows[0].c as number; /** 候选行的公共守卫:未作废、未结算、未验收(与服务内判定一致) */ const UNGUARDED_SP = ` COALESCE(sp.prepare_status, 0) < 40 AND COALESCE(sp.is_history_repair, false) = false AND COALESCE(sp.transferred_to_purchase, false) = false AND COALESCE(sp.purchase_price, 0) > 0 AND NOT EXISTS (SELECT 1 FROM statement_lines sl WHERE sl.order_code = sp.order_code AND sl.sku_code = sp.sku_code AND sl.statement_type = 'supplier') AND NOT EXISTS (SELECT 1 FROM inspections i WHERE i.order_code = sp.order_code AND i.sku_code = sp.sku_code AND COALESCE(NULLIF(TRIM(i.source_type), ''), 'supplier') = 'supplier' AND COALESCE(i.actual_qty, 0) > 0)`; type Candidate = { order_code: string; sku_code: string; purchase_price: string | null; prepare_status: number | null; supplier_code: string | null; id: string | null; purchase_code?: string; purchase_status?: number; }; /** 纯备货行(同单同 SKU 没有任何未作废自采单) */ const findPrepCandidate = async (): Promise => { const r = await client.query( `SELECT sp.order_code, sp.sku_code, sp.purchase_price, sp.prepare_status, sp.supplier_code, sp.id FROM supplier_preparations sp WHERE ${UNGUARDED_SP} AND NOT EXISTS (SELECT 1 FROM purchase_orders po WHERE po.order_code = sp.order_code AND po.sku_code = sp.sku_code AND COALESCE(po.purchase_status, 0) <> 40) LIMIT 1` ); return r.rows[0] as Candidate | undefined; }; /** * 带自采单的候选(按 purchase_status 过滤)。 * **不要求存在备货行** —— 自采单可以没有对应备货行(此时 prep_updated=0); * 而 20/30 那个分支(曾因 `SELECT unit` 报错)必须能命中。 */ const findPoCandidate = async (statuses: number[]): Promise => { const r = await client.query( `SELECT po.order_code, po.sku_code, po.purchase_code, po.purchase_status, sp.id, sp.purchase_price, sp.prepare_status, sp.supplier_code FROM purchase_orders po LEFT JOIN supplier_preparations sp ON sp.order_code = po.order_code AND sp.sku_code = po.sku_code WHERE COALESCE(po.purchase_status, 0) = ANY($1::int[]) AND NOT EXISTS (SELECT 1 FROM statement_lines sl WHERE sl.order_code = po.order_code AND sl.sku_code = po.sku_code AND sl.statement_type = 'supplier') AND NOT EXISTS (SELECT 1 FROM inspections i WHERE i.order_code = po.order_code AND i.sku_code = po.sku_code AND COALESCE(NULLIF(TRIM(i.source_type), ''), 'supplier') = 'supplier' AND COALESCE(i.actual_qty, 0) > 0) ORDER BY po.purchase_status, po.purchase_code LIMIT 1`, [statuses] ); return r.rows[0] as Candidate | undefined; }; try { // ── ① 备货行 const c1 = await findPrepCandidate(); if (!c1) { console.log('[① 备货行] 跳过:库里没有「未结算/未验收的备货行」候选'); } else { const base = Number(c1.purchase_price); const target = Number((base + 1).toFixed(4)); await snapPrep(c1.order_code, c1.sku_code); touchedKeys.add(`${c1.order_code}:${c1.sku_code}`); console.log(`[① 备货行] ${c1.order_code}/${c1.sku_code} 原价=${base}`); const res = await writeOrderEnteredCostToSupply(client, { orderCode: c1.order_code, skuCode: c1.sku_code, supplierCode: c1.supplier_code, branchCode: branch, unitCost: target, operatorId: null, operatorRole: null, }); const after = ( await client.query(`SELECT purchase_price FROM supplier_preparations WHERE id = $1::uuid`, [c1.id]) ).rows[0]; check( '备货价被改写为订单成本', Number(after.purchase_price) === target && res.prep_updated === 1, `${base} → ${after.purchase_price}` ); check('写入 order_cost_writeback 审计', (await auditCount(c1.order_code, c1.sku_code)) === 1); } // ── ② 自采 status=10 const c2 = await findPoCandidate([10]); if (!c2?.purchase_code) { console.log('[② 自采 status=10] 跳过:没有「未结算/未验收的 status=10 自采单」候选'); } else { const cost = Number(((Number(c2.purchase_price) || 1) + 2).toFixed(4)); await snapPrep(c2.order_code, c2.sku_code); await snapPo(c2.purchase_code); touchedKeys.add(`${c2.order_code}:${c2.sku_code}`); console.log(`[② 自采 status=10] ${c2.order_code}/${c2.sku_code} PO=${c2.purchase_code}`); const res = await writeOrderEnteredCostToSupply(client, { orderCode: c2.order_code, skuCode: c2.sku_code, supplierCode: c2.supplier_code, branchCode: branch, unitCost: cost, operatorId: null, operatorRole: null, }); const po = ( await client.query(`SELECT purchase_price FROM purchase_orders WHERE purchase_code = $1`, [ c2.purchase_code, ]) ).rows[0]; check( '自采单 purchase_price 被改写(此处曾抛 column "unit" does not exist)', Number(po.purchase_price) === cost && res.purchase_updated === 1, `→ ${po.purchase_price}` ); } // ── ③ 已结算守卫 const settled = ( await client.query( `SELECT sp.order_code, sp.sku_code, sp.supplier_code, sp.purchase_price FROM supplier_preparations sp WHERE EXISTS (SELECT 1 FROM statement_lines sl WHERE sl.order_code = sp.order_code AND sl.sku_code = sp.sku_code AND sl.statement_type = 'supplier') LIMIT 1` ) ).rows[0]; if (!settled) { console.log('[③ 已结算守卫] 跳过:库里没有已结算的备货行'); } else { await snapPrep(settled.order_code, settled.sku_code); touchedKeys.add(`${settled.order_code}:${settled.sku_code}`); console.log(`[③ 已结算守卫] ${settled.order_code}/${settled.sku_code}`); const res = await writeOrderEnteredCostToSupply(client, { orderCode: settled.order_code, skuCode: settled.sku_code, supplierCode: settled.supplier_code, branchCode: branch, unitCost: 999, operatorId: null, operatorRole: null, }); const after = ( await client.query( `SELECT purchase_price FROM supplier_preparations WHERE order_code = $1 AND sku_code = $2`, [settled.order_code, settled.sku_code] ) ).rows[0]; check( "已结算行返回 skipped='settled' 且价格不动", res.skipped === 'settled' && Number(after.purchase_price) === Number(settled.purchase_price), `skipped=${res.skipped} 价格=${after.purchase_price}` ); } // ── ④ 自采 status=20(事务内,跑完 ROLLBACK) const c4 = await findPoCandidate([20, 30]); if (!c4?.purchase_code) { console.log('[④ 自采 status=20/30] 跳过:没有候选'); } else { const cost = Number(((Number(c4.purchase_price) || 1) + 3).toFixed(4)); await client.query('BEGIN'); const before = ( await client.query( `SELECT purchase_price, actual_price FROM purchase_orders WHERE purchase_code = $1`, [c4.purchase_code] ) ).rows[0]; const itemBefore = ( await watch.query(`SELECT unit_cost FROM order_items WHERE order_code = $1 AND sku_code = $2`, [ c4.order_code, c4.sku_code, ]) ).rows; touchedKeys.add(`${c4.order_code}:${c4.sku_code}`); console.log(`[④ 自采 status=${c4.purchase_status}] ${c4.order_code}/${c4.sku_code} PO=${c4.purchase_code}`); let res: Awaited> | null = null; let err: string | null = null; try { res = await writeOrderEnteredCostToSupply(client, { orderCode: c4.order_code, skuCode: c4.sku_code, supplierCode: c4.supplier_code, branchCode: branch, unitCost: cost, operatorId: null, operatorRole: null, }); } catch (e) { err = (e as Error).message; } const during = ( await client.query( `SELECT purchase_price, actual_price FROM purchase_orders WHERE purchase_code = $1`, [c4.purchase_code] ) ).rows[0]; await client.query('ROLLBACK'); const afterRollback = ( await client.query( `SELECT purchase_price, actual_price FROM purchase_orders WHERE purchase_code = $1`, [c4.purchase_code] ) ).rows[0]; const itemAfter = ( await watch.query(`SELECT unit_cost FROM order_items WHERE order_code = $1 AND sku_code = $2`, [ c4.order_code, c4.sku_code, ]) ).rows; check('status=20 分支未抛错且被计数', !err && !!res && res.purchase_updated === 1, err || ''); check( '实采价被改写、purchase_price 不变', Number(during.actual_price) === cost && Number(during.purchase_price) === Number(before.purchase_price), `actual_price ${before.actual_price} → ${during.actual_price}` ); check( '订单行 unit_cost 未被本次回写改动(skipOrderItemSync)', JSON.stringify(itemBefore) === JSON.stringify(itemAfter), itemAfter.map((r) => r.unit_cost).join(',') ); check( 'ROLLBACK 后自采单复原', Number(afterRollback.actual_price) === Number(before.actual_price) && Number(afterRollback.purchase_price) === Number(before.purchase_price) ); } } finally { for (const [id, price] of prepBackup) { await client.query(`UPDATE supplier_preparations SET purchase_price = $2::numeric WHERE id = $1::uuid`, [ id, price, ]); } for (const [code, row] of poBackup) { await client.query( `UPDATE purchase_orders SET purchase_price = $2::numeric, actual_price = $3::numeric WHERE purchase_code = $1`, [code, row.purchase_price, row.actual_price] ); } /** * 清理本次运行产生的审计:**按脚本自己动过的 (order_code:sku_code) 精确删除**。 * 不能按时间删 —— 本地库可能同时有人在真实操作,会误删别人的真实审计行。 */ const touched = [...touchedKeys]; const del = touched.length ? await client.query( `DELETE FROM operation_logs WHERE operation_type = 'order_cost_writeback' AND target_id = ANY($1::text[])`, [touched] ) : { rowCount: 0 }; console.log( `\n[还原] 备货行 ${prepBackup.size} 行、自采单 ${poBackup.size} 单已复原;清理本次审计 ${del.rowCount} 条` ); client.release(); watch.release(); await pool.end(); } const failed = results.filter(([, ok]) => !ok); console.log(`\n结果:${results.length - failed.length}/${results.length} 通过`); if (failed.length) process.exitCode = 1; } main().then( () => process.exit(process.exitCode || 0), (e) => { console.error('FATAL', (e as Error).message); process.exit(1); } );