197 lines
8.9 KiB
TypeScript
197 lines
8.9 KiB
TypeScript
/**
|
||
* 方案丙「批次级规格 + 抵扣按客户要求的规格选批次」**真库端到端自检脚本**(2026-10-16)。
|
||
*
|
||
* 为什么要有它:本方案的单元测试大多是"读源码字符串",而三轮对抗里真正被打穿的
|
||
* (`FOR UPDATE` × 窗口函数、无匹配时偏离 FIFO、同单同 SKU 两行取错规格)**都只能靠真跑发现**。
|
||
* 这个脚本把当时的临时验证固定下来,任何人(或 CI)都能一键复现:
|
||
*
|
||
* cd server && npx tsx --env-file=.env scripts/verify-batch-spec.ts
|
||
*
|
||
* 它自建夹具(前缀 `ZZ_VERIFY_`)、自检、最后**无论成败都清理自己造的数据**(try/finally)。
|
||
* 断言(每条都对应一个真实缺陷或设计要求):
|
||
* ① 订单有规格 ⇒ 命中批优先(哪怕命中批入库更晚)
|
||
* ② 订单无规格 ⇒ 纯 FIFO(与改前逐字一致)
|
||
* ③ **无匹配 ⇒ 仍为纯 FIFO** —— 夹具刻意把"规格不匹配"的批次放在**最早**、
|
||
* "规格未知"放第二早:三段式 CASE 的实现会错扣第二早那批(对抗实测缺陷,见设计文 §13.3)
|
||
* ④ 全角数字(1箱12瓶)与 NBSP 形态都算命中(SQL/JS 归一同口径)
|
||
* ⑤ 实扣事实以 `inventory_logs` 为准,且每单只扣 1 件
|
||
*
|
||
* ⚠️ 只动 `ZZ_VERIFY_` 前缀的数据;不碰其它数据。生产环境不要跑(会写库存流水)。
|
||
*/
|
||
import { pool } from '../src/db';
|
||
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
|
||
import { fifoDeductInventory, deductInventoryForOrderDeparture } from '../src/services/inventoryOutboundService';
|
||
import { planFifoBatchesForCoveredItems } from '../src/services/stockCoverBatchPlanService';
|
||
|
||
const BRANCH = 'BR002';
|
||
const SKU = 'ZZ_VERIFY_MILK';
|
||
/** 周期码:`orders.cycle_code` 非空(实测 NOT NULL 且无默认值),随便给一个本分支的合法账期 */
|
||
const CYCLE = '202610';
|
||
|
||
type Case = { order: string; label: string; spec: string | null; expect: string };
|
||
|
||
const CASES: Case[] = [
|
||
{ order: 'ZZ_VERIFY_SPEC', label: '订单要求 1箱12瓶', spec: '1箱12瓶', expect: 'ZZ_V_MATCH' },
|
||
{ order: 'ZZ_VERIFY_NOSPEC', label: '订单没写规格', spec: null, expect: 'ZZ_V_EARLY_MISMATCH' },
|
||
{
|
||
order: 'ZZ_VERIFY_NOMATCH',
|
||
label: '订单要求 1箱48瓶(无此规格)',
|
||
spec: '1箱48瓶',
|
||
expect: 'ZZ_V_EARLY_MISMATCH',
|
||
},
|
||
{ order: 'ZZ_VERIFY_FULLWIDTH', label: '订单要求 1箱12瓶(全角)', spec: '1箱12瓶', expect: 'ZZ_V_MATCH' },
|
||
{
|
||
order: 'ZZ_VERIFY_NBSP',
|
||
label: '订单要求 1箱<NBSP>12瓶',
|
||
spec: '1箱\u00a012瓶',
|
||
expect: 'ZZ_V_MATCH',
|
||
},
|
||
];
|
||
|
||
async function cleanup(): Promise<void> {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`SELECT set_config('app.branch_code', $1, true)`, [BRANCH]);
|
||
await client.query(
|
||
`DELETE FROM picking_items WHERE order_item_id IN (
|
||
SELECT id FROM order_items WHERE order_code LIKE 'ZZ_VERIFY_%')`
|
||
);
|
||
await client.query(`DELETE FROM inventory_logs WHERE related_order_code LIKE 'ZZ_VERIFY_%'`);
|
||
await client.query(`DELETE FROM order_items WHERE order_code LIKE 'ZZ_VERIFY_%'`);
|
||
await client.query(`DELETE FROM orders WHERE order_code LIKE 'ZZ_VERIFY_%'`);
|
||
await client.query(`DELETE FROM inventory WHERE sku_code = $1`, [SKU]);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
async function seed(): Promise<void> {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`SELECT set_config('app.branch_code', $1, true)`, [BRANCH]);
|
||
/**
|
||
* 夹具刻意这样排(对抗缺陷的复现条件):
|
||
* V_EARLY_MISMATCH(规格 1箱24瓶,**最早**入库)→ 订单要 1箱48瓶 时"一个都不命中",
|
||
* 纯 FIFO 必须仍扣它;三段式实现会跳过它去扣 V_UNKNOWN。
|
||
*/
|
||
const batches: Array<[string, string | null, number, number]> = [
|
||
['ZZ_V_EARLY_MISMATCH', '1箱24瓶', 4, 3],
|
||
['ZZ_V_UNKNOWN', null, 3, 2],
|
||
['ZZ_V_MATCH', '1箱12瓶', 2, 2.5],
|
||
['ZZ_V_MATCH_B', '1箱12瓶', 1, 2.6],
|
||
];
|
||
for (const [batchNo, spec, daysAgo, cost] of batches) {
|
||
await client.query(
|
||
`INSERT INTO inventory (batch_no, sku_code, quantity, available_qty, cost_price, status, branch_code, spec, created_at)
|
||
VALUES ($1, $2, 100, 100, $3, 10, $4, $5, NOW() - ($6 || ' days')::interval)`,
|
||
[batchNo, SKU, cost, BRANCH, spec, String(daysAgo)]
|
||
);
|
||
}
|
||
for (const item of CASES) {
|
||
// orders 的 NOT NULL 无默认列:order_code / cycle_code / bid_code(实测)
|
||
await client.query(
|
||
`INSERT INTO orders (order_code, cycle_code, bid_code, branch_code, customer_code, order_status, delivery_date)
|
||
VALUES ($1, $2, $3, $4, 'ZZ_VERIFY_CUST', 45, CURRENT_DATE)`,
|
||
[item.order, CYCLE, `ZZ_VERIFY_BID_${item.order}`, BRANCH]
|
||
);
|
||
// order_items 的 NOT NULL 无默认列:quantity / price / amount(实测)
|
||
await client.query(
|
||
`INSERT INTO order_items (order_code, item_name, sku_code, quantity, price, amount, unit, stock_cover_qty, spec, branch_code)
|
||
VALUES ($1, 'ZZ对抗自检牛奶', $2, 1, 10, 10, '箱', 1, $3, $4)`,
|
||
[item.order, SKU, item.spec, BRANCH]
|
||
);
|
||
}
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
async function main(): Promise<void> {
|
||
let failed = 0;
|
||
await runWithTenantDbContext(BRANCH, async () => {
|
||
await cleanup();
|
||
await seed();
|
||
try {
|
||
for (const item of CASES) {
|
||
const client = await pool.connect();
|
||
let got = '(未扣)';
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(`SELECT set_config('app.branch_code', $1, true)`, [BRANCH]);
|
||
await fifoDeductInventory(client as never, {
|
||
skuCode: SKU,
|
||
qty: 1,
|
||
branchCode: BRANCH,
|
||
orderCode: item.order,
|
||
pickCode: 'ZZ_VERIFY_PICK',
|
||
operatorId: null,
|
||
operationType: 'picking_out',
|
||
} as never);
|
||
const log = await client.query(
|
||
`SELECT batch_no FROM inventory_logs WHERE related_order_code = $1 ORDER BY created_at DESC LIMIT 1`,
|
||
[item.order]
|
||
);
|
||
got = String(log.rows[0]?.batch_no || '(无流水)');
|
||
await client.query('ROLLBACK');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
got = `抛错: ${(error as Error).message}`;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
const ok = got === item.expect;
|
||
if (!ok) failed += 1;
|
||
console.log(
|
||
`${ok ? '✅' : '❌'} ${item.order} ${item.label} ⇒ 实扣 ${got}(期望 ${item.expect})`
|
||
);
|
||
}
|
||
/**
|
||
* ⑥ **计划 vs 实扣一致**(设计 §9.7「抵扣门槛/批次计划/实际出库三处对同一订单给出同一批次」):
|
||
* 走完整链路 `planFifoBatchesForCoveredItems`(写 `picking_items.outbound_batches`)→
|
||
* `deductInventoryForOrderDeparture`(实扣),两处必须指向同一批。
|
||
* 注意:开了分拣的分公司且还没有拣货行时,计划会**有意延后**(`deferredNoPickingRow`)——
|
||
* 这种情形只核对实扣,并把延后原因打印出来(不算失败)。
|
||
*/
|
||
const chain = CASES[0];
|
||
const plan = await planFifoBatchesForCoveredItems({ orderCode: chain.order });
|
||
const plannedBatches = plan.items.flatMap((row) => row.batches.map((b) => b.batch_no));
|
||
const deductResult = await deductInventoryForOrderDeparture(chain.order, {
|
||
operatorId: null,
|
||
operationType: 'picking_out',
|
||
});
|
||
const chainLog = await pool.query(
|
||
`SELECT batch_no FROM inventory_logs WHERE related_order_code = $1 ORDER BY created_at DESC LIMIT 1`,
|
||
[chain.order]
|
||
);
|
||
const actuallyDeducted = String(chainLog.rows[0]?.batch_no || '(无流水)');
|
||
const planOk = plannedBatches.length === 0 || plannedBatches[0] === chain.expect;
|
||
const deductOk = actuallyDeducted === chain.expect && deductResult.deducted;
|
||
if (!planOk || !deductOk) failed += 1;
|
||
console.log(
|
||
`${planOk && deductOk ? '✅' : '❌'} 计划→实扣链路 ${chain.order} ⇒ 计划 [${plannedBatches.join(',') || '延后(deferred=' + (plan.deferredNoPickingRow ?? 0) + ')'}]` +
|
||
` / 实扣 ${actuallyDeducted}(期望 ${chain.expect})`
|
||
);
|
||
} finally {
|
||
await cleanup();
|
||
}
|
||
});
|
||
console.log(failed === 0 ? '\n全部通过(夹具已清理)' : `\n有 ${failed} 条不符合预期`);
|
||
process.exit(failed === 0 ? 0 : 1);
|
||
}
|
||
|
||
main().catch(async (error) => {
|
||
console.error('自检脚本异常:', error);
|
||
await cleanup().catch(() => undefined);
|
||
process.exit(1);
|
||
});
|