import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; /** * **分拣完毕 = 出库 = 扣库存**(开发者 2026-10-13 口径,全单统一)。 * * 设计:docs/design/20261013-分拣完毕即出库扣库存(全单统一).md * * 背景(真库实证):`ORD_API_20261012_BR003_0002` 的 `preparations.picked_up` 收口成功(status=done), * 但该单批次**只有入库流水、没有出库流水** ⇒ 骑手上门取货单永久漏扣。扣库触发权在主系统事件 + * 时点要求在发车,两条都不由我方掌控。 * * 这里钉住三件事: * ① 分拣完成(`tryAdvanceOrderToDelivery` 置 50 之前)必须软扣一次库存; * ② 核货差额**不回补**(发车命中 `already_outbound` 守卫 ⇒ 不二次扣、不回冲); * ③ 软扣语义与冻结项不变(库存不足不拦;发车仍只拦「无核货明细」)。 */ const FILE = path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'); const OUTBOUND = path.join(__dirname, '../src/services/inventoryOutboundService.ts'); const src = readFileSync(FILE, 'utf8'); const outbound = readFileSync(OUTBOUND, 'utf8'); describe('分拣完毕即出库扣库存', () => { it('① 置 50 之前调用软扣(ensureOrderInventorySettledOnComplete + softInventory)', () => { const settleIdx = src.indexOf('await ensureOrderInventorySettledOnComplete(orderCode, {'); // 分拣路径的收尾(picker 路径专属文案)——扣库必须发生在它之前, // 否则会出现「已待配送但库存没扣」的窗口。⚠️ 不能用文件里第一处 `UPDATE ... order_status = 50`: // 那是「未启用分拣」分支的,位置在本段之前。 const pickingPathReturnIdx = src.indexOf( "return { advanced: true, message: '分拣已完成,订单进入待配送' };" ); expect(settleIdx, '未找到分拣完毕的扣库调用').toBeGreaterThan(-1); // 软扣 + 分拣出库口径(picking_out) expect(src.slice(settleIdx, settleIdx + 400)).toContain('softInventory: true'); expect(src.slice(settleIdx, settleIdx + 400)).toContain("operationType: 'picking_out'"); expect(pickingPathReturnIdx).toBeGreaterThan(-1); expect(settleIdx).toBeLessThan(pickingPathReturnIdx); // 失败只告警、不拦进入待配送(软扣纪律);2026-10-14 起同处还要把软扣缺口打进日志 const around = src.slice(settleIdx - 900, settleIdx + 900); expect(around).toContain('不拦进入待配送'); expect(around).toContain('softSkipped'); }); it('② 核货差额不回补:发车/结案再扣时靠 already_outbound 守卫短路', () => { expect(outbound).toContain("reason: 'already_outbound'"); // 守卫按流水判定(picking_out / delivery_loading_out 都算已出库) expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')"); // 发车仍是原来的软扣调用(未改成硬拦、未加二次扣) expect(src).toContain('softInventory: true,'); expect(src).toContain("deduct = await deductInventoryForOrderDeparture(orderCode, {"); }); it('③ 冻结项不变:发车只拦「无核货明细」,库存不足不拦', () => { expect(src).toContain("if (deduct.reason === 'no_loading_items')"); expect(src).toContain('缺少核货/分拣明细'); expect(src).toContain("reason: 'soft_inventory_skip'"); // 状态链常量不在本文件里改 expect(src).not.toContain('ORDER_STATUS_ALLOWED ='); }); }); /** * 出库扣库"从来没成功过"的真根因(2026-10-13 真库事故): * 扣库事务里的**留痕查询**写成 `SELECT ... p.name FROM public.profiles p`, * 而 `public.profiles` 只有 `full_name`(列清单:id/username/full_name/phone/avatar_url/department/status/…) * ⇒ `column p.name does not exist` ⇒ **事务 abort** ⇒ 后面扣库语句全被拒 ⇒ 回滚; * 错误被 catch 吞掉,只留一行日志 ⇒ 现象="库存就是扣不掉"。 * 真库实证:BR003 `inventory_logs` 里 `delivery_loading_out`/`picking_out` **0 条**。 */ describe('出库留痕不得拖垮扣库事务', () => { it('④ 审计查询用 full_name;整段留痕用 SAVEPOINT 隔离', () => { expect(outbound).toContain('p.full_name AS name'); expect(outbound).not.toMatch(/SELECT DISTINCT pt\.uid, p\.name/); // SAVEPOINT 三件套:建、释放、失败回滚 expect(outbound).toContain('SAVEPOINT ${outboundAuditSavepoint}'); expect(outbound).toContain('RELEASE SAVEPOINT ${outboundAuditSavepoint}'); expect(outbound).toContain('ROLLBACK TO SAVEPOINT ${outboundAuditSavepoint}'); }); }); /** * 存量兜底:扣库时点前移到「分拣完成」**之前**就已经越过该时点的单,靠调度器捞出来补扣 * (2026-10-13 开发者要求)。真库实证:BR003 有两张单(`…_0002` 米块 8 斤、`…_0003` 四行 63 斤) * 「状态 50、已出库、却无任何出库流水」,本轮已用同一函数补扣完成。 */ describe('出库扣库兜底(存量单)', () => { const jobs = readFileSync(path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8'); it('⑤ 调度器注册了兜底任务,取数在 service、只覆盖未结案的单', () => { expect(jobs).toContain('runOutboundSettleBackfill()'); expect(jobs).toContain('listOrdersMissingOutboundSettlement'); // 节流 10 分钟(与批次计划兜底同款) expect(jobs).toContain('lastOutboundSettleBackfillAt'); // 取数谓词:50–89、近 45 天、有实拣量、无出库流水 expect(outbound).toContain('o.order_status BETWEEN 50 AND 89'); expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')"); // ⚠️ 不得把已结案(90)的单也捞进来:历史结案白名单是有意跳过 FIFO 扣库的 expect(outbound).not.toContain('o.order_status >= 50'); }); }); /** * 分拣出库扣库的**正确性**(2026-10-13 开发者要求逐条核查)。 * * 真库实测(临时单,跑完即清理): * ① 分拣完成 ⇒ 流水 `picking_out` 6.00,批次 22 → 16; * ② 发车再扣(`deductInventoryForOrderDeparture`)⇒ `already_outbound`、批次不变; * ③ 别单挂 6 斤活跃预留后,扣 20 斤被拦:`库存不足,缺少 10(扣除他单预留后可用 10)`。 * * ⚠️ 2026-10-13 变化:`restoreInventoryForOrderDeparture`(发车失败回补)在生产代码里**没有调用方**, * 已按开发者指示作为死代码删除;原先"回补只认 delivery_loading_out"的断言随之移除, * 改为断言"该函数确实不存在",并保留"分拣/核货两种出库类型分开记"的口径。 */ describe('分拣出库扣库:不重复扣 / 不吃他单预留 / 出库必扣', () => { it('⑧ 分拣出库写 picking_out;发车失败回补(死代码)已清理', () => { const funnel = readFileSync(path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8'); const idx = funnel.indexOf('await ensureOrderInventorySettledOnComplete(orderCode, {'); expect(idx).toBeGreaterThan(-1); expect(funnel.slice(idx, idx + 400)).toContain("operationType: 'picking_out'"); // 死代码清理:回补函数不再存在,其 unique 流水类型也没有写入方(历史数据展示文案保留) expect(outbound).not.toContain('export async function restoreInventoryForOrderDeparture'); expect(outbound).not.toContain("'delivery_loading_restore'"); // 两种出库类型仍分开记(备注据此区分:分拣出库 / 配送核货出库) expect(outbound).toContain('分拣出库 ${input.pickCode}'); expect(outbound).toContain('配送核货出库 ${input.pickCode}'); }); it('⑧b 10 分钟兜底补写同样按「分拣出库(picking_out)」记', () => { const jobs = readFileSync(path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8'); const fn = jobs.slice(jobs.indexOf('async function runOutboundSettleBackfill')); expect(fn).toContain("operationType: 'picking_out'"); expect(fn).toContain('ensureOrderInventorySettledOnComplete(orderCode, {'); }); it('⑨ 幂等守卫认两种出库类型 ⇒ 分拣/发车/结案三条路互不重复扣', () => { expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')"); // 三条会扣库的入口都走带守卫的函数 const funnel = readFileSync(path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8'); expect(funnel).toContain('ensureOrderInventorySettledOnComplete(orderCode'); expect(funnel).toContain('deductInventoryForOrderDeparture(orderCode'); expect(outbound).toContain('export async function ensureOrderInventorySettledOnComplete('); }); it('⑩ 扣库不得吃他单活跃预留:先按「毛可用 − 他单预留」校验', () => { const cover = readFileSync(path.join(__dirname, '../src/services/inventoryStockCoverService.ts'), 'utf8'); expect(cover).toContain('sumOtherOrderReservations'); expect(cover).toContain('export async function getClaimableStockQty('); expect(outbound).toContain('respectOtherReservations'); expect(outbound).toContain('扣除他单预留后可用'); }); });