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'); }); });