Files
SupplierSystem/server/tests/prepPriceChangeCoverGuard.test.ts
T
Ubuntu 6af272dc98
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
修复备货改价写坏「库存抵扣成本价」:选行无来源过滤 + 金额用备货量
开发者报障:「我就采购部分修改了采购成本价 采购的数量多了点 但是应该和抵扣成本价无关呀」

现象(本地库 BR002,订单 ORD_WEB_20261015_BR002_0002 / 抄手皮):
订单详情「抵扣成本价」由 2.00 变 2.76,而被抵扣批次成本价就是 2.00。

根因(实测逐字对上):
- 该行计划 10 斤、抵扣 5 斤 ⇒ 库存抵扣账本行 cost_details(inventory_cover/stock_cover)
  原为 10.00(5 × 批次成本 2.00;allocated_amount 仍留 10.00 作原值指纹);
- 16:19:58 那次 workflow/preparation/update-purchase-price{prepare_qty:6, purchase_price:2.3}
  后,该行金额变成 13.80 = 6 × 2.30,而「抵扣成本价」= 金额 ÷ 抵扣量 = 13.80 ÷ 5 = 2.76;
- closePurchaseCostLoopAfterPrepPriceChange 的两条错:
  ① 选行 `SELECT id, cost_subtype ... WHERE order_code/sku + LIMIT 1` 无来源过滤 ——
     部分抵扣的行有两行 purchase(inventory_cover 先插入、order_goods 后插入),命中了抵扣行;
  ② 金额用备货量 prepare_qty("打算买多少")而不是缺口量。
- 触发条件:部分抵扣(抵扣量 < 计划量)+ 在采购/备货页改价(带数量);全额抵扣行只有一行,
  不踩(同单精瘦肉 37.50 = 5×7.50、苹果 50.00 = 10×5.00 正常)。
- 次要后果:amount ≠ allocated_amount ⇒ 看板成本 KPI(读 allocated_amount,dashboardService:304)
  与订单详情(读 amount,stockCoverBatchQueryService:293)同一笔成本差 3.80。

修复(开发者裁决·方案甲,只改这一条写路径):
1. 金额按缺口:先汇总 order_items 的 Σ GREATEST(0, quantity − stock_cover_qty)
   (与 orderCostPostingService:574 同口径),amount = 缺口量 × purchase_price;备货量不再参与金额;
2. 只认占位行:目标行加 `AND COALESCE(remark,'') = 'unit_cost_sync'` + ORDER BY created_at DESC;
3. 不写正式账、不碰抵扣行:无占位行时先查"是否已有正式采购账"
   (remark IS DISTINCT FROM 'unit_cost_sync' AND cost_source <> 'inventory_cover'),有则跳过;
   无论如何绝不写 cost_source='inventory_cover'(抵扣行只由 FIFO 批次成本回算写);
4. 顺带把 allocated_amount 与 amount 写成同一值,消除看板/详情口径错位。

口径(口径文档 §3):备货量=计划、实采量/实采价=事实(验收落正式账)、
缺口量=本单实际要买的量;多采留库走 cost_details(inventory_holding)(独立入库/验收多采),
将来被抵扣时再从持有桶搬进 inventory_cover(分公司总额不变)。

验证:
- server/tests/prepPriceChangeCoverGuard.test.ts(6 例,假 Db 断言实际执行的 SQL):
  有占位行只 UPDATE 占位行且金额 5×2.30=11.50(不是 6×2.30=13.80);无占位行+有正式账不写;
  无占位行+无正式账 INSERT 且按缺口;缺口 0 不写;任何写语句不含 inventory_cover;源码 pin。
- npx tsc --noEmit 0 错误;server 全量 vitest 26 failed files / 33 failed tests = 基线逐项一致。
- 真实库事务内 dry-run(改完 ROLLBACK):缺口量 5.0000、命中占位行 bb659750(非抵扣行)、
  改后抵扣行仍 10.00 / 占位行 11.50、回滚无痕。
- 本地现场已修回 10.00 ⇒ 抵扣成本价回到 2.0000(精瘦肉 7.50、苹果 5.00 未动)。
- 线上只读核查:br001/br002/br003 的 inventory_cover 行 amount 与 allocated_amount 全部一致
  (br002 有 3 行抵扣、2 张订单),尚未被写花;修复需随下次部署生效。
- 设计门禁 run-all.sh --verify:8 通过 / 1 红(check-ai-cost 既知不可调绿)/ 1 未执行(verify-facts)。
- 未部署(等明确部署命令)。

设计文档:docs/design/20261015-备货改价不得写坏库存抵扣成本价(缺口口径).md
未覆盖(留待裁决):直送/免入库路径上"采多了"算谁的,本次未核实也未动。
2026-10-15 16:49:17 +08:00

160 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.
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { closePurchaseCostLoopAfterPrepPriceChange } from '../src/services/supplierPreparationStatusService';
/**
* 备货改价不得写坏「库存抵扣成本价」(2026-10-15 开发者实测报障)。
*
* 现场(本地库 BR002,订单 `ORD_WEB_20261015_BR002_0002` / 抄手皮):
* · 该行 计划 10 斤、抵扣 5 斤(批次成本 2.00)⇒ 库存抵扣账本 `inventory_cover` 记 10.00;
* · 缺口 5 斤由备货承担 ⇒ `order_goods` 占位行(`remark='unit_cost_sync'`)记 5 × 2.30 = 11.50;
* · 开发者在采购页改价 `{prepare_qty: 6, purchase_price: 2.3}` 后,详情「抵扣成本价」
* 由 2.00 变成 **2.76** —— 因为旧实现那条 `SELECT ... WHERE order_code/sku + LIMIT 1`
* 没有任何来源过滤,命中了先插入的 **库存抵扣行**,把金额覆盖成 6 × 2.30 = 13.80,
* 而「抵扣成本价」= 该行金额 ÷ 抵扣量 = 13.80 ÷ 5 = 2.76。
*
* 口径(开发者裁决·方案甲):备货量只是"打算买多少",本单成本按**缺口量**算;
* 多采留库的走 `inventory_holding`(独立入库/验收多采),将来被抵扣时再搬进 `inventory_cover`。
* ⇒ 改价只许刷新占位行,金额 = (计划量 − 抵扣量) × 单价,且**永不触碰** `inventory_cover`。
*/
type Call = { sql: string; params: unknown[] };
function makeDb(opts: {
gapQty?: number;
placeholder?: { id: string; cost_subtype?: string } | null;
formal?: { id: string } | null;
}) {
const calls: Call[] = [];
const db = {
async query(sql: string, params?: unknown[]) {
const s = String(sql);
calls.push({ sql: s, params: [...(params || [])] });
// 无入库记录 ⇒ 不走 reconcile 分支
if (s.includes('FROM inspections')) return { rowCount: 0, rows: [] as unknown[] };
if (s.includes('FROM order_items')) {
return { rowCount: 1, rows: [{ gap_qty: String(opts.gapQty ?? 0) }] };
}
if (s.includes('FROM cost_details') && s.includes('IS DISTINCT FROM')) {
return { rowCount: opts.formal ? 1 : 0, rows: opts.formal ? [opts.formal] : [] };
}
if (s.includes('FROM cost_details') && s.includes("'unit_cost_sync'")) {
return {
rowCount: opts.placeholder ? 1 : 0,
rows: opts.placeholder ? [opts.placeholder] : [],
};
}
if (s.includes('FROM orders')) {
return { rowCount: 1, rows: [{ cycle_code: '202610', branch_code: 'BR002' }] };
}
// UPDATE / INSERT
return { rowCount: 1, rows: [] as unknown[] };
},
};
return { db: db as never, calls };
}
const writes = (calls: Call[]) =>
calls.filter((c) => /^\s*(UPDATE|INSERT)/i.test(c.sql.trim()));
/** 本单复刻:计划 10、抵扣 5、备货 6、单价 2.30 */
const SCENARIO = {
order_code: 'ORD_WEB_20261015_BR002_0002',
sku_code: 'SKU97144738818',
supplier_code: 'SUP36286544',
prepare_qty: 6,
purchase_price: 2.3,
branch_code: 'BR002',
};
describe('备货改价 · 成本只写缺口占位行', () => {
it('有占位行:只改占位行,金额按缺口(5 × 2.30 = 11.50),不是备货量(6 × 2.30 = 13.80)', async () => {
const { db, calls } = makeDb({
gapQty: 5,
placeholder: { id: 'placeholder-row', cost_subtype: 'order_goods' },
});
const res = await closePurchaseCostLoopAfterPrepPriceChange(db, SCENARIO);
expect(res.costUpdated).toBe(true);
const w = writes(calls);
expect(w).toHaveLength(1);
expect(w[0].sql).toMatch(/^UPDATE cost_details/);
expect(w[0].params[0]).toBe('placeholder-row');
expect(Number(w[0].params[1])).toBeCloseTo(11.5, 6);
// allocated_amount 必须与 amount 同步(否则看板读 allocated_amount、详情读 amount 会打架)
expect(w[0].sql).toContain('allocated_amount = $2');
});
it('绝不把 inventory_cover(库存抵扣行)当目标:选行 SQL 只认占位行,且显式排除抵扣来源', async () => {
const { db, calls } = makeDb({
gapQty: 5,
placeholder: { id: 'placeholder-row', cost_subtype: 'order_goods' },
});
await closePurchaseCostLoopAfterPrepPriceChange(db, SCENARIO);
const selectTarget = calls.find(
(c) => c.sql.includes('FROM cost_details') && c.sql.includes('SELECT id, cost_subtype')
);
expect(selectTarget, '必须有一条只选占位行的目标查询').toBeTruthy();
expect(selectTarget!.sql).toContain("COALESCE(remark, '') = 'unit_cost_sync'");
expect(selectTarget!.sql).toContain('ORDER BY created_at DESC');
// 任何写语句都不得涉及库存抵扣行
for (const w of writes(calls)) {
expect(w.sql).not.toContain('inventory_cover');
expect(w.params).not.toContain('cover-row');
}
});
it('无占位行 + 已有正式采购账:不写、不叠插(避免重复计成本)', async () => {
const { db, calls } = makeDb({ gapQty: 5, placeholder: null, formal: { id: 'formal-row' } });
const res = await closePurchaseCostLoopAfterPrepPriceChange(db, SCENARIO);
expect(res.costUpdated).toBe(false);
expect(writes(calls)).toHaveLength(0);
});
it('无占位行 + 无正式账:补记一行,金额同样按缺口', async () => {
const { db, calls } = makeDb({ gapQty: 5, placeholder: null, formal: null });
const res = await closePurchaseCostLoopAfterPrepPriceChange(db, SCENARIO);
expect(res.costUpdated).toBe(true);
const w = writes(calls);
expect(w).toHaveLength(1);
expect(w[0].sql).toMatch(/^INSERT INTO cost_details/);
expect(Number(w[0].params[2])).toBeCloseTo(11.5, 6);
// 「有没有正式账」的判定必须排除占位行与库存抵扣来源(抵扣行不是采购正式账)
const formal = calls.find((c) => c.sql.includes('IS DISTINCT FROM'));
expect(formal, '无占位行时必须先查正式账').toBeTruthy();
expect(formal!.sql).toContain("IS DISTINCT FROM 'unit_cost_sync'");
expect(formal!.sql).toContain("<> 'inventory_cover'");
});
it('全额抵扣(缺口 0):不写任何成本行', async () => {
const { db, calls } = makeDb({ gapQty: 0, placeholder: { id: 'placeholder-row' } });
const res = await closePurchaseCostLoopAfterPrepPriceChange(db, SCENARIO);
expect(res.costUpdated).toBe(false);
expect(writes(calls)).toHaveLength(0);
});
it('源码口径:金额只由缺口量决定,备货量不再参与金额计算', () => {
const src = readFileSync(
new URL('../src/services/supplierPreparationStatusService.ts', import.meta.url),
'utf8'
);
const fn = src.slice(
src.indexOf('export async function closePurchaseCostLoopAfterPrepPriceChange'),
src.indexOf('/**\n * 改价「数量变更」后')
);
expect(fn).toContain('stock_cover_qty');
expect(fn).toContain('Math.round(gapQty * price * 100) / 100');
expect(fn).not.toContain('Math.round(qty * price * 100) / 100');
expect(fn).toContain("COALESCE(remark, '') = 'unit_cost_sync'");
expect(fn).toContain("<> 'inventory_cover'");
// 入库后的正式账走 reconcile,不能被改价覆盖
expect(fn).toContain('reconcileOrderPurchaseFromLatestInspections');
});
});