import { beforeEach, describe, expect, it, vi } from 'vitest'; import { readFileSync } from 'node:fs'; /** * 极简流转「录单 → 智能分配 → 直接待配送」(2026-10-07,用户批准)。 * * 设计见 docs/design/20261007-direct-to-delivery-mode.md,四条硬约束: * ① **默认关闭**,关闭时行为与现状逐字一致;② 只对新单(刚分配完、状态 30 的单)生效; * ③ 不建验收单(跳过 `ensureInspectionsForOrder`)、不建分拣待办,但**必须补核货行** * (否则发车被 `no_loading_items` 拦);④ 不碰状态链常量、不碰分配信号量。 * * 这里把 DB / 补行 / 建配送任务换成假件,钉住「编排」层面的行为。 */ const dbMocks = vi.hoisted(() => ({ query: vi.fn() })); const loadingMocks = vi.hoisted(() => ({ ensureSkipInboundLoadingLines: vi.fn() })); const deliveryTaskMocks = vi.hoisted(() => ({ ensureDeliveryTaskForOrder: vi.fn() })); vi.mock('../src/db', () => ({ pool: { query: dbMocks.query }, // tenantScope 的惰性查询依赖此导出;补 mock 避免新增动态回写模块后 suite 崩。 getRawPoolQuery: () => dbMocks.query, })); vi.mock('../src/services/skipInboundLoadingService', () => ({ ensureSkipInboundLoadingLines: loadingMocks.ensureSkipInboundLoadingLines, })); vi.mock('../src/services/orderWorkflowFulfillmentService', () => ({ ensureDeliveryTaskForOrder: deliveryTaskMocks.ensureDeliveryTaskForOrder, })); const directDeliveryMocks = vi.hoisted(() => ({ isOrderOnlyDirectDelivery: vi.fn() })); vi.mock('../src/services/skuDirectDelivery', () => ({ isOrderOnlyDirectDelivery: directDeliveryMocks.isOrderOnlyDirectDelivery, skuDirectDeliveryAppliesSql: () => 'FALSE', })); import { applyDirectToDeliveryAfterAllocation } from '../src/services/directToDeliveryService'; import { setDirectToDeliveryConfig, invalidateDirectToDeliveryCache } from '../src/services/directToDeliveryConfigService'; const ORDER = 'ORD_WEB_20261007_BR002_0001'; /** 开关值 + 订单状态 → 假 DB;返回收到的 SQL 列表(可断言"有没有写") */ function mockDb(opts: { enabled: boolean; orderStatus?: number | null; advanceMatches?: boolean }) { const calls: string[] = []; dbMocks.query.mockImplementation(async (sql: unknown) => { const text = String(sql); calls.push(text); if (/FROM (public\.)?system_configs/i.test(text)) { return opts.enabled ? { rows: [{ config_value: { enabled: true } }], rowCount: 1 } : { rows: [], rowCount: 0 }; } if (/SELECT order_status, branch_code FROM orders/i.test(text)) { if (opts.orderStatus == null) return { rows: [], rowCount: 0 }; return { rows: [{ order_status: opts.orderStatus, branch_code: 'BR002' }], rowCount: 1 }; } if (/UPDATE supplier_preparations/i.test(text)) return { rows: [], rowCount: 2 }; if (/INSERT INTO order_item_fulfillments/i.test(text)) return { rows: [], rowCount: 3 }; if (/UPDATE purchase_orders/i.test(text)) return { rows: [], rowCount: 1 }; if (/UPDATE orders/i.test(text)) { const ok = opts.advanceMatches !== false; return { rows: ok ? [{ order_code: ORDER }] : [], rowCount: ok ? 1 : 0 }; } return { rows: [], rowCount: 0 }; }); return calls; } const anyWrite = (calls: string[]) => calls.some((sql) => /^\s*(INSERT|UPDATE|DELETE)/i.test(sql)); describe('极简流转:分配完成后直接待配送', () => { beforeEach(() => { dbMocks.query.mockReset(); loadingMocks.ensureSkipInboundLoadingLines.mockReset(); loadingMocks.ensureSkipInboundLoadingLines.mockResolvedValue(undefined); deliveryTaskMocks.ensureDeliveryTaskForOrder.mockReset(); deliveryTaskMocks.ensureDeliveryTaskForOrder.mockResolvedValue(undefined); directDeliveryMocks.isOrderOnlyDirectDelivery.mockReset(); directDeliveryMocks.isOrderOnlyDirectDelivery.mockResolvedValue(false); // 开关读的是 5 秒缓存(分配里要逐明细判断)——每个用例前清掉,避免串味 invalidateDirectToDeliveryCache(); }); it('开关关闭(默认)⇒ 什么都不做,一个写操作都没有', async () => { const calls = mockDb({ enabled: false, orderStatus: 30 }); const result = await applyDirectToDeliveryAfterAllocation(ORDER, 'BR002'); expect(result.advanced).toBe(false); expect(anyWrite(calls)).toBe(false); expect(loadingMocks.ensureSkipInboundLoadingLines).not.toHaveBeenCalled(); expect(deliveryTaskMocks.ensureDeliveryTaskForOrder).not.toHaveBeenCalled(); }); it('开关开启 + 订单 30 ⇒ 备货单置完成、补核货行、置 50 并留痕、建配送任务', async () => { const calls = mockDb({ enabled: true, orderStatus: 30 }); const result = await applyDirectToDeliveryAfterAllocation(ORDER, 'BR002'); expect(result.advanced).toBe(true); // ① 备货单自动完成(不进待采/待备货待办) const prepSql = calls.find((sql) => /UPDATE supplier_preparations/i.test(sql)) || ''; expect(prepSql).toMatch(/prepare_status = 30/); expect(prepSql).toMatch(/prepare_time = COALESCE\(prepare_time, NOW\(\)\)/); expect(prepSql).not.toMatch(/updated_at/); // ①a 写「配送直供」履约来源:这是「不建备货单/采购单」后仍能通过覆盖断言的关键 const coverSql = calls.find((sql) => /INSERT INTO order_item_fulfillments/i.test(sql)) || ''; expect(coverSql).toMatch(/direct_delivery_cover/); expect(coverSql).toMatch(/ON CONFLICT \(order_item_id\) DO UPDATE/); // 已有来源的行不许被改写(否则会触发 order_item_fulfillment_one_source 约束) expect(coverSql).toMatch(/WHERE order_item_fulfillments\.supplier_preparation_id IS NULL/); expect(coverSql).toMatch(/AND order_item_fulfillments\.purchase_code IS NULL/); // ①b 自采自动完成:写 20(完成自采),且只碰仍在待办的口径 (10,32) const buySql = calls.find((sql) => /UPDATE purchase_orders/i.test(sql)) || ''; expect(buySql).toMatch(/purchase_status = 20/); expect(buySql).toMatch(/IN \(10, 32\)/); expect(buySql).not.toMatch(/purchase_status = 30/); // ② 补核货行:走免入库那条路,但要求「所有明细」(否则发车被 no_loading_items 拦) expect(loadingMocks.ensureSkipInboundLoadingLines).toHaveBeenCalledWith(ORDER, undefined, { includeAllItems: true }); // ③ 置 50 + 痕迹 const advance = calls.find((sql) => /UPDATE orders/i.test(sql)) || ''; expect(advance).toMatch(/order_status = 50/); expect(advance).toMatch(/auto_advanced_from_status = 30/); expect(advance).toMatch(/order_status = 30/); // 并发门槛:只推进仍处于 30 的单 // ④ 建配送任务 expect(deliveryTaskMocks.ensureDeliveryTaskForOrder).toHaveBeenCalledWith(ORDER, 'BR002'); }); it('订单不在 30(已 40/50/90)⇒ 不碰它,避免把人工推进的单拉回来', async () => { for (const status of [20, 40, 45, 50, 60, 90]) { const calls = mockDb({ enabled: true, orderStatus: status }); const result = await applyDirectToDeliveryAfterAllocation(ORDER, 'BR002'); expect(result.advanced).toBe(false); expect(anyWrite(calls)).toBe(false); } expect(loadingMocks.ensureSkipInboundLoadingLines).not.toHaveBeenCalled(); expect(deliveryTaskMocks.ensureDeliveryTaskForOrder).not.toHaveBeenCalled(); }); it('并发下没抢到(置 50 的 UPDATE 未命中)⇒ 不建配送任务', async () => { mockDb({ enabled: true, orderStatus: 30, advanceMatches: false }); const result = await applyDirectToDeliveryAfterAllocation(ORDER, 'BR002'); expect(result.advanced).toBe(false); expect(deliveryTaskMocks.ensureDeliveryTaskForOrder).not.toHaveBeenCalled(); }); it('全单商品直送 ⇒ 跳过(否则推到 50 却没有核货行,发车会被 no_loading_items 拦死)', async () => { const calls = mockDb({ enabled: true, orderStatus: 30 }); directDeliveryMocks.isOrderOnlyDirectDelivery.mockResolvedValue(true); const result = await applyDirectToDeliveryAfterAllocation(ORDER, 'BR002'); expect(result.advanced).toBe(false); expect(result.message).toContain('直送'); expect(anyWrite(calls)).toBe(false); expect(loadingMocks.ensureSkipInboundLoadingLines).not.toHaveBeenCalled(); expect(deliveryTaskMocks.ensureDeliveryTaskForOrder).not.toHaveBeenCalled(); }); it('缺订单号 ⇒ 直接跳过', async () => { const result = await applyDirectToDeliveryAfterAllocation('', 'BR002'); expect(result.advanced).toBe(false); expect(dbMocks.query).not.toHaveBeenCalled(); }); }); /** * 契约(源码级):把「默认关闭」「写开关必须带分公司」「分配侧跳过验收单」三件事钉住, * 避免以后被人顺手改成默认开启、或把验收单又建回来。 */ describe('极简流转:源码契约', () => { const configSrc = readFileSync(new URL('../src/services/directToDeliveryConfigService.ts', import.meta.url), 'utf8'); const allocationSrc = readFileSync(new URL('../src/services/orderAllocationService.ts', import.meta.url), 'utf8'); const routeSrc = readFileSync(new URL('../src/modules/workflow/routes/orderRoutes.ts', import.meta.url), 'utf8'); const loadingSrc = readFileSync(new URL('../src/services/skipInboundLoadingService.ts', import.meta.url), 'utf8'); const modeDoc = readFileSync(new URL('../../docs/design/20261007-direct-to-delivery-mode.md', import.meta.url), 'utf8'); it('默认关闭:缺省配置 enabled=false,且没有分公司时拒绝写入', () => { expect(configSrc).toMatch(/const DEFAULT_CONFIG: DirectToDeliveryConfig = \{\s*enabled: false,\s*\}/); expect(configSrc).toMatch(/enabled: enabled === true/); expect(configSrc).toMatch(/operating_branch_required/); }); it('无分公司时 setDirectToDeliveryConfig 直接报错(避免误写成全局开启)', async () => { dbMocks.query.mockReset(); await expect(setDirectToDeliveryConfig('', true)).rejects.toMatchObject({ code: 'operating_branch_required' }); expect(dbMocks.query).not.toHaveBeenCalled(); }); it('分配侧:开关开启时跳过建验收单,改走极简流转', () => { expect(allocationSrc).toMatch(/isDirectToDeliveryEnabled\(orderBranchCode\)/); expect(allocationSrc).toMatch(/applyDirectToDeliveryAfterAllocation\(orderCode, orderBranchCode\)/); // ensureInspectionsForOrder 必须留在 else 分支(开启极简流转时不建验收单) // 窗口放宽到 700:else 分支内 2026-10-12 新增了「分配即供货完成」的 finalize 调用在前。 expect(allocationSrc).toMatch(/\} else if \(result\.preparationsCreated > 0 \|\| result\.orderStatusUpdated === 30\) \{[\s\S]{0,700}ensureInspectionsForOrder/); }); it('备货单完成用 prepare_time 而非 updated_at(该表没有 updated_at,写错会静默不生效)', () => { const src = readFileSync(new URL('../src/services/directToDeliveryService.ts', import.meta.url), 'utf8'); expect(src).toMatch(/prepare_time = COALESCE\(prepare_time, NOW\(\)\)/); // 只看那段 SQL 本身(注释里会提到 updated_at 这个坑,不能一并算进去) const prepSql = src.slice(src.indexOf('UPDATE supplier_preparations'), src.indexOf('UPDATE supplier_preparations') + 400); expect(prepSql).not.toMatch(/updated_at/); // 与既有实现同款谓词:缺货行、已转采购行不动 expect(src).toMatch(/COALESCE\(is_stockout, false\) = false/); expect(src).toMatch(/COALESCE\(transferred_to_purchase, false\) = false/); }); it('读写都必须显式走 public.system_configs(写接口在租户上下文、读取是裸 pool,schema 不一致会静默失效)', () => { // 2026-10-07 实测:不写全 schema 时,界面保存的行落在 tenant_brXXX,而分配后读取落在 public ⇒ 永远读到关闭 expect(configSrc).not.toMatch(/FROM system_configs\b/); expect(configSrc).toMatch(/FROM public\.system_configs/); expect(configSrc).toMatch(/INSERT INTO public\.system_configs/); expect(configSrc).toMatch(/UPDATE public\.system_configs/); }); it('开关只按分公司取值:没有分公司一律关闭,不回退全局行', async () => { // 就算库里存在一个「全局已开启」的行,也不许被命中 dbMocks.query.mockReset(); dbMocks.query.mockResolvedValue({ rows: [{ config_value: { enabled: true } }], rowCount: 1 }); const { getDirectToDeliveryConfig } = await import('../src/services/directToDeliveryConfigService'); await expect(getDirectToDeliveryConfig(null)).resolves.toEqual({ enabled: false }); await expect(getDirectToDeliveryConfig('')).resolves.toEqual({ enabled: false }); expect(dbMocks.query).not.toHaveBeenCalled(); }); it('补核货行复用免入库那条路,并支持 includeAllItems', () => { expect(loadingSrc).toMatch(/options\?\.includeAllItems === true/); // 免入库标志、以及「备货单已完成」这条 EXISTS,都只在**非**极简流转时要求: // 否则全量库存抵扣(没有备货单)的单会一行核货行都补不出来 ⇒ 发车被 no_loading_items 拦死 expect(loadingSrc).toMatch(/includeAllItems \? 'TRUE' : supplierSkipInboundExistsSql/); expect(loadingSrc).toMatch(/const preparationReadyCondition = includeAllItems\s*\n?\s*\? 'TRUE'/); expect(loadingSrc).toMatch(/AND \$\{preparationReadyCondition\}/); }); it('自采自动完成写 20 且只碰待办口径 (10,32)(与角标/列表同口径,且 30/32 只能由验收写)', () => { const src = readFileSync(new URL('../src/services/directToDeliveryService.ts', import.meta.url), 'utf8'); const badge = readFileSync(new URL('../src/services/orderStatusDisplayService.ts', import.meta.url), 'utf8'); const list = readFileSync(new URL('../src/services/purchaseOrderQueryService.ts', import.meta.url), 'utf8'); // 三处口径必须一致:完成写 20、角标与列表都按 (10,32) 计待办 expect(src).toMatch(/COALESCE\(purchase_status, 10\) IN \(10, 32\)/); expect(badge).toMatch(/COALESCE\(po\.purchase_status, 10\) IN \(10, 32\)/); expect(list).toMatch(/po\.purchase_status IN \(10, 32\)/); }); it('分配侧:极简模式下不建采购单、不建备货单(两个创建点按开关短路)', () => { expect(allocationSrc).toMatch(/if \(await isDirectToDeliveryEnabled\(params\.branchCode\)\) return false;/); expect(allocationSrc).toMatch(/if \(await isDirectToDeliveryEnabled\(params\.branchCode\)\) \{\s*\n\s*return \{ created: false \};/); }); it('分配内部:覆盖检查之前必须先补「配送直供」来源(否则会报「未能进入自采或备货」)', () => { const fnAt = allocationSrc.indexOf('async function forceCoverUnfulfilledOrderItems'); const callAt = allocationSrc.indexOf('await ensureDirectDeliveryCoverRows(client, orderCode, branchCode)'); const itemCheckAt = allocationSrc.indexOf('if (!(await isOrderItemFulfilled(orderCode, item, client)))'); expect(fnAt).toBeGreaterThan(-1); expect(callAt).toBeGreaterThan(fnAt); // 在该函数内 expect(itemCheckAt).toBeGreaterThan(callAt); // 且在逐条判定之前 }); it('覆盖判定接受「配送直供」来源(两条查询共用同一份判据)', () => { const fulfill = readFileSync(new URL('../src/services/orderItemFulfillmentService.ts', import.meta.url), 'utf8'); // 2026-10-13 收口:判据只有一份(FULFILLED_BRANCHES_SQL),两条查询引用它 expect(fulfill.match(/OR COALESCE\(f\.direct_delivery_cover, false\) = true/g)?.length).toBe(1); expect(fulfill.match(/\$\{FULFILLED_BRANCHES_SQL\}/g)?.length).toBe(2); expect(fulfill).toContain('const FULFILLED_BRANCHES_SQL ='); }); it('扣库也跳过「配送直供」行(否则完成配送/结案会抛「库存不足」+ 弹红字)', () => { const outbound = readFileSync(new URL('../src/services/inventoryOutboundService.ts', import.meta.url), 'utf8'); // 两条扣库路径(发车扣库、结案前扣库计划)的取数都要带上直供标记 expect((outbound.match(/AS direct_delivery_cover/g) || []).length).toBe(2); // 发车扣库循环跳过(2026-10-07 起同口径再加「加菜」) expect(outbound).toMatch(/if \(skipInbound \|\| skuDirect \|\| directDeliveryCover \|\| extraDish\) continue;/); // 结案前扣库计划跳过 expect(outbound).toMatch(/row\.direct_delivery_cover === true/); }); it('加菜不参与扣库:两条扣库路径都取 is_extra_dish 并跳过', () => { const outbound = readFileSync(new URL('../src/services/inventoryOutboundService.ts', import.meta.url), 'utf8'); // 两处取数(发车扣库、结案前补扣计划)都要带加菜标记 expect((outbound.match(/AS is_extra_dish/g) || []).length).toBe(2); // 两处跳过判断都要含加菜 expect((outbound.match(/row\.is_extra_dish === true/g) || []).length).toBe(2); expect(outbound).toMatch(/if \(skipInbound \|\| skuDirect \|\| directDeliveryCover \|\| extraDish\) continue;/); }); it('迁移:新增 direct_delivery_cover 列,并放宽 order_item_fulfillment_one_source 约束', () => { const migration = readFileSync(new URL('../../migrations/20261007_direct_delivery_cover.sql', import.meta.url), 'utf8'); expect(migration).toMatch(/ADD COLUMN IF NOT EXISTS direct_delivery_cover BOOLEAN NOT NULL DEFAULT FALSE/); expect(migration).toMatch(/DROP CONSTRAINT IF EXISTS order_item_fulfillment_one_source/); expect(migration).toMatch(/ADD CONSTRAINT order_item_fulfillment_one_source CHECK/); // 必须遍历各租户 schema(迁移器按文件执行一次、不改 search_path) expect(migration).toMatch(/information_schema\.tables/); expect(migration).toMatch(/EXECUTE format\(/); }); it('直送守卫与既有「待配送定时强推」同一条(源码契约)', () => { const src = readFileSync(new URL('../src/services/directToDeliveryService.ts', import.meta.url), 'utf8'); const advanceSrc = readFileSync(new URL('../src/services/orderAutoAdvanceService.ts', import.meta.url), 'utf8'); expect(src).toMatch(/isOrderOnlyDirectDelivery\(code\)/); expect(advanceSrc).toMatch(/isOrderOnlyDirectDelivery\(code\)/); expect(src).toContain('全单商品直送,交给直送流程'); }); it('录单提交路径在 COMMIT 之后也触发一次(外部事务下分配侧钩子不会执行)', () => { const submitSrc = readFileSync(new URL('../src/services/customerOrderSubmitService.ts', import.meta.url), 'utf8'); // 必须出现在 client.query('COMMIT') 之后 const commitAt = submitSrc.indexOf("await client.query('COMMIT');"); const callAt = submitSrc.indexOf('await applyDirectToDeliveryAfterAllocation(orderCode, input.branchCode);'); expect(commitAt).toBeGreaterThan(-1); expect(callAt).toBeGreaterThan(commitAt); // 失败不得影响下单 expect(submitSrc).toMatch(/\[customerOrderSubmit\] 极简流转失败(不影响下单)/); }); it('开关判定以订单行分公司为准(调用方可能不传分公司)', () => { const src = readFileSync(new URL('../src/services/directToDeliveryService.ts', import.meta.url), 'utf8'); // 先读订单,再判开关;分公司取 order.branch_code || 入参 const orderAt = src.indexOf('SELECT order_status, branch_code FROM orders'); const switchAt = src.indexOf('isDirectToDeliveryEnabled(branch)'); expect(orderAt).toBeGreaterThan(-1); expect(switchAt).toBeGreaterThan(orderAt); expect(src).toMatch(/order\.branch_code \|\| branchCode/); }); it('接口成对存在,且读接口给的是 enabled 布尔', () => { expect(routeSrc).toMatch(/router\.get\('\/orders\/direct-to-delivery-config'/); expect(routeSrc).toMatch(/router\.put\('\/orders\/direct-to-delivery-config'/); expect(routeSrc).toMatch(/isDirectToDeliveryEnabled\(branchCode\)/); expect(routeSrc).toMatch(/setDirectToDeliveryConfig\(branchCode, req\.body\.enabled/); }); it('设计文档把「不碰状态链常量 / 分配信号量」「只对新单」写清楚', () => { expect(modeDoc).toContain('不动 `ORDER_STATUS_ALLOWED`'); expect(modeDoc).toContain('只对新单生效'); }); });