import { readFileSync } from 'node:fs'; import path from 'path'; import { describe, expect, it } from 'vitest'; import { defaultOrderAutoAdvanceConfig, parseOrderAutoAdvanceConfigValue, } from '../src/services/orderAutoAdvanceConfigService'; describe('订单定时强推 + 待补录', () => { it('配置默认关闭,时间非法值回退默认', () => { const def = defaultOrderAutoAdvanceConfig(); expect(def.enabled).toBe(false); expect(def.time).toBe('08:00'); expect(parseOrderAutoAdvanceConfigValue({ enabled: true, time: '9:05' })).toEqual({ enabled: true, time: '09:05', earliestRunDate: null, lastRunDate: null, }); expect(parseOrderAutoAdvanceConfigValue({ enabled: true, time: '25:99' }).time).toBe('08:00'); expect(parseOrderAutoAdvanceConfigValue('{"enabled":true,"time":"07:30"}').enabled).toBe(true); expect(parseOrderAutoAdvanceConfigValue(null).enabled).toBe(false); }); it('强推服务:仅 30/40/45、不再打待补录标记、补产物、建配送任务、写审计', () => { const src = readFileSync( path.join(__dirname, '../src/services/orderAutoAdvanceService.ts'), 'utf8' ); expect(src).toContain('PRE_DELIVERY_STATUSES = [30, 40, 45]'); // 「待补录」中间态已取消(用户 2026-09-15):强推不再打 pending_backfill 标记。 // 约束到「自动推进的 UPDATE 语句」而非全文 —— 原先的 toContain 是全文件匹配, // 而"结案失败恢复标记"那句同名字符串仍存在,导致断言形同虚设(无法真正守住该行为)。 // 见 docs/design/20260915-remove-pending-backfill-state.md const advanceUpdate = src.slice( src.indexOf('// 3) 置待配送'), src.indexOf('RETURNING order_code') ); expect(advanceUpdate.length).toBeGreaterThan(0); expect(advanceUpdate).not.toContain('pending_backfill = TRUE'); expect(advanceUpdate).toContain('order_status = 50'); expect(src).not.toContain('newValue: { order_status: 50, pending_backfill: true }'); expect(src).toContain('auto_advanced_from_status'); expect(src).toContain('ensureInspectionsForOrder'); expect(src).toContain('createPickingTask'); expect(src).toContain('ensureDeliveryTaskForOrder'); // 已有未出库分拣任务时不重复建单 expect(src).toContain('分拣任务已存在'); expect(src).toContain("'order_auto_advance'"); // 只推配送日已到(含当天北京日),未来配送日不扫 expect(src).toContain("o.delivery_date <= (NOW() AT TIME ZONE 'Asia/Shanghai')::date"); }); it('调度挂载:按分公司配置时刻每日一次,北京时间且不依赖服务器时区', () => { const jobs = readFileSync( path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8' ); expect(jobs).toContain('runDailyOrderAutoAdvance'); expect(jobs).toContain('shouldRunOrderAutoAdvanceTick'); expect(jobs).toContain('markOrderAutoAdvanceRan'); expect(jobs).toContain('getOrderAutoAdvanceConfig'); expect(jobs).not.toContain('lastAutoAdvanceKeyByBranch'); // 强推必须按北京时间计算(容器可能跑 UTC),不能用服务器本地时间 const fnStart = jobs.indexOf('async function runDailyOrderAutoAdvance'); const fnSrc = jobs.slice(fnStart, fnStart + 2000); expect(fnSrc).toContain('chinaCalendarParts'); expect(fnSrc).not.toContain('now.getHours()'); // 每次执行都留日志(含 0 单),否则无法区分「没跑」与「没单可推」 expect(fnSrc).toContain('扫描 ${result.scanned},强推 ${result.advanced}'); expect(fnSrc.indexOf('console.log')).toBeLessThan(0 + fnSrc.length); }); it('未分配/竞价中的订单不强推(无履约来源,推了也送不了)', () => { const src = readFileSync( path.join(__dirname, '../src/services/orderAutoAdvanceService.ts'), 'utf8' ); // 扫描与数量预览共用 AUTO_ADVANCE_ELIGIBLE_WHERE_SQL,护栏在其中定义 const guardStart = src.indexOf('AUTO_ADVANCE_ELIGIBLE_WHERE_SQL = `'); const guardSrc = src.slice(guardStart, guardStart + 1200); expect(guardSrc).toContain('UNASSIGNED'); expect(guardSrc).toContain('NOT EXISTS'); expect(src).toContain('${AUTO_ADVANCE_ELIGIBLE_WHERE_SQL}'); }); it('手动触发入口:POST /orders/auto-advance-run', () => { const routes = readFileSync( path.join(__dirname, '../src/modules/workflow/routes/deliveryRoutes.ts'), 'utf8' ); expect(routes).toContain("router.post('/orders/auto-advance-run'"); expect(routes).toContain('autoAdvancePreDeliveryOrdersForBranch'); const web = readFileSync( path.join(__dirname, '../../src/pages/orders/orderManagement/OrderManagementPage.tsx'), 'utf8' ); expect(web).toContain('runOrderAutoAdvanceApi'); expect(web).toContain('立即执行一次'); }); it('配置弹窗展示当前可强推订单数(与定时扫描同一口径)', () => { const svc = readFileSync( path.join(__dirname, '../src/services/orderAutoAdvanceService.ts'), 'utf8' ); // 扫描与计数共用同一段 WHERE,防止两处口径漂移 expect(svc).toContain('AUTO_ADVANCE_ELIGIBLE_WHERE_SQL'); expect(svc).toContain('export async function countAutoAdvanceEligibleOrders'); const routes = readFileSync( path.join(__dirname, '../src/modules/workflow/routes/deliveryRoutes.ts'), 'utf8' ); expect(routes).toContain('eligible_count'); expect(routes).toContain('countAutoAdvanceEligibleOrders'); const web = readFileSync( path.join(__dirname, '../../src/pages/orders/orderManagement/OrderManagementPage.tsx'), 'utf8' ); expect(web).toContain('当前可强推订单'); expect(web).toContain('autoAdvanceEligibleCount'); }); it('展示层不回退强推状态:pendingBackfill 时禁止按事实降级落库', () => { const display = readFileSync( path.join(__dirname, '../src/services/orderStatusDisplayService.ts'), 'utf8' ); expect(display).toContain('pendingBackfill'); const pickStart = display.indexOf('export function pickDisplayOrderStatus'); const pickSrc = display.slice(pickStart, pickStart + 1200); // 待补录守卫必须在「备货未完成回退」之前生效 expect(pickSrc.indexOf('pendingBackfill')).toBeLessThan( pickSrc.indexOf('fulfillmentIncomplete') ); const query = readFileSync( path.join(__dirname, '../src/services/orderManagementQueryService.ts'), 'utf8' ); expect(query).toContain('pendingBackfill: row.pending_backfill === true'); }); it('结案分流:待补录只物理结案不入账;对账不结案待补录单', () => { const fulfill = readFileSync( path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8' ); const finalizeStart = fulfill.indexOf('finalizeOrderFulfillmentCore'); const core = fulfill.slice(finalizeStart, finalizeStart + 4000); expect(core).toContain('pending_backfill'); expect(fulfill).toContain('insertSignRecordIdempotent'); expect(fulfill).toContain('SAVEPOINT sign_record_insert'); expect(fulfill).toContain('ROLLBACK TO SAVEPOINT sign_record_insert'); // 分流发生在零价校验与置 90 之前 expect(core.indexOf('pending_backfill === true')).toBeLessThan( core.indexOf('assertNoZeroPriceItems') ); const reconcile = readFileSync( path.join(__dirname, '../src/services/orderStatusReconcileService.ts'), 'utf8' ); expect(reconcile).toContain('pending_backfill'); expect(reconcile).toContain('!pendingBackfill'); }); it('确认入账:校验无遗留待验/待分拣,失败恢复标记', () => { const src = readFileSync( path.join(__dirname, '../src/services/orderAutoAdvanceService.ts'), 'utf8' ); const start = src.indexOf('export async function confirmBackfillAndFinalize'); const body = src.slice(start); expect(body).toContain('countPendingInspections'); expect(body).toContain('countUnfinishedBackfillPickingItems'); expect(body).not.toContain('countUnfinishedPickingTasks'); const countFn = readFileSync( path.join(__dirname, '../src/services/orderWorkflowFulfillmentService.ts'), 'utf8' ); const countStart = countFn.indexOf('export async function countPendingInspections'); const countNext = countFn.indexOf('export async function countPendingPickingTasks'); const countBody = countFn.slice(countStart, countNext > countStart ? countNext : countStart + 1800); expect(countBody).toContain('skuDirectDeliveryAppliesSql'); expect(countBody).toContain('supplierSkipInboundExistsSql'); expect(countBody).toContain('i.supplier_code'); expect(countBody).toContain('FROM order_items oi'); expect(countBody).toContain('COALESCE(oi.is_returned, false) = false'); expect(countBody).toContain('i.sku_code IS NOT DISTINCT FROM oi.sku_code'); const handler = readFileSync( path.join(__dirname, '../src/modules/handlers/inspectionHandler.ts'), 'utf8' ); expect(handler).toContain('countPendingInspections'); // 未入库明细拦截:无合格入库记录且未被库存抵扣/直送覆盖的行,禁止结案(防 phantom 应收) expect(body).toContain('items_not_inbounded'); expect(body).toContain('ensureBackfillInboundOnConfirm'); expect(body).toContain("supplierSkipInboundExistsSql"); expect(body).toContain('未验收入库'); expect(body).toContain('pending_backfill = FALSE'); expect(body).toContain('finalizeOrderFulfillment'); // 结案失败恢复标记 expect(body.indexOf('pending_backfill = TRUE')).toBeGreaterThan( body.indexOf('pending_backfill = FALSE') ); const routes = readFileSync( path.join(__dirname, '../src/modules/workflow/routes/deliveryRoutes.ts'), 'utf8' ); expect(routes).toContain("router.post('/orders/confirm-backfill'"); expect(routes).toContain("router.get('/orders/auto-advance-config'"); expect(routes).toContain("router.put('/orders/auto-advance-config'"); }); it('迁移与列表查询:pending_backfill 字段、过滤、统计', () => { const migration = readFileSync( path.join(__dirname, '../../migrations/20260854_order_pending_backfill.sql'), 'utf8' ); expect(migration).toContain('pending_backfill'); expect(migration).toContain('auto_advanced_from_status'); const query = readFileSync( path.join(__dirname, '../src/services/orderManagementQueryService.ts'), 'utf8' ); expect(query).toContain('pending_backfill'); expect(query).toContain('AS backfill'); expect(query).toContain('inspection_fail_items'); expect(query).toContain('fetchUnresolvedFailedInspectionItemsBatch'); }); it('Web:待补录标记、确认入账按钮、定时强推配置入口', () => { const web = readFileSync( path.join(__dirname, '../../src/pages/orders/orderManagement/OrderManagementPage.tsx'), 'utf8' ); expect(web).toContain('待补录'); expect(web).toContain('confirmOrderBackfillApi'); expect(web).toContain('handleConfirmBackfill'); expect(web).toContain('confirmLedgerMessage'); expect(web).toContain('定时强推'); // 「待补录」筛选入口(backfillOnly 状态与顶部筛选卡片)已移除 // (用户 2026-09-15 决定清理该状态;线上待补录单已清零、后端已停写该标记)。 // 见提交 988d571(前端批次1)。 expect(web).not.toContain('backfillOnly'); expect(web).toContain('savePendingBackfillReceivedQtyApi'); // 「保存实收」按钮已并入主「保存」(设计 20260829-save-received-qty-merge) expect(web).not.toContain('保存实收'); expect(web).toContain('collectDirtyReceivedQtyLines'); const helpers = readFileSync( path.join(__dirname, '../../src/pages/orders/orderManagement/orderManagementHelpers.ts'), 'utf8' ); // Order 类型与响应映射中的 pending_backfill 已随「待补录」状态清理移除 // (提交 988d571 前端批次1)。 expect(helpers).not.toContain('pending_backfill'); }); });