Files
SupplierSystem/server/scripts/verify-batch-spec.ts
T
Ubuntu cb066d8302
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
test(规格): 补真 HTTP 端到端验证 + 可复现自检脚本 + 唯一实现守卫 + 只读成本对账
承接 §13 的返工教训:把"真跑才能发现"的验证固定下来,不再只靠读源码字符串。

## 新增可复现自检脚本 server/scripts/verify-batch-spec.ts
自建 ZZ_VERIFY_ 夹具、5 条断言、无论成败自清(实测跑完残留全 0):
有规格⇒命中批优先;无规格⇒纯 FIFO;**无匹配⇒仍纯 FIFO**(刻意把"规格不匹配"批次放最早、
"规格未知"放第二早 —— 正是三段式实现会错扣的条件);全角数字⇒命中;NBSP⇒命中。

## 测试 ⑬:唯一实现守卫(扫整个 src/services)
除白名单(两处是"取 FIFO 首批的存放区域"用于分拣区域分组,非批次选择,已写明理由)外,
任何文件再手写 `ORDER BY created_at ASC, expiry_date ASC NULLS FIRST` 都会被拦下。
避免将来长出第二份排序、重回"建议按规格、实扣按 FIFO"的漂移。

## 真 HTTP 端到端(不是直接调服务)
- P4:POST /api/workflow/inspection/submit 带 spec ⇒ 新批次 inventory.spec='1箱12瓶';
  传纯空白 ⇒ spec IS NULL。**修正路由前两次都会写 NULL**。
- P3:GET /orders/:code/stock-cover-batches 三态正确(命中 true / 无规格 null / 无匹配 false);
  GET /picking/outbound-batches ⇒ order_spec='1箱12瓶',命中批置顶且带 spec/spec_matched。

## 只读成本对账(未改任何数据,供财务冻结登记)
- BR002 多批次 SKU 2 个、其中批次规格不一致 2 个
- 有规格 × 多批次的订单行:BR002 共 3 行,**全部是本次对抗夹具**;排除夹具后 = 0 行
- 单件成本最大差:真实 SKU12951865280 为 ¥5.00(批次 5.00/6.00/10.00);夹具 ZZ_SKU_MILK 为 ¥1.00
⇒ 口径变更是条件性的:只有"该 SKU 确实有多个不同规格批次 且 订单行写了规格"才改变扣哪批与订单成本;
存量受影响订单行 = 0。仍按财务冻结登记"成本随被选中的规格批次取值",已结算不回改。

## 测试与类型
inventoryBatchSpecSelection 13 通过 / stockCoverBatchQuery 17 / stockCoverBatchPlan 12(合计 42);
server tsc 仅剩既有 src/prompts/defaults.ts(465);门禁快档 8 通过 / check-ai-cost 既有红。

## 本地副作用(已在设计文 §14.5 如实列出)
两条待验收单被真实验收并各新建一个批次;临时借用过 admin 的密码 hash 给 BR002 操作员账号,
已逐字还原并验证(还原后 123456 登录失败);ZZ 对抗夹具按开发者要求保留。
2026-10-16 20:05:31 +08:00

170 lines
7.1 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.
/**
* 方案丙「批次级规格 + 抵扣按客户要求的规格选批次」**真库端到端自检脚本**(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 } from '../src/services/inventoryOutboundService';
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})`
);
}
} 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);
});