// app/service/systems/intercept_auto_confirm.js 'use strict'; const MainService = require('../main'); // 允许确认拦截(更新为 intercepted_at_warehouse)的前置拦截状态白名单: // 拦截发起中(requested/requesting/intercepting)与历史遗留值 intercepted。 // 其余状态一律不允许确认拦截,防止并发修改导致误更新。 const CONFIRMABLE_INTERCEPT_STATUSES = Object.freeze([ 'requested', 'requesting', 'intercepting', 'intercepted' ]); // 自动确认扫描命中的拦截状态:仅请求拦截(requested) const AUTO_CONFIRM_INTERCEPT_STATUS = 'requested'; // 自动确认扫描要求的面单打印状态:未打印 const AUTO_CONFIRM_PRINT_STATUS = 'none'; // 拦截时间超时阈值(小时):intercept_time 超过 12 小时自动确认 const INTERCEPT_TIME_TIMEOUT_HOURS = 12; // 创建时间超时阈值(小时):create_at 超过 36 小时自动确认 const CREATE_AT_TIMEOUT_HOURS = 36; // 拦截时间超时阈值(毫秒),供口径镜像函数使用 const INTERCEPT_TIME_TIMEOUT_MS = INTERCEPT_TIME_TIMEOUT_HOURS * 60 * 60 * 1000; // 创建时间超时阈值(毫秒),供口径镜像函数使用 const CREATE_AT_TIMEOUT_MS = CREATE_AT_TIMEOUT_HOURS * 60 * 60 * 1000; // 单批扫描数量上限(分页扫描,避免单批过大) const SCAN_BATCH_SIZE = 100; // 单批确认数量上限(批量确认,避免单批过大) const CONFIRM_BATCH_SIZE = 100; // 仓库当前表分表名匹配模式:wms_order_delivery_{warehouseId}(不含 history/dispatch/outsourced) const CURRENT_SHARD_TABLE_PATTERN = /^wms_order_delivery_(\d+)$/; // 定时任务自动确认的操作人(无用户上下文) const AUTO_CONFIRM_OPERATOR = Object.freeze({ id: null, name: '系统' }); /** * 将任意时间值转换为毫秒时间戳,无法解析时返回 null。 * * @param {*} value 时间值(Date / 日期字符串 / 数字)。 * @return {number|null} 毫秒时间戳或 null。 */ function toTimestamp(value) { if (value === null || value === undefined || value === '') { return null; } if (value instanceof Date) { const time = value.getTime(); return Number.isFinite(time) ? time : null; } if (typeof value === 'number') { return Number.isFinite(value) ? value : null; } const parsed = Date.parse(String(value)); return Number.isFinite(parsed) ? parsed : null; } /** * 自动库内拦截确定服务。 * * 背景:订单发起拦截(intercept_status='requested')后若人工迟迟未做「库内拦截确定」, * 订单会长期停留在拦截发起中。本服务定时扫描待处理表(current 分表),对 * 「intercept_status='requested' 且 print_status='none'(面单未打印)」的订单, * 满足以下任一条件时自动执行库内拦截确定: * - intercept_time 超过 12 小时(NULL 自然不命中,无需特判); * - create_at 超过 36 小时。 * * 本服务同时提供 confirmInterceptForOrderIds 作为库内拦截确定的内部实现, * systemMethods/order/recheckOrder.js 的 confirmIntercept 出口复用该方法, * 定时任务同样复用,保证两条链路行为一致。 */ class InterceptAutoConfirmService extends MainService { /** * 在当前调用内临时注入 ctx.user 上下文,并在结束后恢复。 * * 用于复用依赖登录上下文的既有 service 能力(如储位取消分配读取 ctx.user.store_id), * 避免扩大影响范围。 * * @param {Object} patchUser 需要覆盖的用户上下文字段。 * @param {Function} callback 业务回调。 * @return {Promise} 回调执行结果。 */ async withPatchedCtxUser(patchUser, callback) { const { ctx } = this; const originUser = ctx.user; const safeOriginUser = originUser && typeof originUser === 'object' ? originUser : {}; const safePatchUser = patchUser && typeof patchUser === 'object' ? patchUser : {}; ctx.user = { ...safeOriginUser, ...safePatchUser, }; try { return await callback(); } finally { ctx.user = originUser; } } /** * 枚举库内全部仓库的当前订单分表(wms_order_delivery_{warehouseId})对应的仓库ID。 * * 通过 INFORMATION_SCHEMA 枚举真实存在的物理分表,比查询 wms_warehouse 更可靠: * 避免仓库配置表与物理分表不一致(如已建表未配置、已停用仓库残留分表)导致的漏扫; * history/dispatch/outsourced 等表位通过表名正则过滤,仅保留 current 表位。 * * @return {Promise} 仓库ID列表。 */ async listCurrentWarehouseIds() { const { ctx } = this; const rows = await ctx.model.query( 'SELECT TABLE_NAME AS tableName' + ' FROM INFORMATION_SCHEMA.TABLES' + ' WHERE TABLE_SCHEMA = DATABASE()' + ' AND TABLE_NAME LIKE \'wms_order_delivery\\_%\'' + ' ORDER BY TABLE_NAME', { type: ctx.model.QueryTypes.SELECT } ); const warehouseIds = []; for (const row of (Array.isArray(rows) ? rows : [])) { const tableName = String(row.tableName || row.TABLE_NAME || '').trim(); const matched = CURRENT_SHARD_TABLE_PATTERN.exec(tableName); if (!matched) { continue; } const warehouseId = Number(matched[1]); if (Number.isInteger(warehouseId) && warehouseId > 0) { warehouseIds.push(warehouseId); } } return Array.from(new Set(warehouseIds)); } /** * 构造自动确认候选订单的 SQL 过滤条件(不含 warehouse_id 与 id 分页条件)。 * * 口径: * - intercept_status = 'requested'(请求拦截); * - print_status = 'none'(面单未打印); * - 满足任一超时条件:intercept_time 超过 12 小时,或 create_at 超过 36 小时; * 时间比较使用数据库侧 NOW()/DATE_SUB,避免应用与数据库时钟偏差; * intercept_time 为 NULL 时小于比较自然不命中,无需特判。 * * @return {string} SQL 过滤条件片段。 */ buildCandidateWhereSql() { return `intercept_status = '${AUTO_CONFIRM_INTERCEPT_STATUS}'` + ` AND print_status = '${AUTO_CONFIRM_PRINT_STATUS}'` + ' AND (' + ` intercept_time < DATE_SUB(NOW(), INTERVAL ${INTERCEPT_TIME_TIMEOUT_HOURS} HOUR)` + ` OR create_at < DATE_SUB(NOW(), INTERVAL ${CREATE_AT_TIMEOUT_HOURS} HOUR)` + ' )'; } /** * 候选订单口径镜像函数:判断单行是否命中自动确认条件(12h/36h 口径)。 * * 与 buildCandidateWhereSql 的 SQL 口径保持一致,供单元测试验证边界语义; * 生产扫描以 SQL 为准。 * * @param {Object} fields 订单行字段。 * @param {string} [fields.interceptStatus] 拦截状态。 * @param {string} [fields.printStatus] 面单打印状态。 * @param {Date|string|number|null} [fields.interceptTime] 拦截时间(可空)。 * @param {Date|string|number|null} [fields.createAt] 创建时间。 * @param {Date} [now=new Date()] 当前时间基准。 * @return {boolean} 是否命中自动确认条件。 */ matchesAutoConfirmCriteria(fields = {}, now = new Date()) { const row = fields && typeof fields === 'object' ? fields : {}; const interceptStatus = String(row.interceptStatus ?? '').trim(); const printStatus = String(row.printStatus ?? '').trim(); const nowMs = now instanceof Date ? now.getTime() : toTimestamp(now); if (interceptStatus !== AUTO_CONFIRM_INTERCEPT_STATUS || printStatus !== AUTO_CONFIRM_PRINT_STATUS) { return false; } const interceptMs = toTimestamp(row.interceptTime); if (interceptMs !== null && interceptMs < nowMs - INTERCEPT_TIME_TIMEOUT_MS) { return true; } const createMs = toTimestamp(row.createAt); if (createMs !== null && createMs < nowMs - CREATE_AT_TIMEOUT_MS) { return true; } return false; } /** * 解析并校验仓库当前订单分表名。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 可直接拼接到 SQL 的表名(仅含字母数字下划线)。 */ resolveCurrentTableName(warehouseId) { const normalizedWarehouseId = Number(warehouseId); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error(`非法仓库ID: ${warehouseId}`); } const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory; if (!factory || typeof factory.generateTableName !== 'function') { throw new Error('订单工厂不可用'); } const tableName = String(factory.generateTableName(normalizedWarehouseId, 'current') || '').trim(); if (!/^[a-zA-Z0-9_]+$/.test(tableName)) { throw new Error(`订单表名不合法: ${tableName}`); } return tableName; } /** * 分页扫描指定仓库的自动确认候选订单ID(id 游标翻页,避免 OFFSET 深翻页)。 * * @param {number|string} warehouseId 仓库ID。 * @param {number} [batchSize=SCAN_BATCH_SIZE] 单批扫描数量。 * @return {Promise} 命中条件的订单ID列表。 */ async scanCandidateOrderIds(warehouseId, batchSize = SCAN_BATCH_SIZE) { const { ctx } = this; const tableName = this.resolveCurrentTableName(warehouseId); const candidateWhereSql = this.buildCandidateWhereSql(); const normalizedBatchSize = Math.max(Number.parseInt(batchSize, 10) || SCAN_BATCH_SIZE, 1); const orderIds = []; let lastId = 0; for (;;) { const rows = await ctx.model.query( 'SELECT id' + ` FROM ${tableName}` + ' WHERE warehouse_id = :warehouseId' + ` AND ${candidateWhereSql}` + ' AND id > :lastId' + ' ORDER BY id ASC' + ' LIMIT :limit', { replacements: { warehouseId: Number(warehouseId), lastId, limit: normalizedBatchSize, }, type: ctx.model.QueryTypes.SELECT, } ); const pageRows = Array.isArray(rows) ? rows : []; if (pageRows.length === 0) { break; } let pageMaxId = lastId; for (const row of pageRows) { const orderId = Number(row && row.id || 0); if (Number.isFinite(orderId) && orderId > 0) { orderIds.push(orderId); pageMaxId = orderId; } } // 防死循环:本页没有解析出任何有效订单ID,或已不足一页,结束翻页 if (pageMaxId <= lastId || pageRows.length < normalizedBatchSize) { break; } lastId = pageMaxId; } return orderIds; } /** * 库内拦截确定内部实现:按订单ID列表批量确认仓库拦截(不依赖用户上下文)。 * * systemMethods 出口 confirmIntercept 与定时任务统一复用本方法,保证行为一致。 * 支持部分失败:未找到的订单与处理失败的订单记录在 failed 列表并返回失败原因, * 其余订单继续处理;每单失败不影响其他订单。 * * 每个订单的拦截处理: * 1. 更新订单:intercept_status=intercepted_at_warehouse、step=4、outbound_status=fin, * where 同时限定拦截状态白名单防并发误更新; * **不写 intercept_time**(该字段恒为「最近一次发起拦截的通知时刻」,库内确定拦截不覆盖, * 见 app/lib/intercept_time.js;库内确定拦截时刻以配送表 dispath_time 为准) * 2. 同步更新运单表:is_intercept='Y'、is_back='Y' * 3. 释放储位分配(cancelAllocateStorage 拦截模式,临时注入仓库上下文) * 4. 释放订单锁(lock_status='none') * 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM) * 全部订单处理完后,按成功订单ID汇总批量创建售后工单 + 通知快递群。 * 运单标记、储位释放、锁释放、工单创建、日志写入失败均不影响主流程。 * * @param {Object} params 参数。 * @param {number[]} params.orderIds 订单ID列表。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Object} [params.operator] 操作人信息({ id, name })。 * @return {Promise} 批量拦截结果,包含 success/failed 列表与 success_count/failed_count 计数。 */ async confirmInterceptForOrderIds(params = {}) { const { ctx } = this; const requestParams = params && typeof params === 'object' ? params : {}; const orderIds = Array.isArray(requestParams.orderIds) ? Array.from(new Set( requestParams.orderIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0) )) : []; const warehouseId = requestParams.warehouseId ?? null; const operator = requestParams.operator && typeof requestParams.operator === 'object' ? requestParams.operator : { ...AUTO_CONFIRM_OPERATOR }; if (orderIds.length === 0) { throw new Error('订单ID不能为空'); } if (warehouseId === null || warehouseId === undefined || warehouseId === '') { throw new Error('缺少仓库上下文 store_id'); } const { Op } = ctx.app.Sequelize; const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderRows = await orderModel.findAll({ where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId, }, attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ], raw: true, }); const orderMap = new Map(); for (const row of orderRows) { orderMap.set(Number(row.id), row); } const successOrders = []; const failedOrders = []; const successOrderIds = []; for (const orderId of orderIds) { const order = orderMap.get(orderId); if (!order) { failedOrders.push({ order_id: orderId, reason: '未找到对应订单' }); continue; } const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); const interceptStatus = String(order.intercept_status || '').trim(); // 未发起拦截(none/空)的订单直接跳过,不参与确认拦截处理 if (interceptStatus === '' || interceptStatus === 'none') { continue; } // 已确认拦截的订单跳过,避免重复执行副作用(释放储位/工单/日志等) if (interceptStatus === 'intercepted_at_warehouse') { failedOrders.push({ order_id: orderId, delivery_order_code: orderNo, reason: '订单已确认拦截', }); continue; } // 仅拦截发起中与历史值 intercepted 允许确认,其余状态不允许确认拦截 if (!CONFIRMABLE_INTERCEPT_STATUSES.includes(interceptStatus)) { failedOrders.push({ order_id: orderId, delivery_order_code: orderNo, reason: `订单拦截状态不允许确认拦截: ${interceptStatus}`, }); continue; } try { const now = new Date(); // 库内确定拦截不写 intercept_time(不覆盖通知拦截时刻),库内确定时刻以配送表 dispath_time 为准 const updateValues = { intercept_status: 'intercepted_at_warehouse', step: 4, outbound_status: 'fin', updated_at: now, }; const updateResult = await orderModel.update(updateValues, { where: { id: orderId, warehouse_id: warehouseId, // 数据库层再次限定拦截状态,防止查询后状态被并发修改导致误更新 intercept_status: { [Op.in]: CONFIRMABLE_INTERCEPT_STATUSES }, }, }); const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); if (affectedRows <= 0) { throw new Error('拦截状态更新失败,请稍后重试'); } // 同步更新运单表:标记拦截 + 退回(库内拦截确认,货物在库内需退回) try { await ctx.model.OrderExpress.update( { is_intercept: 'Y', is_back: 'Y' }, { where: { order_id: orderId, warehouse_id: warehouseId } } ); } catch (expressErr) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 更新运单拦截/退回标记失败, orderId=${orderId}, error=${expressErr.message}` ); } // 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用) try { await this.withPatchedCtxUser({ store_id: warehouseId }, () => ( ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({ order_ids: [ orderId ], interceptMode: true, }) )); } catch (allocErr) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 释放储位分配失败,不影响拦截, orderId=${orderId}, error=${allocErr.message}` ); } // 拦截成功后释放订单锁 try { await orderModel.update( { lock_status: 'none', updated_at: now }, { where: { id: orderId, warehouse_id: warehouseId } } ); } catch (lockErr) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 释放锁失败,不影响拦截, orderId=${orderId}, error=${lockErr.message}` ); } // 写入操作日志(失败不影响主流程) try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'order', businessId: orderId, operationCode: 'ORDER_INTERCEPT_CONFIRM', operator, extras: { warehouseId, orderId, orderNo, previousInterceptStatus: String(order.intercept_status || '').trim(), newInterceptStatus: 'intercepted_at_warehouse', }, beforeChanges: null, }); } catch (logErr) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` ); } successOrders.push({ order_id: orderId, order_no: orderNo, intercept_status: 'intercepted_at_warehouse', updated_at: now, }); successOrderIds.push(orderId); } catch (error) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 确认拦截失败, orderId=${orderId}, error=${error.message}` ); failedOrders.push({ order_id: orderId, delivery_order_code: orderNo, reason: `确认拦截失败: ${error.message}`, }); } } // 创建售后工单 + 通知快递群(成功订单 ID 汇总统一调用,失败不影响主流程) if (successOrderIds.length > 0) { try { await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({ orderIds: successOrderIds, warehouseId, creatorLabel: operator.name || '系统', }); } catch (workOrderErr) { ctx.logger.warn( `[interceptAutoConfirm.confirmInterceptForOrderIds] 创建工单/通知失败, orderIds=${successOrderIds.join(',')}, error=${workOrderErr.message}` ); } } return { success: successOrders, failed: failedOrders, success_count: successOrders.length, failed_count: failedOrders.length, }; } /** * 自动库内拦截确定主入口:枚举仓库 → 分页扫描候选订单 → 分批确认拦截。 * * 单个仓库扫描/确认失败仅记录日志与 detail.error,不影响其他仓库; * 全部动作失败不阻断下轮执行(异常上抛由定时任务捕获记录)。 * * @param {Object} [options={}] 执行选项。 * @param {number} [options.scanBatchSize=SCAN_BATCH_SIZE] 单批扫描数量。 * @param {number} [options.confirmBatchSize=CONFIRM_BATCH_SIZE] 单批确认数量。 * @return {Promise} 执行结果汇总,包含 warehouse_count/candidate_count/confirmed_count/ * failed_count/warehouse_ids/duration_ms/details。 */ async runAutoConfirm(options = {}) { const { ctx } = this; const startedAt = Date.now(); const requestOptions = options && typeof options === 'object' ? options : {}; const scanBatchSize = Math.max(Number.parseInt(requestOptions.scanBatchSize, 10) || SCAN_BATCH_SIZE, 1); const confirmBatchSize = Math.max(Number.parseInt(requestOptions.confirmBatchSize, 10) || CONFIRM_BATCH_SIZE, 1); const warehouseIds = await this.listCurrentWarehouseIds(); const details = []; let candidateCount = 0; let confirmedCount = 0; let failedCount = 0; for (const warehouseId of warehouseIds) { const detail = { warehouse_id: warehouseId, candidate_count: 0, confirmed_count: 0, failed_count: 0, error: null, }; try { const candidateIds = await this.scanCandidateOrderIds(warehouseId, scanBatchSize); detail.candidate_count = candidateIds.length; for (let offset = 0; offset < candidateIds.length; offset += confirmBatchSize) { const batchIds = candidateIds.slice(offset, offset + confirmBatchSize); const batchResult = await this.confirmInterceptForOrderIds({ orderIds: batchIds, warehouseId, operator: AUTO_CONFIRM_OPERATOR, }); detail.confirmed_count += batchResult.success_count; detail.failed_count += batchResult.failed_count; } } catch (error) { detail.error = String(error && error.message ? error.message : error); ctx.logger.warn( `[interceptAutoConfirm.runAutoConfirm] 仓库 ${warehouseId} 处理失败,跳过: ${detail.error}` ); } candidateCount += detail.candidate_count; confirmedCount += detail.confirmed_count; failedCount += detail.failed_count; details.push(detail); } return { warehouse_count: warehouseIds.length, candidate_count: candidateCount, confirmed_count: confirmedCount, failed_count: failedCount, warehouse_ids: warehouseIds, duration_ms: Date.now() - startedAt, details, }; } } module.exports = InterceptAutoConfirmService;