'use strict'; const { Op } = require('sequelize'); const OrderBaseService = require('./base'); const runWaveStrategyQuickScanRunner = require('../../../lib/wave_strategy_quick_scan_runner'); const DEFAULT_PAGE = 1; const DEFAULT_PAGE_SIZE = 20; const MAX_PAGE_SIZE = 200; const BATCH_LIST_MAX_PAGE_SIZE = 500; const DEFAULT_MAX_WAVE_QUANTITY = 500; const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; const BATCH_CANCEL_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX = 'wave:batch-remove-exception-orders:'; const BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-express:'; const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:'; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 5; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:'; const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2; const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:'; const WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS = 60 * 30; const CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX = 'wave:confirm-print:unclaimed:version:'; const CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS = 60 * 1000; const CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS = 1000; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ]; const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map(); const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ id: 'id', delivery_no: 'delivery_order_code', deliveryNo: 'delivery_order_code', tracking_no: 'express_numbers', trackingNo: 'express_numbers', items_count: 'items_count', items_count_min: 'items_count', items_count_max: 'items_count', items_total: 'items_total', items_total_min: 'items_total', items_total_max: 'items_total', sys_logistics_name: 'logistics_name', store_name: 'shop_nick', owner_name: 'shop_nick', province: 'province', sys_platform_name: 'sys_platform_name', }); const WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS = Object.freeze({ locked: '已锁定', intercepted: '已拦截', printed: '已打印', no_match: '未匹配策略', }); const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ storage: Object.freeze({ fieldName: 'storage_assignment_status', enumMap: Object.freeze({ 未分配: 'none', 部分分配: 'partial', 已分配: 'finished', }), caseInsensitive: false, statsColumnPrefix: 'storage', withErrorStatus: true, }), express: Object.freeze({ fieldName: 'express_assignment_status', enumMap: Object.freeze({ unassigned: 'none', partially_assigned: 'partial', assigned: 'finished', }), caseInsensitive: true, statsColumnPrefix: 'post', withErrorStatus: true, }), print: Object.freeze({ fieldName: 'print_assignment_status', enumMap: Object.freeze({ unprinted: 'none', partially_printed: 'partial', printed: 'finished', }), caseInsensitive: true, statsColumnPrefix: 'print', withErrorStatus: false, }), confirm_print: Object.freeze({ fieldName: 'confirm_print_assignment_status', enumMap: Object.freeze({ unconfirmed: 'none', partially_confirmed: 'partial', confirmed: 'finished', }), caseInsensitive: true, statsColumnPrefix: 'confirm_print', withErrorStatus: false, }), review: Object.freeze({ fieldName: 'review_assignment_status', enumMap: Object.freeze({ unreviewed: 'none', partially_reviewed: 'partial', reviewed: 'finished', }), caseInsensitive: true, statsColumnPrefix: 'review', withErrorStatus: true, }), sync: Object.freeze({ fieldName: 'sync_assignment_status', enumMap: Object.freeze({ unsynced: 'none', partially_synced: 'partial', synced: 'finished', }), caseInsensitive: true, statsColumnPrefix: 'sync', withErrorStatus: true, }), }); class WaveService extends OrderBaseService { /** * 初始化波次方法权限配置。 * * @param {Egg.Context} ctx 请求上下文。 */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount'; const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintScan,confirmPrintUnclaimedWaveCount'; const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** * 构建批次分配快递号链路追踪ID。 * * 优先使用入参中的 trace_id/traceId,其次尝试读取上下文中的 trace 标识, * 最后兜底生成带时间戳的随机追踪ID。 * * @param {Object} [data={}] 入参对象。 * @param {string} [fallback=''] 兜底业务标识(如 taskId)。 * @return {string} 追踪ID。 */ buildBatchAllocateExpressTraceId(data = {}, fallback = '') { const normalizedData = this.isPlainObject(data) ? data : {}; const ctxTraceId = this.ctx && this.ctx.traceId !== undefined ? this.ctx.traceId : this.ctx && this.ctx.requestId !== undefined ? this.ctx.requestId : this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined ? this.ctx.state.traceId : ''; const normalizedTraceId = String( normalizedData.trace_id || normalizedData.traceId || ctxTraceId || fallback || '' ).trim(); if (normalizedTraceId) { return normalizedTraceId; } return `wave_allocate_express_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; } /** * 构建订单操作日志批量写入数据。 * * @param {Array} logItems 日志项。 * @param {number|string} warehouseId 仓库ID。 * @return {Array} 可直接用于 bulkCreate 的日志行。 */ buildOrderOperationLogRows(logItems = [], warehouseId = 0) { if (!Array.isArray(logItems) || logItems.length === 0) { return []; } const normalizedWarehouseId = Number(this.getOrderLogWarehouseId(warehouseId) || 0); const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user) ? this.ctx.state.user : null; const ctxUser = this.isPlainObject(this.ctx && this.ctx.user) ? this.ctx.user : null; const paramsObject = this.isPlainObject(this.params) ? this.params : {}; const paramsOperator = this.isPlainObject(paramsObject.__operator) ? paramsObject.__operator : (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null); const operatorSource = stateUser || ctxUser || paramsOperator || {}; const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; const rawOperatorName = operatorSource.employees_name ?? operatorSource.operator_name ?? operatorSource.real_name ?? operatorSource.name; const operatorId = rawOperatorId === undefined || rawOperatorId === null ? null : String(rawOperatorId).trim() || null; const operatorName = rawOperatorName === undefined || rawOperatorName === null ? 'system' : String(rawOperatorName).trim() || 'system'; const platformCode = String(operatorSource.platform_code || 'SYSTEM').trim() || 'SYSTEM'; return logItems .map(item => { const orderId = Number(item && item.orderId || 0); const operationCode = String(item && item.operationCode || '').trim() || 'ORDER_WAVE_UPDATE'; const message = String(item && item.message || '').trim(); if (!Number.isInteger(orderId) || orderId <= 0 || !message) { return null; } return { business_type: 'order', business_id: `${orderId}`, operation_code: operationCode, operator_id: operatorId, operator_name: operatorName, external_log_type: 'NONE', warehouse_id: Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : null, platform_code: platformCode, message, }; }) .filter(Boolean); } /** * 批量写入订单操作日志。 * * 该方法为业务降级路径,写入失败仅告警,不影响主流程。 * * @param {Array} logItems 日志项。 * @param {Object} options 写入选项。 * @param {number|string} options.warehouseId 仓库ID。 * @param {string} [options.scene='wave'] 场景标识,用于日志追踪。 * @return {Promise} 实际写入条数。 */ async batchCreateOrderOperationLogs(logItems = [], options = {}) { const rows = this.buildOrderOperationLogRows(logItems, options && options.warehouseId); const loggerWarn = this.ctx.logger && typeof this.ctx.logger.warn === 'function' ? this.ctx.logger.warn.bind(this.ctx.logger) : null; if (rows.length === 0) { return 0; } const operationLogModel = this.ctx.model && this.ctx.model.OperationLog; if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') { if (loggerWarn) { loggerWarn('[wave.batchCreateOrderOperationLogs] OperationLog.bulkCreate 不可用,跳过写入', { scene: String(options && options.scene || 'wave'), rows: rows.length, }); } return 0; } try { await operationLogModel.bulkCreate(rows); return rows.length; } catch (error) { if (loggerWarn) { loggerWarn('[wave.batchCreateOrderOperationLogs] 批量写订单操作日志失败,不影响主流程', { scene: String(options && options.scene || 'wave'), rows: rows.length, error: error && error.message ? error.message : `${error}`, }); } return 0; } } /** * 构建稳定机器结构标识(可作为抓取接口入参)。 * * @param {Object} params 结构参数。 * @param {string} params.item_part_type 商品结构来源字段类型。 * @param {string} params.item_part 商品结构来源值。 * @param {boolean} params.distinguish_express 是否区分快递。 * @param {string} params.logistics_name 快递名称。 * @param {string} params.item_snapshot_key 机器明细快照。 * @return {string} 稳定机器结构标识。 */ buildMachineStructureToken(params = {}) { const itemPartType = String(params.item_part_type || 'items_hash').trim() || 'items_hash'; const itemPart = encodeURIComponent(String(params.item_part || '').trim()); const distinguishExpress = params.distinguish_express ? '1' : '0'; const logisticsName = encodeURIComponent(String(params.logistics_name || '').trim()); const itemSnapshotKey = encodeURIComponent(String(params.item_snapshot_key || '').trim()); return `v1|${itemPartType}|${itemPart}|${distinguishExpress}|${logisticsName}|${itemSnapshotKey}`; } /** * 解析机器结构标识。 * * @param {string} token 机器结构标识。 * @return {{ item_part_type: string, item_part: string, distinguish_express: boolean, logistics_name: string, item_snapshot_key: string }} 解析结果。 */ parseMachineStructureToken(token) { const normalizedToken = String(token || '').trim(); const parts = normalizedToken.split('|'); if (parts.length < 6 || parts[0] !== 'v1') { throw new Error('item_detail_machine 格式不合法'); } const itemPartType = String(parts[1] || '').trim(); if (![ 'items_hash', 'items' ].includes(itemPartType)) { throw new Error('item_detail_machine item_part_type 不支持'); } const itemPart = decodeURIComponent(String(parts[2] || '').trim()); if (!itemPart) { throw new Error('item_detail_machine item_part 不能为空'); } const distinguishExpress = String(parts[3] || '') === '1'; const logisticsName = decodeURIComponent(String(parts[4] || '').trim()); const itemSnapshotKey = decodeURIComponent(String(parts[5] || '').trim()); return { item_part_type: itemPartType, item_part: itemPart, distinguish_express: distinguishExpress, logistics_name: logisticsName, item_snapshot_key: itemSnapshotKey, }; } /** * 获取订单可分组的商品结构值(优先 items_hash)。 * * @param {Object} order 订单主表记录。 * @return {{ item_part_type: string, item_part: string }} 分组结构值。 */ getOrderItemPart(order = {}) { const itemsHash = String(order.items_hash || '').trim(); if (itemsHash) { return { item_part_type: 'items_hash', item_part: itemsHash, }; } return { item_part_type: 'items', item_part: String(order.items || '').trim(), }; } /** * 读取默认抓取数量(缓存优先,缓存 miss 再读库)。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 默认抓取数量。 */ async getDefaultWaveQuantity(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return DEFAULT_MAX_WAVE_QUANTITY; } try { const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); const maxWaveQuantity = Number(this.getWarehouseSubjectConfigValue(subjectConfig, 'max_wave_quantity')); if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) { return DEFAULT_MAX_WAVE_QUANTITY; } return maxWaveQuantity; } catch (error) { this.ctx.logger.warn('[wave.getDefaultWaveQuantity] 获取仓库默认波次数量失败: %s', error.message); return DEFAULT_MAX_WAVE_QUANTITY; } } /** * 读取最小团购抓取数量(缓存优先,缓存 miss 再读库)。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 最小团购抓取数量。 */ async getMinGroupOrderFetchQuantity(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; } try { const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); const minGroupOrderFetchQuantity = Number( this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') ); if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; } return minGroupOrderFetchQuantity; } catch (error) { this.ctx.logger.warn('[wave.getMinGroupOrderFetchQuantity] 获取仓库最小团购抓取数量失败: %s', error.message); return DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; } } /** * 读取团购波次编号前缀(缓存优先,缓存 miss 再读库)。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 团购波次编号前缀。 */ async getGroupWavePrefix(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return 'B'; } try { const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); const groupWavePrefix = String( this.getWarehouseSubjectConfigValue(subjectConfig, 'group_wave_prefix') || '' ).trim(); if (!groupWavePrefix) { return 'B'; } return groupWavePrefix.slice(0, 5); } catch (error) { this.ctx.logger.warn('[wave.getGroupWavePrefix] 获取仓库团购波次前缀失败: %s', error.message); return 'B'; } } /** * 读取散单波次编号前缀(缓存优先,缓存 miss 再读库)。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 散单波次编号前缀。 */ async getSingleFetchByIdsWavePrefix(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return 'A'; } try { const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); const singleFetchByIdsWavePrefix = String( this.getWarehouseSubjectConfigValue(subjectConfig, 'delete_order_wave_prefix') || '' ).trim(); if (!singleFetchByIdsWavePrefix) { return 'A'; } return singleFetchByIdsWavePrefix.slice(0, 5); } catch (error) { this.ctx.logger.warn('[wave.getSingleFetchByIdsWavePrefix] 获取仓库散单波次前缀失败: %s', error.message); return 'A'; } } /** * 统一读取仓库主体配置(缓存优先,缓存 miss 回源数据库)。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 仓库主体配置对象。 */ async getWarehouseSubjectConfig(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return {}; } const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { return {}; } const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId); return this.isPlainObject(subjectConfig) ? subjectConfig : {}; } /** * 从仓库主体配置中读取字段值,优先 subject_config 内嵌配置。 * * @param {Object} subjectConfig 仓库主体配置。 * @param {string} key 字段名。 * @return {*} 字段值。 */ getWarehouseSubjectConfigValue(subjectConfig = {}, key = '') { const normalizedKey = String(key || '').trim(); if (!normalizedKey) { return undefined; } const normalizedSubjectConfig = this.isPlainObject(subjectConfig) ? subjectConfig : {}; const nestedSubjectConfig = this.isPlainObject(normalizedSubjectConfig.subject_config) ? normalizedSubjectConfig.subject_config : {}; if (nestedSubjectConfig[normalizedKey] !== undefined) { return nestedSubjectConfig[normalizedKey]; } return normalizedSubjectConfig[normalizedKey]; } /** * 解析抓取结构请求参数。 * * @param {Object} data 请求参数。 * @param {number} defaultQuantity 默认抓取数量。 * @return {Array} 结构化请求。 */ normalizeFetchStructureRequests(data = {}, defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY) { const requestData = this.isPlainObject(data) ? data : {}; const rawStructureList = requestData.structure_list; if (!Array.isArray(rawStructureList) || rawStructureList.length === 0) { throw new Error('structure_list 必须是非空数组'); } return rawStructureList.map((item, index) => { if (!this.isPlainObject(item)) { throw new Error(`structure_list[${index}] 必须是对象`); } const itemDetailMachine = String(item.item_detail_machine || '').trim(); if (!itemDetailMachine) { throw new Error(`structure_list[${index}].item_detail_machine 不能为空`); } const parsedToken = this.parseMachineStructureToken(itemDetailMachine); const quantity = item.quantity === undefined || item.quantity === null || item.quantity === '' ? defaultQuantity : this.normalizePositiveInteger(item.quantity, `structure_list[${index}].quantity`, defaultQuantity); if (!Number.isInteger(quantity) || quantity <= 0) { throw new Error(`structure_list[${index}].quantity 必须大于 0`); } return { index, item_detail_machine: itemDetailMachine, quantity, ...parsedToken, }; }); } /** * 生成可排序且足够唯一的 wave_id。 * * @param {number} suffix 同批次偏移量。 * @return {number} 波次ID。 */ generateWaveId(suffix = 0) { const base = Date.now() * 1000; const randomPart = Math.floor(Math.random() * 900) + 100; return base + randomPart + Number(suffix || 0); } /** * 获取当前日期片段(YYYYMMDD)。 * * @return {string} 当前日期片段。 */ getCurrentDatePart() { const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); return `${year}${month}${day}`; } /** * 获取当天前缀下的下一个波次序号(原子取号)。 * * 基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务): * INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE * current_seq = GREATEST(current_seq, :seed) + 1 * 其中 :seed 为当日该前缀主表已有最大序号,保证与历史编号对齐; * upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq, * 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。 * 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。 * * @param {string} prefix 波次编号前缀。 * @param {string} datePart 日期片段(YYYYMMDD)。 * @param {Object} transaction Sequelize 事务。 * @return {Promise} 下一个序号(最小为 1)。 */ async getNextWaveNoSequence(prefix, datePart, transaction) { const normalizedPrefix = String(prefix || '').trim() || 'B'; const normalizedDatePart = String(datePart || '').trim(); const pattern = `${normalizedPrefix}${normalizedDatePart}%`; const prefixDatePartLength = normalizedPrefix.length + normalizedDatePart.length; const bizType = `wave_no_${normalizedPrefix.slice(0, 20)}`; // 历史对齐种子:当日该前缀主表已有最大序号(无则为 0) const seedRows = await this.ctx.model.query( `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) AS max_seq FROM wms_wave_batch WHERE wave_no LIKE :pattern`, { replacements: { pattern, startPos: prefixDatePartLength + 1, }, type: this.ctx.model.QueryTypes.SELECT, transaction, } ); const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq || 0); // 原子取号:全局维度(warehouse_id=0)按「前缀+日期」递增,唯一键串行化并发事务 await this.ctx.model.query( `INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at) VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW()) ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`, { replacements: { warehouseId: 0, bizType, datePart: normalizedDatePart, seed, }, transaction, } ); // 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化), // FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响 const seqRows = await this.ctx.model.query( `SELECT current_seq FROM wms_number_sequence WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart FOR UPDATE`, { replacements: { warehouseId: 0, bizType, datePart: normalizedDatePart, }, type: this.ctx.model.QueryTypes.SELECT, transaction, } ); const sequence = Number(seqRows && seqRows[0] && seqRows[0].current_seq || 0); if (!Number.isInteger(sequence) || sequence <= 0) { return 1; } return sequence; } /** * 构建波次编号。 * * @param {string} [prefix='B'] 波次编号前缀。 * @param {string} [datePart=''] 日期片段(YYYYMMDD)。 * @param {number|string} [sequence=1] 当天序号。 * @return {string} 波次编号。 */ buildWaveNo(prefix = 'B', datePart = '', sequence = 1) { const normalizedPrefix = String(prefix || '').trim(); const normalizedDatePart = String(datePart || '').trim(); const normalizedSequence = Number(sequence || 0); const safeSequence = Number.isInteger(normalizedSequence) && normalizedSequence > 0 ? normalizedSequence : 1; return `${normalizedPrefix}${normalizedDatePart}${String(safeSequence).padStart(5, '0')}`; } /** * 获取波次创建人。 * * 优先级:employees_name > real_name > name > id(字符串) > system。 * * @return {string} 创建人。 */ getWaveCreator() { const user = this.isPlainObject(this.ctx.user) ? this.ctx.user : {}; const creator = String(user.employees_name || user.real_name || user.name || '').trim(); if (creator) { return creator; } const userId = user.id; if (userId !== undefined && userId !== null && userId !== '') { return `${userId}`; } return 'system'; } /** * 从 SQL 执行结果中提取 insertId。 * * @param {*} queryResult Sequelize query 返回值。 * @return {number} 自增主键ID,提取失败返回 0。 */ extractInsertId(queryResult) { if (Array.isArray(queryResult)) { const [ first, second ] = queryResult; const firstInsertId = Number(first && first.insertId || 0); if (Number.isInteger(firstInsertId) && firstInsertId > 0) { return firstInsertId; } const secondInsertId = Number(second && second.insertId || 0); if (Number.isInteger(secondInsertId) && secondInsertId > 0) { return secondInsertId; } } const directInsertId = Number(queryResult && queryResult.insertId || 0); if (Number.isInteger(directInsertId) && directInsertId > 0) { return directInsertId; } return 0; } /** * 从 LAST_INSERT_ID 查询结果中提取 insertId。 * * @param {*} queryResult Sequelize query 返回值。 * @return {number} 自增主键ID,提取失败返回 0。 */ extractLastInsertId(queryResult) { const directInsertId = this.extractInsertId(queryResult); if (Number.isInteger(directInsertId) && directInsertId > 0) { return directInsertId; } if (!Array.isArray(queryResult)) { return 0; } const [ first ] = queryResult; if (Array.isArray(first) && first.length > 0) { for (const row of first) { const rowInsertId = Number( row && (row.insertId || row.insert_id || row.LAST_INSERT_ID || row.last_insert_id) || 0 ); if (Number.isInteger(rowInsertId) && rowInsertId > 0) { return rowInsertId; } } } return 0; } /** * 判断数据库错误是否为唯一键冲突(重复键 ER_DUP_ENTRY)。 * * @param {*} error 数据库异常对象。 * @return {boolean} 是否唯一键冲突。 */ isDuplicateEntryError(error) { const errno = Number( error && (error.original && error.original.errno || error.parent && error.parent.errno || error.errno) || 0 ); const code = String( error && (error.original && error.original.code || error.parent && error.parent.code || error.code) || '' ); return errno === 1062 || code === 'ER_DUP_ENTRY'; } /** * 根据波次元信息推导订单 wave_scope(波次范围)。 * * 口径: * - wave_type=1 且 source=0 → 1(大团购); * - wave_type=1 且 source=2 → 3(小团购); * - wave_type=2 且 pickMode=2 → 4(单品单件); * - 其余(散单等)→ 2(散单)。 * 未分配波次(wave_id=0)由调用方直接置 0。 * * @param {number|string} waveType 波次类型(1-团购 2-散单)。 * @param {number|string} source 波次来源(0-普通 1-管理后台策略 2-PDA策略)。 * @param {number|string} [pickMode] 拣货模式(1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购)。 * @return {number} wave_scope:1-大团购 2-散单 3-小团购 4-单品单件。 */ resolveWaveScopeByWaveMeta(waveType, source, pickMode) { const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; const normalizedSource = [ 0, 1, 2 ].includes(Number(source)) ? Number(source) : 0; const normalizedPickMode = [ 1, 2, 3, 4, 5 ].includes(Number(pickMode)) ? Number(pickMode) : 0; if (normalizedWaveType === 1 && normalizedSource === 0) { return 1; } if (normalizedWaveType === 1 && normalizedSource === 2) { return 3; } if (normalizedWaveType === 2 && normalizedPickMode === 2) { return 4; } return 2; } /** * 新增一条“已就绪”波次批次记录,并返回自增 wave_id。 * * @param {Object} params 入参。 * @param {number|string} params.warehouseId 仓库ID。 * @param {number|string} params.totalOrders 订单总数。 * @param {string} params.itemDetailMachine 机器结构标识。 * @param {string} params.itemPartType 商品结构来源字段类型。 * @param {string} params.itemPart 商品结构来源值。 * @param {number|boolean|string} params.distinguishExpress 是否区分快递(归一化为0/1)。 * @param {string} params.logisticsName 快递名称。 * @param {string} params.itemSnapshotKey 机器明细快照。 * @param {string} [params.wavePrefix] 波次编号前缀。 * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 * @param {number|string} [params.waveType=1] 波次类型,仅允许 1(团购)或 2(散单),非法值回退 1。 * @param {number|string} [params.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @param {Object} params.transaction Sequelize 事务。 * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 */ async createWaveBatchReady({ warehouseId, totalOrders, itemDetailMachine, itemPartType, itemPart, distinguishExpress, logisticsName, itemSnapshotKey, wavePrefix, waveNo, waveType, source, transaction, } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedTotalOrders = Number(totalOrders || 0); const normalizedItemDetailMachine = String(itemDetailMachine || '').trim(); const normalizedItemPartType = String(itemPartType || '').trim(); const normalizedItemPart = String(itemPart || '').trim(); const normalizedDistinguishExpress = distinguishExpress === true || Number(distinguishExpress) === 1 ? 1 : 0; const normalizedLogisticsName = String(logisticsName || '').trim(); const normalizedItemSnapshotKey = String(itemSnapshotKey || '').trim(); const normalizedWavePrefix = String(wavePrefix || '').trim() || 'B'; const normalizedWaveNoInput = String(waveNo || '').trim(); const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; const normalizedSourceInput = Number(source); const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; const retryOnDuplicate = !normalizedWaveNoInput; const maxWaveNoAttempts = retryOnDuplicate ? 3 : 1; let normalizedWaveNo = normalizedWaveNoInput; const creator = this.getWaveCreator(); const sql = ` INSERT INTO wms_wave_batch ( wave_no, wave_type, wave_status, total_orders, processed_orders, item_detail_machine, item_part_type, item_part, distinguish_express, logistics_name, item_snapshot_key, warehouse_id, creator, source, create_time, update_time ) VALUES ( :waveNo, :waveType, 1, :totalOrders, 0, :itemDetailMachine, :itemPartType, :itemPart, :distinguishExpress, :logisticsName, :itemSnapshotKey, :warehouseId, :creator, :source, NOW(), NOW() ) `; // 撞号重试:唯一索引兜底下,并发撞号时自动重新取号(最多 3 次) let createResult = null; for (let attempt = 1; attempt <= maxWaveNoAttempts; attempt += 1) { if (!normalizedWaveNo) { const datePart = this.getCurrentDatePart(); const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); } try { createResult = await this.ctx.model.query(sql, { replacements: { waveNo: normalizedWaveNo, waveType: normalizedWaveType, totalOrders: normalizedTotalOrders, itemDetailMachine: normalizedItemDetailMachine, itemPartType: normalizedItemPartType, itemPart: normalizedItemPart, distinguishExpress: normalizedDistinguishExpress, logisticsName: normalizedLogisticsName, itemSnapshotKey: normalizedItemSnapshotKey, warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, creator, source: normalizedSource, }, transaction, }); break; } catch (error) { const isDuplicateWaveNo = this.isDuplicateEntryError(error); if (!retryOnDuplicate || !isDuplicateWaveNo || attempt >= maxWaveNoAttempts) { throw error; } this.ctx.logger.warn( '[wave.createWaveBatchReady] 波次编号 %s 已存在(撞号),自动重新取号重试 %d/%d', normalizedWaveNo, attempt, maxWaveNoAttempts ); normalizedWaveNo = ''; } } let insertedWaveId = this.extractInsertId(createResult); if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { transaction, }); insertedWaveId = this.extractLastInsertId(fallbackResult); } if (!Number.isInteger(insertedWaveId) || insertedWaveId <= 0) { throw new Error('创建波次失败,未获取到自增 wave_id'); } return { waveId: insertedWaveId, waveNo: normalizedWaveNo, }; } /** * 构建抓取候选订单筛选条件。 * * @param {Object} structure 结构化请求。 * @return {Object} Sequelize where 条件。 */ buildFetchWhere(structure = {}) { const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, intercept_status: 'none', lock_status: 'none', wave_id: 0, }; const itemPartType = String(structure.item_part_type || '').trim(); const itemPart = String(structure.item_part || '').trim(); if (itemPartType === 'items_hash') { where.items_hash = itemPart; } else { where.items = itemPart; } if (structure.distinguish_express) { const expressCode = String(structure.logistics_name || '').trim(); if (expressCode) { where.sys_logistics_code = expressCode; } } return where; } /** * 按单个结构抓取订单并写入同一波次。 * * @param {Object} model 订单主表模型。 * @param {Object} structure 结构化请求。 * @param {number|string} warehouseId 仓库ID。 * @param {string} [wavePrefix='B'] 波次编号前缀。 * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 * @param {Object} [options={}] 额外抓取选项。 * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 单结构抓取结果。 */ async fetchSingleStructure( model, structure = {}, warehouseId = 0, wavePrefix = 'B', minGroupOrderFetchQuantity = DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY, options = {} ) { const { ctx } = this; const where = this.buildFetchWhere(structure); const requestedQuantity = Number(structure.quantity || 0); const normalizedOptions = this.isPlainObject(options) ? options : {}; const normalizedMaxFetchQuantity = Number.isInteger(Number(normalizedOptions.maxFetchQuantity)) && Number(normalizedOptions.maxFetchQuantity) > 0 ? Number(normalizedOptions.maxFetchQuantity) : 0; const normalizedSourceInput = Number(normalizedOptions.source); const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; const logOperator = this.getOrderLogOperator() || {}; const claimOperator = String(logOperator.name || '').trim() || null; const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null; const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) && Number(minGroupOrderFetchQuantity) > 0 ? Number(minGroupOrderFetchQuantity) : DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY; const allWaveIds = []; const allOrderIds = []; const fetchedOrderLogItems = []; let totalFetchedQuantity = 0; let remainingFetchQuantity = normalizedMaxFetchQuantity; let stopReason = ''; const transaction = await ctx.model.transaction(); try { for (;;) { let fetchLimit = requestedQuantity; if (normalizedMaxFetchQuantity > 0) { if (remainingFetchQuantity <= 0) { stopReason = '达到最大抓取上限'; break; } fetchLimit = Math.min(fetchLimit, remainingFetchQuantity); } const rows = await model.findAll({ where, attributes: [ 'id' ], raw: true, transaction, lock: transaction.LOCK.UPDATE, order: [[ 'id', 'DESC' ]], limit: fetchLimit, }); const candidateOrderIds = rows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0); if (candidateOrderIds.length === 0) { if (totalFetchedQuantity === 0) { stopReason = '无可抓取订单'; } break; } if (candidateOrderIds.length < normalizedMinGroupOrderFetchQuantity) { stopReason = '剩余订单低于最小团购抓取数量'; break; } const { waveId, waveNo } = await this.createWaveBatchReady({ warehouseId, totalOrders: candidateOrderIds.length, itemDetailMachine: structure.item_detail_machine, itemPartType: structure.item_part_type, itemPart: structure.item_part, distinguishExpress: structure.distinguish_express, logisticsName: structure.logistics_name, itemSnapshotKey: structure.item_snapshot_key, wavePrefix, source: normalizedSource, transaction, }); await model.update({ wave_id: waveId, wave_no: waveNo, wave_scope: this.resolveWaveScopeByWaveMeta(1, normalizedSource), grab_operator_id: grabOperatorId, grab_operator: claimOperator, }, { where: { id: { [Op.in]: candidateOrderIds }, wave_id: 0, }, transaction, }); // 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯 if ([ 1, 2 ].includes(normalizedSource) && claimOperator) { await ctx.model.WaveBatch.update( { claim_operator: claimOperator, claim_time: new Date(), }, { where: { wave_id: waveId, warehouse_id: warehouseId, }, transaction, } ); } const grabbedRows = await model.findAll({ where: { id: { [Op.in]: candidateOrderIds }, wave_id: waveId, }, attributes: [ 'id' ], raw: true, transaction, }); const grabbedOrderIds = grabbedRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0) .sort((a, b) => a - b); const fetchedQuantity = grabbedOrderIds.length; if (fetchedQuantity <= 0) { await this.ctx.model.query(` DELETE FROM wms_wave_batch WHERE wave_id = :waveId `, { replacements: { waveId }, transaction, }); if (totalFetchedQuantity === 0) { stopReason = '无可抓取订单'; } break; } if (fetchedQuantity !== candidateOrderIds.length) { await this.ctx.model.query(` UPDATE wms_wave_batch SET total_orders = :totalOrders, update_time = NOW() WHERE wave_id = :waveId `, { replacements: { waveId, totalOrders: fetchedQuantity, }, transaction, }); } allWaveIds.push(waveId); allOrderIds.push(...grabbedOrderIds); fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ orderId, operationCode: 'ORDER_WAVE_ASSIGN', message: `订单被分配到波次 ${waveNo}`, }))); totalFetchedQuantity += fetchedQuantity; if (normalizedMaxFetchQuantity > 0) { remainingFetchQuantity -= fetchedQuantity; if (remainingFetchQuantity <= 0) { stopReason = '达到最大抓取上限'; break; } } } if (allWaveIds.length > 0 && allOrderIds.length > 0) { await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: allWaveIds, orderModel: model, transaction, }); } await transaction.commit(); await this.batchCreateOrderOperationLogs(fetchedOrderLogItems, { warehouseId, scene: 'fetchSingleStructure', }); // 抓取波次(source=1/2)会冗余写入领料人/领料时间,递增统计版本号驱动长轮询 await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, mergedOrderIds, { triggerScan: false, source: 'fetchSingleStructure', }); let reason = stopReason; if (!reason && totalFetchedQuantity > 0 && totalFetchedQuantity < requestedQuantity) { reason = '可抓取订单不足'; } return { item_detail_machine: structure.item_detail_machine, request_quantity: requestedQuantity, fetched_quantity: totalFetchedQuantity, ...(normalizedMaxFetchQuantity > 0 ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), ...(normalizedMaxFetchQuantity > 0 ? { limit_reached: totalFetchedQuantity >= normalizedMaxFetchQuantity } : {}), wave_id: allWaveIds.length > 0 ? allWaveIds[0] : 0, wave_ids: allWaveIds, order_ids: mergedOrderIds, ...(reason ? { reason } : {}), }; } catch (error) { await transaction.rollback(); throw error; } } normalizeBoolean(value, defaultValue = false) { if (value === undefined || value === null || value === '') { return defaultValue; } if (typeof value === 'boolean') { return value; } if (typeof value === 'number') { return value === 1; } const normalized = String(value).trim().toLowerCase(); if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) { return true; } if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) { return false; } return defaultValue; } normalizePositiveInteger(value, fieldName, defaultValue = 0) { if (value === undefined || value === null || value === '') { return defaultValue; } const num = Number(value); if (!Number.isInteger(num) || num < 0) { throw new Error(`${fieldName} 参数不合法`); } return num; } /** * 解析必填的正整数参数。 * * @param {*} value 原始参数值。 * @param {string} fieldName 字段名称。 * @return {number} 归一化后的正整数。 */ normalizeRequiredPositiveInteger(value, fieldName) { if (value === undefined || value === null || value === '') { throw new Error(`${fieldName} 参数不能为空`); } const normalizedValue = Number(value); if (!Number.isInteger(normalizedValue) || normalizedValue <= 0) { throw new Error(`${fieldName} 参数必须为正整数`); } return normalizedValue; } /** * 归一化 ids 入参为去重后的正整数数组。 * * 支持数组、逗号分隔字符串、单个 number/string。 * * @param {Array|number|string} value 原始 ids 入参。 * @return {Array} 归一化后的 ids 数组。 */ normalizeIdsInput(value) { let sourceList = []; if (Array.isArray(value)) { sourceList = value; } else if (typeof value === 'string') { sourceList = value.split(','); } else if (typeof value === 'number') { sourceList = [ value ]; } else { sourceList = []; } const normalizedIds = sourceList .map(item => String(item === undefined || item === null ? '' : item).trim()) .filter(item => item !== '') .map(item => Number(item)) .filter(item => Number.isInteger(item) && item > 0); return [ ...new Set(normalizedIds) ]; } /** * 规范化分页参数。 * * @param {Object} data 请求参数;兼容直接传入 pagination 对象。 * @param {Object} data.pagination 分页参数对象。 * @param {number|string} data.pagination.page 页码。 * @param {number|string} data.pagination.pageSize 每页数量(驼峰写法,可用)。 * @param {number|string} data.pagination.page_size 每页数量(下划线写法,可用)。 * @param {number|string} data.pagination.limit 每页数量(limit 写法,可用)。 * @param {number|string} data.pagination.size 每页数量(size 写法,可用)。 * @param {number|string} data.page 页码(直接分页对象写法)。 * @param {number|string} data.pageSize 每页数量(直接分页对象驼峰写法)。 * @param {number|string} data.page_size 每页数量(直接分页对象下划线写法)。 * @param {number|string} data.limit 每页数量(直接分页对象 limit 写法)。 * @param {number|string} data.size 每页数量(直接分页对象 size 写法)。 * @param {Object} options 规范化选项。 * @param {number|string} options.maxPageSize 每页数量上限。 * @return {{ page: number, pageSize: number }} 规范化后的分页信息。 */ normalizePagination(data = {}, options = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const pagination = this.isPlainObject(normalizedData.pagination) ? normalizedData.pagination : normalizedData; const pageSource = pagination.page; const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.limit ?? pagination.size; const maxPageSizeSource = Number(options.maxPageSize || MAX_PAGE_SIZE); const maxPageSize = Number.isInteger(maxPageSizeSource) && maxPageSizeSource > 0 ? maxPageSizeSource : MAX_PAGE_SIZE; const page = Number(pageSource || DEFAULT_PAGE); const pageSize = Number(pageSizeSource || DEFAULT_PAGE_SIZE); const normalizedPage = Number.isInteger(page) && page > 0 ? page : DEFAULT_PAGE; const normalizedPageSize = Number.isInteger(pageSize) && pageSize > 0 ? Math.min(pageSize, maxPageSize) : DEFAULT_PAGE_SIZE; return { page: normalizedPage, pageSize: normalizedPageSize, }; } /** * 规范化波次状态列表。 * * @param {Array} value 波次状态列表。 * @return {Array} 规范化后的状态数组。 */ normalizeWaveStatusList(value) { if (!Array.isArray(value)) { return [ 0, 1 ]; } const statusList = value .map(item => Number(item)) .filter(item => Number.isInteger(item)); if (statusList.length === 0) { return [ 0, 1 ]; } return [ ...new Set(statusList) ]; } /** * 规范化波次列表库位分配状态筛选值。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListStorageAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'storage'); } /** * 规范化波次列表快递分配状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListExpressAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'express'); } /** * 规范化波次列表打印状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListPrintAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); } /** * 规范化波次列表确认打印状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListConfirmPrintAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'confirm_print'); } /** * 规范化波次列表领料状态筛选值。 * * 领料状态以波次表 claim_time 为准(二态,无 partial): * - none = 未领料(claim_time IS NULL); * - finished = 已领料(claim_time IS NOT NULL)。 * * @param {string} value 入参筛选值(unclaimed/claimed,兼容中文 未领料/已领料)。 * @return {string} 规范化后的筛选值(none/finished),未传时返回空字符串。 */ normalizeBatchListClaimAssignmentStatusFilter(value) { if (value === undefined || value === null || value === '') { return ''; } const normalizedValue = String(value).trim().toLowerCase(); if (!normalizedValue) { return ''; } if ([ 'unclaimed', 'none', '未领料', '未领单' ].includes(normalizedValue)) { return 'none'; } if ([ 'claimed', 'finished', '已领料', '已领单' ].includes(normalizedValue)) { return 'finished'; } throw new Error('claim_assignment_status 参数不合法,仅支持: unclaimed / claimed(未领料 / 已领料)'); } /** * 规范化波次列表复核状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListReviewAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'review'); } /** * 规范化波次列表同步状态筛选值(英文枚举)。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListSyncAssignmentStatusFilter(value) { return this.normalizeBatchListAssignmentStatusFilterByType(value, 'sync'); } /** * 根据类型获取波次分配状态筛选配置。 * * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 * @return {{ fieldName: string, enumMap: Object, caseInsensitive: boolean, statsColumnPrefix: string, withErrorStatus: boolean }} 筛选配置。 */ getBatchListAssignmentFilterSchema(type) { const normalizedType = String(type || '').trim(); const schema = BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS[normalizedType]; if (!schema) { throw new Error(`不支持的分配状态筛选类型: ${normalizedType}`); } return schema; } /** * 按类型规范化波次列表分配状态筛选值。 * * @param {string} value 入参筛选值。 * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListAssignmentStatusFilterByType(value, type) { const schema = this.getBatchListAssignmentFilterSchema(type); return this.normalizeBatchListAssignmentStatusFilter(value, schema); } /** * 规范化波次列表分配状态筛选值。 * * @param {string} value 入参筛选值。 * @param {{ fieldName: string, enumMap: Object, caseInsensitive: boolean }} schema 筛选配置。 * @return {string} 规范化后的筛选标识(none/partial/finished)。 */ normalizeBatchListAssignmentStatusFilter(value, schema) { if (value === undefined || value === null || value === '') { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue) { return ''; } const enumMap = this.isPlainObject(schema && schema.enumMap) ? schema.enumMap : {}; const allowedValues = Object.keys(enumMap); const isCaseInsensitive = Boolean(schema && schema.caseInsensitive); const lookupValue = isCaseInsensitive ? normalizedValue.toLowerCase() : normalizedValue; const normalizedEnumMap = isCaseInsensitive ? Object.fromEntries( Object.entries(enumMap).map(([ key, mappedValue ]) => [ String(key).toLowerCase(), mappedValue ]) ) : enumMap; const matchedValue = normalizedEnumMap[lookupValue]; if (!matchedValue) { const fieldName = String(schema && schema.fieldName || 'assignment_status'); throw new Error(`${fieldName} 参数不合法,仅支持: ${allowedValues.join('、')}`); } return matchedValue; } /** * 解析模型对应的 SQL 表名并完成安全转义。 * * @param {Object} model Sequelize 模型对象。 * @return {string} 可直接拼接到 SQL 的表名。 */ getModelTableSqlName(model) { const rawTableName = model && typeof model.getTableName === 'function' ? model.getTableName() : model && model.tableName; const tableName = typeof rawTableName === 'string' ? rawTableName : rawTableName && typeof rawTableName.tableName === 'string' ? rawTableName.tableName : ''; const normalizedTableName = String(tableName || '').trim(); if (!normalizedTableName) { throw new Error('订单模型表名解析失败'); } const tableParts = normalizedTableName.split('.').map(part => String(part || '').trim()).filter(Boolean); if (tableParts.length === 0) { throw new Error('订单模型表名解析失败'); } for (const tablePart of tableParts) { if (!/^[a-zA-Z0-9_$]+$/.test(tablePart)) { throw new Error(`订单模型表名不合法: ${normalizedTableName}`); } } return tableParts.map(part => `\`${part}\``).join('.'); } /** * 构建波次列表库位分配状态筛选 SQL 条件。 * * @param {string} statusFilter 库位分配状态筛选值。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListStorageAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'storage'); } /** * 构建波次列表快递分配状态筛选 SQL 条件。 * * @param {string} statusFilter 快递分配状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListExpressAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'express'); } /** * 构建波次列表打印状态筛选 SQL 条件。 * * @param {string} statusFilter 打印状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListPrintAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); } /** * 构建波次列表确认打印状态筛选 SQL 条件。 * * @param {string} statusFilter 确认打印状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListConfirmPrintAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'confirm_print'); } /** * 构建波次列表领料状态筛选 SQL 条件(波次表 claim_time 口径,二态)。 * * @param {string} statusFilter 领料状态筛选值(none/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListClaimAssignmentFilterClause(statusFilter = '') { const normalizedStatusFilter = String(statusFilter || '').trim(); if (!normalizedStatusFilter) { return { sql: '', replacements: {}, }; } if (normalizedStatusFilter === 'none') { return { sql: '\n AND wb.claim_time IS NULL', replacements: {}, }; } if (normalizedStatusFilter === 'finished') { return { sql: '\n AND wb.claim_time IS NOT NULL', replacements: {}, }; } throw new Error(`不支持的领料状态筛选值: ${normalizedStatusFilter}`); } /** * 构建波次列表复核状态筛选 SQL 条件。 * * @param {string} statusFilter 复核状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListReviewAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'review'); } /** * 构建波次列表同步状态筛选 SQL 条件。 * * @param {string} statusFilter 同步状态筛选值(none/partial/finished)。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListSyncAssignmentFilterClause(statusFilter = '') { return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'sync'); } /** * 按类型构建波次列表分配状态筛选 SQL 条件。 * * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 * @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListAssignmentStatusFilterClauseByType(statusFilter = '', type = 'storage') { const schema = this.getBatchListAssignmentFilterSchema(type); return this.buildBatchListAssignmentStatusFilterClause(statusFilter, schema); } /** * 构建波次列表分配状态筛选 SQL 条件(通用)。 * * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 * @param {{ statsColumnPrefix: string, withErrorStatus: boolean }} schema 筛选配置。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListAssignmentStatusFilterClause(statusFilter = '', schema = {}) { const normalizedStatusFilter = String(statusFilter || '').trim(); if (!normalizedStatusFilter) { return { sql: '', replacements: {}, }; } const statsPrefix = String(schema && schema.statsColumnPrefix || '').trim(); if (!statsPrefix) { throw new Error('分配状态筛选配置不完整,缺少统计字段前缀'); } const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; const noneExpr = `COALESCE(wave_order_stats.${statsPrefix}_none_count, 0)`; const finExpr = `COALESCE(wave_order_stats.${statsPrefix}_fin_count, 0)`; const withErrorStatus = Boolean(schema && schema.withErrorStatus); const errorExpr = withErrorStatus ? `COALESCE(wave_order_stats.${statsPrefix}_error_count, 0)` : ''; if (normalizedStatusFilter === 'finished') { return { sql: ` AND ${finExpr} = ${totalExpr} AND ${totalExpr} > 0`, replacements: {}, }; } if (normalizedStatusFilter === 'partial') { return { sql: ` AND ${withErrorStatus ? `${errorExpr} = 0\n AND ` : ''}${noneExpr} <> ${totalExpr} AND ${finExpr} <> ${totalExpr}`, replacements: {}, }; } if (normalizedStatusFilter === 'none') { return { sql: ` AND ( ${totalExpr} = 0 ${withErrorStatus ? `OR ${errorExpr} > 0\n ` : ''}OR ${noneExpr} = ${totalExpr} )`, replacements: {}, }; } throw new Error(`不支持的分配状态筛选值: ${normalizedStatusFilter}`); } /** * 判断波次列表 where 字段条件是否为空值。 * * 空值(undefined/null/空串/空数组)不参与 SQL 拼接; * 例外:显式声明 isnull/isnotnull 的标准结构即使不带 value 也视为有效条件。 * * @param {*} rawCondition 原始条件值。 * @return {boolean} 是否为空值。 */ isEmptyBatchListWhereValue(rawCondition) { if (rawCondition === undefined || rawCondition === null) { return true; } if (typeof rawCondition === 'string') { return rawCondition.trim() === ''; } if (Array.isArray(rawCondition)) { return rawCondition.length === 0; } if (this.isPlainObject(rawCondition)) { const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] .some(key => Object.prototype.hasOwnProperty.call(rawCondition, key)); if (!hasStandardKeys) { return false; } const operator = String(rawCondition.operator || '').toLowerCase(); if (operator === 'isnull' || operator === 'isnotnull') { return false; } const value = Object.prototype.hasOwnProperty.call(rawCondition, 'value') ? rawCondition.value : rawCondition.values; if (value === undefined || value === null) { return true; } if (typeof value === 'string' && value.trim() === '') { return true; } if (Array.isArray(value) && value.length === 0) { return true; } return false; } return false; } /** * 解析波次列表单字段条件(兼容裸值与 {operator,value,type} 标准结构)。 * * - 标准结构(含 value/operator/type/field/values 任一键):显式读取 operator,缺省回落 defaultOperator; * - 裸值:数组按 in 处理,其余按 defaultOperator(保持历史语义,如 wave_no 默认模糊匹配)。 * * @param {*} rawCondition 原始条件值。 * @param {string} [defaultOperator='eq'] 未显式传 operator 时的默认操作符。 * @return {{ operator: string, value: *, hasExplicitOperator: boolean }} 解析结果。 */ resolveBatchListFieldCondition(rawCondition, defaultOperator = 'eq') { const isStandardCondition = this.isPlainObject(rawCondition) && [ 'value', 'operator', 'type', 'field', 'values' ] .some(key => Object.prototype.hasOwnProperty.call(rawCondition, key)); if (isStandardCondition) { const normalized = this.normalizeWhereCondition('__batch_list_where_field__', rawCondition); return { operator: String(normalized.operator || defaultOperator).toLowerCase(), value: normalized.value, hasExplicitOperator: true, }; } return { operator: Array.isArray(rawCondition) ? 'in' : String(defaultOperator || 'eq').toLowerCase(), value: rawCondition, hasExplicitOperator: false, }; } /** * 将波次列表单字段条件构建为 SQL 片段与占位符参数。 * * 支持操作符:eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/ * notlike/startswith/endswith/isnull/isnotnull(调用方通过 allowedOperators 限定)。 * 数组值:like/contains/startswith/endswith 多值按 OR 展开,notlike 多值按 AND 展开。 * * @param {Object} options 构建参数。 * @param {string} options.fieldKey 字段名(用于错误提示)。 * @param {string} options.columnName 目标 SQL 列名(服务端白名单常量)。 * @param {*} options.rawCondition 原始条件值。 * @param {string} [options.defaultOperator='eq'] 默认操作符。 * @param {'text'|'integer'|'number'} [options.valueType='text'] 值类型。 * @param {boolean} [options.allowZero=true] integer 类型是否允许 0。 * @param {Array} [options.allowedOperators=[]] 允许的操作符集合,空数组表示不限制。 * @param {Function} [options.valueNormalizer=null] 自定义值归一化函数,优先级最高。 * @param {string} [options.replacementKeyBase='whereField'] 占位符前缀。 * @param {Object} [options.replacements={}] 占位符参数收集对象。 * @return {string} SQL 条件片段(不含前导 AND),无有效条件时返回空字符串。 */ buildBatchListFieldConditionSql(options = {}) { const { fieldKey, columnName, rawCondition, defaultOperator = 'eq', valueType = 'text', allowZero = true, allowedOperators = [], valueNormalizer = null, replacementKeyBase = 'whereField', replacements = {}, } = options; if (this.isEmptyBatchListWhereValue(rawCondition)) { return ''; } const resolved = this.resolveBatchListFieldCondition(rawCondition, defaultOperator); const rawValue = resolved.value; let operator = String(resolved.operator || defaultOperator).toLowerCase(); if (allowedOperators.length > 0 && !allowedOperators.includes(operator)) { throw new Error(`${fieldKey} 不支持操作符: ${operator},仅支持: ${allowedOperators.join('、')}`); } const normalizeSingleValue = item => { if (typeof valueNormalizer === 'function') { return valueNormalizer(item); } if (valueType === 'number') { const numberValue = Number(item); if (!Number.isFinite(numberValue)) { throw new Error(`${fieldKey} 参数不合法`); } return numberValue; } if (valueType === 'integer') { const numberValue = Number(item); const isValidInteger = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); if (!isValidInteger) { throw new Error(`${fieldKey} 参数不合法`); } return numberValue; } const textValue = String(item === undefined || item === null ? '' : item).trim(); if (!textValue) { throw new Error(`${fieldKey} 参数不合法`); } return textValue; }; const normalizeValueList = () => { const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ]; const valueList = sourceList.filter(item => item !== undefined && item !== null && String(item).trim() !== ''); if (valueList.length === 0) { throw new Error(`${fieldKey} 参数不合法`); } return valueList.map(item => normalizeSingleValue(item)); }; // eq + 数组等价于 in(与 Sequelize 字段数组语义保持一致) if (operator === 'eq' && Array.isArray(rawValue)) { operator = 'in'; } switch (operator) { case 'eq': case 'ne': { const singleValue = normalizeSingleValue(Array.isArray(rawValue) ? rawValue[0] : rawValue); replacements[replacementKeyBase] = singleValue; return `${columnName} ${operator === 'eq' ? '=' : '<>'} :${replacementKeyBase}`; } case 'gt': case 'lt': case 'ge': case 'le': { const comparators = { gt: '>', lt: '<', ge: '>=', le: '<=', }; const singleValue = normalizeSingleValue(Array.isArray(rawValue) ? rawValue[0] : rawValue); replacements[replacementKeyBase] = singleValue; return `${columnName} ${comparators[operator]} :${replacementKeyBase}`; } case 'like': case 'contains': case 'startswith': case 'endswith': { const valueList = normalizeValueList(); const useMultipleKeys = valueList.length > 1; const clauses = valueList.map((textValue, index) => { const replacementKey = useMultipleKeys ? `${replacementKeyBase}${index}` : replacementKeyBase; replacements[replacementKey] = operator === 'startswith' ? `${textValue}%` : operator === 'endswith' ? `%${textValue}` : `%${textValue}%`; return `${columnName} LIKE :${replacementKey}`; }); return clauses.length > 1 ? `(${clauses.join(' OR ')})` : clauses[0]; } case 'notlike': { const valueList = normalizeValueList(); const useMultipleKeys = valueList.length > 1; const clauses = valueList.map((textValue, index) => { const replacementKey = useMultipleKeys ? `${replacementKeyBase}${index}` : replacementKeyBase; replacements[replacementKey] = `%${textValue}%`; return `${columnName} NOT LIKE :${replacementKey}`; }); return clauses.length > 1 ? `(${clauses.join(' AND ')})` : clauses[0]; } case 'in': case 'notin': { const valueList = normalizeValueList(); replacements[replacementKeyBase] = valueList; return `${columnName} ${operator === 'in' ? 'IN' : 'NOT IN'} (:${replacementKeyBase})`; } case 'between': case 'notbetween': { let betweenValue = rawValue; if (this.isPlainObject(betweenValue)) { const start = betweenValue.start ?? betweenValue.from ?? betweenValue.begin; const end = betweenValue.end ?? betweenValue.to ?? betweenValue.finish; betweenValue = [ start, end ]; } if (!Array.isArray(betweenValue) || betweenValue.length !== 2) { throw new Error(`${fieldKey} 的 ${operator} 操作符要求 value 为长度为2的数组`); } const startValue = normalizeSingleValue(betweenValue[0]); const endValue = normalizeSingleValue(betweenValue[1]); replacements[`${replacementKeyBase}From`] = startValue; replacements[`${replacementKeyBase}To`] = endValue; return operator === 'between' ? `${columnName} BETWEEN :${replacementKeyBase}From AND :${replacementKeyBase}To` : `(${columnName} < :${replacementKeyBase}From OR ${columnName} > :${replacementKeyBase}To)`; } case 'isnull': return `${columnName} IS NULL`; case 'isnotnull': return `${columnName} IS NOT NULL`; default: throw new Error(`${fieldKey} 不支持操作符: ${operator}`); } } /** * 归一化波次列表 distinguish_express 条件值(布尔/数字/文本统一为 0/1)。 * * @param {*} value 原始值。 * @return {number} 0 或 1。 */ normalizeBatchListDistinguishExpressValue(value) { if (typeof value === 'boolean') { return value ? 1 : 0; } if (typeof value === 'number') { if (value !== 0 && value !== 1) { throw new Error('distinguish_express 参数不合法'); } return value; } const boolText = String(value === undefined || value === null ? '' : value).trim().toLowerCase(); if ([ '1', 'true', 'yes', 'y', 'on' ].includes(boolText)) { return 1; } if ([ '0', 'false', 'no', 'n', 'off' ].includes(boolText)) { return 0; } throw new Error('distinguish_express 参数不合法'); } /** * 解析波次列表 store_id 筛选条件。 * * 兼容单值/数组/{operator,value}:默认按 in 匹配(返回包含任一筛选货主订单的波次,含混合货主波次); * operator=ne/notin 时反向匹配(排除包含所选货主订单的波次)。 * * @param {*} rawCondition 原始条件。 * @return {{ operator: 'in'|'notin', ids: number[] }} 归一化结果。 */ normalizeBatchListStoreIdCondition(rawCondition) { if (rawCondition === undefined || rawCondition === null || rawCondition === '') { return { operator: 'in', ids: [], }; } const resolved = this.resolveBatchListFieldCondition(rawCondition, 'in'); const operator = String(resolved.operator || 'in').toLowerCase(); if (![ 'eq', 'in', 'ne', 'notin' ].includes(operator)) { throw new Error(`store_id 不支持操作符: ${operator},仅支持: eq、in、ne、notin`); } const rawValue = resolved.value; const sourceList = Array.isArray(rawValue) ? rawValue : [ rawValue ]; const normalizedIds = []; for (const item of sourceList) { if (item === undefined || item === null || item === '') { continue; } const numberValue = Number(String(item).trim()); if (!Number.isInteger(numberValue) || numberValue <= 0) { throw new Error('store_id 参数不合法'); } normalizedIds.push(numberValue); } return { operator: operator === 'in' || operator === 'eq' ? 'in' : 'notin', ids: [ ...new Set(normalizedIds) ], }; } /** * 构建波次列表 where 条件(白名单字段)。 * * 每个白名单字段均支持裸值与 `{ operator, value, type }` 标准结构; * 未显式传 operator 时按字段默认语义(wave_no/creator/logistics_name/item_part/ * item_snapshot_key/item_detail_machine 默认 contains 模糊,其余默认 eq)。 * * @param {Object} whereData 查询 where 入参。 * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string, reviewAssignmentStatus: string, storeIds: number[], storeIdOperator: 'in'|'notin' }} SQL 条件片段、参数与分配状态筛选值。 */ buildBatchListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; const whereKeys = Object.keys(normalizedWhere); if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); } const allowedFields = [ 'wave_id', 'wave_no', 'wave_type', 'wave_status', 'creator', 'logistics_name', 'item_part_type', 'item_part', 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', 'source', 'total_orders', 'total_orders_min', 'total_orders_max', 'processed_orders', 'processed_orders_min', 'processed_orders_max', 'storage_assignment_status', 'express_assignment_status', 'print_assignment_status', 'confirm_print_assignment_status', 'claim_assignment_status', 'review_assignment_status', 'sync_assignment_status', 'store_id', ]; const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); if (invalidFields.length > 0) { throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); } const conditions = []; const replacements = {}; const textSearchOperators = [ 'eq', 'ne', 'like', 'contains', 'notlike', 'startswith', 'endswith', 'in', 'notin', 'isnull', 'isnotnull' ]; const comparableOperators = [ 'eq', 'ne', 'gt', 'lt', 'ge', 'le', 'in', 'notin', 'between', 'notbetween', 'isnull', 'isnotnull' ]; const fieldSpecs = [ { fieldKey: 'wave_id', columnName: 'wave_id', defaultOperator: 'eq', valueType: 'integer', allowZero: false, allowedOperators: comparableOperators, replacementKeyBase: 'whereWaveId', }, { fieldKey: 'wave_no', columnName: 'wave_no', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereWaveNo', }, { fieldKey: 'wave_type', columnName: 'wave_type', defaultOperator: 'eq', valueType: 'integer', allowedOperators: comparableOperators, replacementKeyBase: 'whereWaveType', }, { fieldKey: 'wave_status', columnName: 'wave_status', defaultOperator: 'eq', valueType: 'integer', allowedOperators: comparableOperators, replacementKeyBase: 'whereWaveStatus', }, { fieldKey: 'source', columnName: 'source', defaultOperator: 'eq', valueType: 'integer', allowedOperators: comparableOperators, replacementKeyBase: 'whereSource', }, { fieldKey: 'creator', columnName: 'creator', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereCreator', }, { fieldKey: 'logistics_name', columnName: 'logistics_name', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereLogisticsName', }, { fieldKey: 'item_part_type', columnName: 'item_part_type', defaultOperator: 'eq', allowedOperators: textSearchOperators, replacementKeyBase: 'whereItemPartType', }, { fieldKey: 'item_part', columnName: 'item_part', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereItemPart', }, { fieldKey: 'item_snapshot_key', columnName: 'item_snapshot_key', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereItemSnapshotKey', }, { fieldKey: 'item_detail_machine', columnName: 'item_detail_machine', defaultOperator: 'like', allowedOperators: textSearchOperators, replacementKeyBase: 'whereItemDetailMachine', }, { fieldKey: 'distinguish_express', columnName: 'distinguish_express', defaultOperator: 'eq', valueType: 'integer', valueNormalizer: value => this.normalizeBatchListDistinguishExpressValue(value), allowedOperators: [ 'eq', 'ne', 'in', 'notin' ], replacementKeyBase: 'whereDistinguishExpress', }, { fieldKey: 'total_orders', columnName: 'total_orders', defaultOperator: 'eq', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereTotalOrders', }, { fieldKey: 'total_orders_min', columnName: 'total_orders', defaultOperator: 'ge', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereTotalOrdersMin', }, { fieldKey: 'total_orders_max', columnName: 'total_orders', defaultOperator: 'le', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereTotalOrdersMax', }, { fieldKey: 'processed_orders', columnName: 'processed_orders', defaultOperator: 'eq', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereProcessedOrders', }, { fieldKey: 'processed_orders_min', columnName: 'processed_orders', defaultOperator: 'ge', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereProcessedOrdersMin', }, { fieldKey: 'processed_orders_max', columnName: 'processed_orders', defaultOperator: 'le', valueType: 'number', allowedOperators: comparableOperators, replacementKeyBase: 'whereProcessedOrdersMax', }, ]; for (const fieldSpec of fieldSpecs) { if (!Object.prototype.hasOwnProperty.call(normalizedWhere, fieldSpec.fieldKey)) { continue; } const fieldSql = this.buildBatchListFieldConditionSql({ ...fieldSpec, rawCondition: normalizedWhere[fieldSpec.fieldKey], replacements, }); if (fieldSql) { conditions.push(fieldSql); } } // store_id 货主筛选:支持单值/数组/{operator,value},默认 in(含混合货主波次),ne/notin 为排除语义。 const storeIdCondition = this.normalizeBatchListStoreIdCondition(normalizedWhere.store_id); // 分配状态类筛选:由聚合统计判定,仅支持等值;显式传入其他操作符直接报错。 const resolveAssignmentStatusFilter = (fieldKey, statusNormalizer) => { const rawCondition = normalizedWhere[fieldKey]; if (this.isEmptyBatchListWhereValue(rawCondition)) { return ''; } const { operator, value } = this.resolveBatchListFieldCondition(rawCondition, 'eq'); if (operator !== 'eq') { throw new Error(`${fieldKey} 不支持操作符: ${operator},仅支持: eq`); } return statusNormalizer(value); }; const storageAssignmentStatus = resolveAssignmentStatusFilter( 'storage_assignment_status', value => this.normalizeBatchListStorageAssignmentStatusFilter(value) ); const expressAssignmentStatus = resolveAssignmentStatusFilter( 'express_assignment_status', value => this.normalizeBatchListExpressAssignmentStatusFilter(value) ); const printAssignmentStatus = resolveAssignmentStatusFilter( 'print_assignment_status', value => this.normalizeBatchListPrintAssignmentStatusFilter(value) ); const confirmPrintAssignmentStatus = resolveAssignmentStatusFilter( 'confirm_print_assignment_status', value => this.normalizeBatchListConfirmPrintAssignmentStatusFilter(value) ); const claimAssignmentStatus = resolveAssignmentStatusFilter( 'claim_assignment_status', value => this.normalizeBatchListClaimAssignmentStatusFilter(value) ); const reviewAssignmentStatus = resolveAssignmentStatusFilter( 'review_assignment_status', value => this.normalizeBatchListReviewAssignmentStatusFilter(value) ); const syncAssignmentStatus = resolveAssignmentStatusFilter( 'sync_assignment_status', value => this.normalizeBatchListSyncAssignmentStatusFilter(value) ); return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', replacements, storageAssignmentStatus, expressAssignmentStatus, printAssignmentStatus, confirmPrintAssignmentStatus, claimAssignmentStatus, reviewAssignmentStatus, syncAssignmentStatus, storeIds: storeIdCondition.ids, storeIdOperator: storeIdCondition.operator, }; } /** * 解析拣货任务列表分页参数。 * * 兼容 current/size 写法,并复用通用分页归一化能力。 * * @param {Object} data 请求参数。 * @return {{ page: number, pageSize: number }} 归一化分页。 */ normalizeWavePickTaskListPagination(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const pagination = this.isPlainObject(normalizedData.pagination) ? normalizedData.pagination : normalizedData; const pageSource = pagination.page ?? pagination.page_no ?? pagination.pageNo ?? pagination.current; const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.size; return this.normalizePagination({ page: pageSource, pageSize: pageSizeSource, }); } /** * 归一化拣货任务列表请求参数。 * * 兼容顶层筛选参数与 where 结构并保持旧调用可用: * - 顶层支持 warehouse_id/status/source/keyword/task_no/cart_id/cart_code * - 同名字段优先使用顶层值覆盖 where * - warehouse_id 未传时回退当前仓库上下文 * * @param {Object} data 请求参数。 * @return {{ warehouseId: number, where: Object }} 归一化仓库与查询条件。 */ normalizeWavePickTaskListRequest(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const baseWhere = this.isPlainObject(requestData.where) ? { ...requestData.where } : {}; const mergeFieldFromTopLevel = fieldName => { if (Object.prototype.hasOwnProperty.call(requestData, fieldName)) { baseWhere[fieldName] = requestData[fieldName]; } }; [ 'status', 'source', 'keyword', 'task_no', 'wave_no', 'pick_mode', 'review_status', 'pick_user_id', 'review_user_id', 'pick_user_name', 'review_user_name', 'claim_operator', 'cart_id', 'cart_code', 'start_time_start', 'start_time_end', ].forEach(mergeFieldFromTopLevel); const contextWarehouseId = Number(this.getWarehouseId() || 0); const inputWarehouseId = requestData.warehouse_id ?? requestData.warehouseId; const warehouseId = inputWarehouseId !== undefined && inputWarehouseId !== null && inputWarehouseId !== '' ? Number(inputWarehouseId) : contextWarehouseId; if (!Number.isInteger(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 参数不合法'); } if (Number.isInteger(contextWarehouseId) && contextWarehouseId > 0 && inputWarehouseId !== undefined && inputWarehouseId !== null && inputWarehouseId !== '' && warehouseId !== contextWarehouseId) { throw new Error('warehouse_id 与当前仓库上下文不一致'); } return { warehouseId, where: baseWhere, }; } /** * 构建拣货任务列表 where 条件(白名单字段)。 * * 注意:当前 wms_wave_pick_task 主表未落 strategy_id 字段, * 因此 strategy_id 过滤入参会被忽略,不参与 SQL 条件拼接。 * * @param {Object} whereData 查询 where 入参。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildWavePickTaskListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; const whereKeys = Object.keys(normalizedWhere); const allowedFields = [ 'status', 'review_status', 'pick_mode', 'source', 'strategy_id', 'pick_user_id', 'review_user_id', 'pick_user_name', 'review_user_name', 'claim_operator', 'task_no', 'wave_no', 'cart_id', 'cart_code', 'keyword', 'start_time_start', 'start_time_end', ]; const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); if (invalidFields.length > 0) { throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); } const conditions = []; const replacements = {}; const appendIntegerEqualCondition = (fieldKey, columnName, replacementKey, allowZero = true) => { const value = normalizedWhere[fieldKey]; if (value === undefined || value === null || value === '') { return; } const numberValue = Number(value); const isValid = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); if (!isValid) { throw new Error(`${fieldKey} 参数不合法`); } conditions.push(`${columnName} = :${replacementKey}`); replacements[replacementKey] = numberValue; }; const status = normalizedWhere.status; if (Array.isArray(status)) { const normalizedStatusList = [ ...new Set(status .map(value => Number(value)) .filter(value => Number.isInteger(value) && value >= 0)) ]; if (normalizedStatusList.length <= 0) { throw new Error('status 参数不合法'); } conditions.push('t.status IN (:whereStatusList)'); replacements.whereStatusList = normalizedStatusList; } else { appendIntegerEqualCondition('status', 't.status', 'whereStatus'); } appendIntegerEqualCondition('review_status', 't.review_status', 'whereReviewStatus'); appendIntegerEqualCondition('pick_mode', 't.pick_mode', 'wherePickMode', false); appendIntegerEqualCondition('source', 't.source', 'whereSource', false); appendIntegerEqualCondition('pick_user_id', 't.pick_user_id', 'wherePickUserId'); appendIntegerEqualCondition('review_user_id', 't.review_user_id', 'whereReviewUserId'); appendIntegerEqualCondition('cart_id', 't.current_cart_id', 'whereCartId', false); const taskNo = normalizedWhere.task_no; if (taskNo !== undefined && taskNo !== null && taskNo !== '') { const normalizedTaskNo = String(taskNo).trim(); if (!normalizedTaskNo) { throw new Error('task_no 参数不合法'); } conditions.push('t.task_no LIKE :whereTaskNo'); replacements.whereTaskNo = `%${normalizedTaskNo}%`; } const appendNameCondition = (fieldKey, columnName, replacementKey) => { const raw = normalizedWhere[fieldKey]; if (raw === undefined || raw === null || raw === '') { return; } // 支持操作符对象:{ operator: 'like' | 'notlike' | 'eq', value },默认 like let operator = 'like'; let value = raw; if (this.isPlainObject(raw)) { operator = String(raw.operator || 'like').trim().toLowerCase(); value = raw.value; } if (value === undefined || value === null || value === '') { return; } const normalizedValue = String(value).trim(); if (!normalizedValue) { throw new Error(`${fieldKey} 参数不合法`); } if (operator === 'eq') { conditions.push(`${columnName} = :${replacementKey}`); replacements[replacementKey] = normalizedValue; } else if (operator === 'notlike') { conditions.push(`(${columnName} NOT LIKE :${replacementKey} OR ${columnName} IS NULL)`); replacements[replacementKey] = `%${normalizedValue}%`; } else if (operator !== 'like') { throw new Error(`${fieldKey} 不支持的 operator: ${operator}`); } else { conditions.push(`${columnName} LIKE :${replacementKey}`); replacements[replacementKey] = `%${normalizedValue}%`; } }; appendNameCondition('pick_user_name', 't.pick_user_name', 'wherePickUserName'); appendNameCondition('review_user_name', 't.review_user_name', 'whereReviewUserName'); appendNameCondition('claim_operator', 't.claim_operator', 'whereClaimOperator'); appendNameCondition('wave_no', 't.batch_no_array', 'whereWaveNo'); // 拣货车编码:主表冗余的绑定快照(current_cart_code_snapshot),与列表返回字段同源, // 支持操作符对象 { operator: 'like'|'notlike'|'eq', value },默认 like appendNameCondition('cart_code', 't.current_cart_code_snapshot', 'whereCartCode'); const keyword = normalizedWhere.keyword; if (keyword !== undefined && keyword !== null && keyword !== '') { const normalizedKeyword = String(keyword).trim(); if (!normalizedKeyword) { throw new Error('keyword 参数不合法'); } conditions.push(`( t.task_no LIKE :whereKeyword OR t.pick_user_name LIKE :whereKeyword OR t.review_user_name LIKE :whereKeyword OR t.batch_no LIKE :whereKeyword OR t.current_cart_code_snapshot LIKE :whereKeyword )`); replacements.whereKeyword = `%${normalizedKeyword}%`; } const startTimeStart = normalizedWhere.start_time_start; if (startTimeStart !== undefined && startTimeStart !== null && startTimeStart !== '') { const normalizedStartTimeStart = String(startTimeStart).trim(); const startDate = new Date(normalizedStartTimeStart); if (!normalizedStartTimeStart || Number.isNaN(startDate.getTime())) { throw new Error('start_time_start 参数不合法'); } conditions.push('t.create_time >= :whereCreateTimeStart'); replacements.whereCreateTimeStart = normalizedStartTimeStart; } const startTimeEnd = normalizedWhere.start_time_end; if (startTimeEnd !== undefined && startTimeEnd !== null && startTimeEnd !== '') { const normalizedStartTimeEnd = String(startTimeEnd).trim(); const endDate = new Date(normalizedStartTimeEnd); if (!normalizedStartTimeEnd || Number.isNaN(endDate.getTime())) { throw new Error('start_time_end 参数不合法'); } conditions.push('t.create_time <= :whereCreateTimeEnd'); replacements.whereCreateTimeEnd = normalizedStartTimeEnd; } return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', replacements, }; } /** * 解析分配状态。 * * @param {number} total 总数量。 * @param {number} noneCount 未分配数量。 * @param {number} finCount 已分配数量。 * @param {number} errorCount 分配异常数量。 * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 * @return {string} 分配状态。 */ resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { const normalizedTotal = Number(total || 0); const normalizedNoneCount = Number(noneCount || 0); const normalizedFinCount = Number(finCount || 0); const normalizedErrorCount = Number(errorCount || 0); const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; const noneLabel = String(normalizedLabels.none || '未分配'); const partialLabel = String(normalizedLabels.partial || '部分分配'); const finishedLabel = String(normalizedLabels.finished || '已分配'); const errorLabel = String(normalizedLabels.error || '分配异常'); if (normalizedErrorCount > 0) { return errorLabel; } if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { return noneLabel; } if (normalizedFinCount === normalizedTotal) { return finishedLabel; } return partialLabel; } normalizeSkuText(value) { if (value === undefined || value === null) { return ''; } return String(value).trim(); } normalizeShopName(value) { if (value === undefined || value === null) { return ''; } return String(value).trim(); } parseItemSnapshot(rawSnapshot) { if (!rawSnapshot) { return {}; } if (typeof rawSnapshot === 'string') { try { const parsed = JSON.parse(rawSnapshot); return parsed && typeof parsed === 'object' ? parsed : {}; } catch { return {}; } } return typeof rawSnapshot === 'object' ? rawSnapshot : {}; } normalizeOrderItemRow(row = {}) { const snapshot = this.parseItemSnapshot(row.item_snapshot); const stockIdRaw = snapshot.stock_id ?? row.stock_id; const quantityRaw = row.plan_qty; const stockId = Number(stockIdRaw || 0); const quantity = Number(quantityRaw || 0); return { stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), barcode: String(snapshot.barcode ?? '').trim(), quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, }; } mergeOrderItemDetails(itemRows = []) { const merged = new Map(); for (const row of itemRows) { const normalized = this.normalizeOrderItemRow(row); const hasIdentity = normalized.stock_id > 0 || normalized.item_code || normalized.item_name; if (!hasIdentity || normalized.quantity <= 0) { continue; } const key = [ normalized.stock_id, normalized.item_code, normalized.item_name, normalized.barcode, ].join('||'); if (!merged.has(key)) { merged.set(key, { stock_id: normalized.stock_id, item_code: normalized.item_code, item_name: normalized.item_name, barcode: normalized.barcode, quantity: 0, }); } merged.get(key).quantity += normalized.quantity; } return Array.from(merged.values()) .sort((a, b) => { if (a.stock_id !== b.stock_id) return a.stock_id - b.stock_id; return String(a.item_code).localeCompare(String(b.item_code)); }); } buildItemSummary(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; } return itemDetails .map(item => { const name = String(item.item_name || '').trim(); const barcode = String(item.barcode || item.item_code || '').trim(); const qty = item.quantity; return `${name}${barcode ? `(${barcode})` : ''}×${qty}`; }) .join(' | '); } /** * 构建订单商品快照字符串。 * * 输出格式:商品名称1*数量|商品名称2*数量。 * * @param {Array} itemDetails 商品明细列表。 * @return {string} 商品快照字符串。 */ buildOrderItemSnapshot(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; } const segments = itemDetails .map(item => { const itemName = String(item && (item.item_name || item.item_code) || '').trim(); const quantity = Number(item && item.quantity || 0); if (!itemName || !Number.isFinite(quantity) || quantity <= 0) { return ''; } return `${itemName}*${quantity}`; }) .filter(Boolean); return segments.join('|'); } buildItemSnapshotKey(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; } return itemDetails.map(item => [ item.stock_id, item.item_code, item.item_name, item.barcode, item.quantity, ].join('::')).join('|'); } orderMatchesIncludeSku(itemDetails = [], includeSku = '') { const token = String(includeSku || '').trim().toLowerCase(); if (!token) { return true; } return itemDetails.some(item => String(item.item_code || '').toLowerCase().includes(token)); } buildCoarseGroupKey(order = {}, distinguishExpress = false) { const itemsHash = String(order.items_hash || '').trim(); const itemsText = String(order.items || '').trim(); const logisticsName = String(order.sys_logistics_code || '').trim(); const itemPart = itemsHash || itemsText; if (!itemPart) { return ''; } return distinguishExpress ? `${itemPart}||${logisticsName}` : itemPart; } buildStatusSummary(orders = []) { const summary = { post_none: 0, post_fin: 0, post_padding: 0, pick_none: 0, pick_fin: 0, outbound_none: 0, outbound_fin: 0, }; for (const order of orders) { const postStatus = String(order.post_status || ''); const pickStatus = String(order.pick_status || ''); const outboundStatus = String(order.outbound_status || ''); if (postStatus === 'none') summary.post_none += 1; if (postStatus === 'fin') summary.post_fin += 1; if (postStatus === 'padding') summary.post_padding += 1; if (pickStatus === 'none') summary.pick_none += 1; if (pickStatus === 'fin') summary.pick_fin += 1; if (outboundStatus === 'none') summary.outbound_none += 1; if (outboundStatus === 'fin') summary.outbound_fin += 1; } return summary; } buildGroupKey(order, itemDetails = [], options = {}) { const itemSummary = this.buildItemSummary(itemDetails); const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); const logisticsName = String(order.sys_logistics_code || '').trim(); const baseParts = [ itemSnapshotKey ]; if (options.distinguishExpress) { baseParts.push(logisticsName); } return { key: baseParts.join('||'), itemSummary, itemSnapshotKey, itemDetails, logisticsName, }; } /** * 团购波次可抓取列表。 * * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 * * @param {Object} data 请求参数。 * @return {Promise} 抓取列表和分页信息。 */ async groupOrderFetchList(data = {}) { const t0 = Date.now(); const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); const model = await this.getOrderModel('pendingOrder', warehouseId); const t1 = Date.now(); const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); const sameOrderQuantityInput = requestData.same_order_quantity; const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); const explicitSameOrderQuantity = hasSameOrderQuantityInput ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) : 0; const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); const sameOrderQuantity = explicitSameOrderQuantity > 0 ? explicitSameOrderQuantity : minGroupOrderFetchQuantity; const shopName = this.normalizeShopName(requestData.shop_name); const includeSku = this.normalizeSkuText(requestData.include_sku); const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); const stockQuery = String(requestData.stock_query || '').trim(); const { page, pageSize } = this.normalizePagination(requestData); const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, intercept_status: 'none', lock_status: 'none', wave_id: 0, }; if (storeId > 0) { where.store_id = storeId; } if (shopName) { where.shop_nick = { [Op.like]: `%${shopName}%` }; } // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 if (stockQuery) { const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); if (stockOrderIds.length > 0) { where.id = { [Op.in]: stockOrderIds }; } else { // 未匹配到任何商品,直接返回空列表 return { list: [], pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, }; } } // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, attributes: [ 'id', 'store_id', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name', 'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, order: [[ 'id', 'DESC' ]], }); const t2 = Date.now(); // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 // coarseGroupMap: coarseKey -> { orders[] } const coarseGroupMap = new Map(); for (const order of rawOrders) { const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); if (!coarseKey) { continue; } if (!coarseGroupMap.has(coarseKey)) { coarseGroupMap.set(coarseKey, { orders: [] }); } coarseGroupMap.get(coarseKey).orders.push(order); } // 过滤最小阈值、排序 let groupEntries = Array.from(coarseGroupMap.entries()); groupEntries = groupEntries.filter(([ , g ]) => g.orders.length >= sameOrderQuantity); groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { if (gB.orders.length !== gA.orders.length) { return gB.orders.length - gA.orders.length; } return keyA.localeCompare(keyB); }); const total = groupEntries.length; const t3 = Date.now(); // Phase 3: 分页分组,只取当前页 const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; const pageStart = (page - 1) * pageSize; const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId for (const [ coarseKey, g ] of pageGroupEntries) { const repOrder = g.orders.find(o => Number(o.id) > 0); if (repOrder) { representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); } } const pageOrderIds = Array.from(representativeIdPerGroup.values()); const t4 = Date.now(); // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); const orderItemRows = pageOrderIds.length > 0 ? await orderItemsModel.findAll({ where: { order_id: { [Op.in]: pageOrderIds } }, attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], raw: true, }) : []; const t5 = Date.now(); // 构建明细索引 const orderItemsMap = new Map(); for (const row of orderItemRows) { const orderId = Number(row && row.order_id); if (!Number.isInteger(orderId) || orderId <= 0) { continue; } if (!orderItemsMap.has(orderId)) { orderItemsMap.set(orderId, []); } orderItemsMap.get(orderId).push(row); } // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 const list = []; for (const [ coarseKey, g ] of pageGroupEntries) { // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 const representativeId = representativeIdPerGroup.get(coarseKey); const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; const itemDetails = this.mergeOrderItemDetails(itemRows); // includeSku 精确过滤(页内应用,total 为粗分组数量) if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { continue; } const itemSummary = this.buildItemSummary(itemDetails); const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); if (!itemSummary || !itemSnapshotKey) { continue; } const firstOrder = g.orders[0] || {}; const itemPartInfo = this.getOrderItemPart(firstOrder); const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, logistics_name: logisticsCode, item_snapshot_key: itemSnapshotKey, }); const store_ids = [ ...new Set( g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) ) ]; let first_order_time = null; let last_order_time = null; let items_total = 0; for (const o of g.orders) { items_total += Number(o.items_total || 0); if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, item_detail_machine_snapshot: itemSnapshotKey, item_snapshot: itemDetails, group: g.orders.length, group_count: g.orders.length, items_total, items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_code: logisticsCode, logistics_name: logisticsDisplayName, distinguish_express: distinguishExpress, ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), first_order_time, last_order_time, status_summary: this.buildStatusSummary(g.orders), }); } const t6 = Date.now(); this.ctx.logger.info('[wave.groupOrderFetchList] 链路耗时', { warehouseId, params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, counts: { rawOrders: rawOrders.length, coarseGroups: coarseGroupMap.size, filteredGroups: total, pageOrderIds: pageOrderIds.length, orderItemRows: orderItemRows.length, pageItems: list.length, }, timing_ms: { getModel: t1 - t0, queryOrders: t2 - t1, coarseGrouping: t3 - t2, pagination: t4 - t3, queryItems: t5 - t4, buildList: t6 - t5, total: t6 - t0, }, }); return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 散单波次可抓取列表。 * * 仅处理待处理订单(排除待审核),且排除已在波次中的订单。 * 与团购抓取共用同一链路,仅排除团购阈值命中的分组。 * * @param {Object} data 请求参数。 * @return {Promise} 抓取列表和分页信息。 */ async singleOrderFetchList(data = {}) { const t0 = Date.now(); const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = this.getWarehouseId(); const model = await this.getOrderModel('pendingOrder', warehouseId); const t1 = Date.now(); const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); const sameOrderQuantityInput = requestData.same_order_quantity; const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); const explicitSameOrderQuantity = hasSameOrderQuantityInput ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) : 0; const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); const sameOrderQuantity = explicitSameOrderQuantity > 0 ? explicitSameOrderQuantity : minGroupOrderFetchQuantity; const shopName = this.normalizeShopName(requestData.shop_name); const includeSku = this.normalizeSkuText(requestData.include_sku); const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false); const stockQuery = String(requestData.stock_query || '').trim(); const { page, pageSize } = this.normalizePagination(requestData); const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, intercept_status: 'none', lock_status: 'none', wave_id: 0, }; if (storeId > 0) { where.store_id = storeId; } if (shopName) { where.shop_nick = { [Op.like]: `%${shopName}%` }; } // stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围 if (stockQuery) { const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); if (stockOrderIds.length > 0) { where.id = { [Op.in]: stockOrderIds }; } else { // 未匹配到任何商品,直接返回空列表 return { list: [], pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false }, }; } } // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, attributes: [ 'id', 'store_id', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name', 'items_hash', 'items', 'items_total', 'items_weight', 'packages_weight', 'post_status', 'pick_status', 'outbound_status', 'create_at', ], raw: true, order: [[ 'id', 'DESC' ]], }); const t2 = Date.now(); // Phase 2: 纯内存粗分组,items_hash 相同即为同组,速度快 // coarseGroupMap: coarseKey -> { orders[] } const coarseGroupMap = new Map(); for (const order of rawOrders) { const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); if (!coarseKey) { continue; } if (!coarseGroupMap.has(coarseKey)) { coarseGroupMap.set(coarseKey, { orders: [] }); } coarseGroupMap.get(coarseKey).orders.push(order); } // 过滤团购阈值(排除团购分组)、排序 let groupEntries = Array.from(coarseGroupMap.entries()); groupEntries = groupEntries.filter(([ , g ]) => g.orders.length < sameOrderQuantity); groupEntries.sort(([ keyA, gA ], [ keyB, gB ]) => { if (gB.orders.length !== gA.orders.length) { return gB.orders.length - gA.orders.length; } return keyA.localeCompare(keyB); }); const total = groupEntries.length; const t3 = Date.now(); // Phase 3: 分页分组,只取当前页 const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; const pageStart = (page - 1) * pageSize; const pageGroupEntries = groupEntries.slice(pageStart, pageStart + pageSize); // 收集当前页每组的代表订单 id(同组 items_hash 相同,只需一条快照即可) const representativeIdPerGroup = new Map(); // coarseKey -> representativeOrderId for (const [ coarseKey, g ] of pageGroupEntries) { const repOrder = g.orders.find(o => Number(o.id) > 0); if (repOrder) { representativeIdPerGroup.set(coarseKey, Number(repOrder.id)); } } const pageOrderIds = Array.from(representativeIdPerGroup.values()); const t4 = Date.now(); // Phase 4: 仅查每组代表订单的明细(每页 20 条左右,大幅降低 IN 数量) const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); const orderItemRows = pageOrderIds.length > 0 ? await orderItemsModel.findAll({ where: { order_id: { [Op.in]: pageOrderIds } }, attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], raw: true, }) : []; const t5 = Date.now(); // 构建明细索引 const orderItemsMap = new Map(); for (const row of orderItemRows) { const orderId = Number(row && row.order_id); if (!Number.isInteger(orderId) || orderId <= 0) { continue; } if (!orderItemsMap.has(orderId)) { orderItemsMap.set(orderId, []); } orderItemsMap.get(orderId).push(row); } // Phase 5: 构建当前页响应,每组取一个代表订单的 item_snapshot 作为展示快照 const list = []; for (const [ coarseKey, g ] of pageGroupEntries) { // 同粗分组内 items_hash 相同,取该组的代表订单明细作为展示快照 const representativeId = representativeIdPerGroup.get(coarseKey); const itemRows = representativeId ? (orderItemsMap.get(representativeId) || []) : []; const itemDetails = this.mergeOrderItemDetails(itemRows); // includeSku 精确过滤(页内应用,total 为粗分组数量) if (!this.orderMatchesIncludeSku(itemDetails, includeSku)) { continue; } const itemSummary = this.buildItemSummary(itemDetails); const itemSnapshotKey = this.buildItemSnapshotKey(itemDetails); if (!itemSummary || !itemSnapshotKey) { continue; } const firstOrder = g.orders[0] || {}; const itemPartInfo = this.getOrderItemPart(firstOrder); const logisticsCode = String(firstOrder.sys_logistics_code || '').trim(); const logisticsNameFromOrder = String(firstOrder.sys_logistics_name || '').trim(); const logisticsDisplayName = logisticsNameFromOrder || logisticsCode; const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, logistics_name: logisticsCode, item_snapshot_key: itemSnapshotKey, }); const store_ids = [ ...new Set( g.orders.map(o => Number(o.store_id || 0)).filter(id => id > 0) ) ]; let first_order_time = null; let last_order_time = null; let items_total = 0; for (const o of g.orders) { items_total += Number(o.items_total || 0); if (!first_order_time || o.create_at < first_order_time) first_order_time = o.create_at; if (!last_order_time || o.create_at > last_order_time) last_order_time = o.create_at; } list.push({ item_detail: itemSummary, item_detail_machine: itemDetailMachine, item_detail_machine_snapshot: itemSnapshotKey, item_snapshot: itemDetails, group: g.orders.length, group_count: g.orders.length, items_total, items_weight: firstOrder.items_weight != null ? Number(firstOrder.items_weight) : null, packages_weight: firstOrder.packages_weight != null ? Number(firstOrder.packages_weight) : null, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_code: logisticsCode, logistics_name: logisticsDisplayName, distinguish_express: distinguishExpress, ...(returnOrderIds ? { order_ids: g.orders.map(o => Number(o.id)) } : {}), first_order_time, last_order_time, status_summary: this.buildStatusSummary(g.orders), }); } const t6 = Date.now(); this.ctx.logger.info('[wave.singleOrderFetchList] 链路耗时', { warehouseId, params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, includeSku: includeSku || null }, counts: { rawOrders: rawOrders.length, coarseGroups: coarseGroupMap.size, filteredGroups: total, pageOrderIds: pageOrderIds.length, orderItemRows: orderItemRows.length, pageItems: list.length, }, timing_ms: { getModel: t1 - t0, queryOrders: t2 - t1, coarseGrouping: t3 - t2, pagination: t4 - t3, queryItems: t5 - t4, buildList: t6 - t5, total: t6 - t0, }, }); return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 团购可抓取订单数统计。 * * 口径与 groupOrderFetchList 完全一致(同一候选 where、同一 items_hash 粗分组、 * 同一团购阈值 same_order_quantity 过滤),但**不分页、不查订单明细**, * 仅返回达到团购阈值分组的数量与组内订单数合计,供前端展示「可抓取订单数」等轻量统计。 * * 差异说明:groupOrderFetchList 的 pagination.total 是**分组数**(每组订单数在 group_count 内), * 本方法 order_count 是**订单数合计**,两者口径不同;include_sku 为页内过滤,本方法不参与统计。 * * @param {Object} [data={}] 请求参数。 * @param {boolean} [data.distinguish_express=false] 是否区分快递(影响分组粒度)。 * @param {number|string} [data.store_id] 货主ID(作为筛选条件)。 * @param {number|string} [data.same_order_quantity] 最小同组订单数量阈值(>=);未传时取仓库配置 min_group_order_fetch_quantity(默认 13)。 * @param {string} [data.shop_name] 店铺名称(模糊匹配)。 * @param {string} [data.stock_query] 商品模糊筛选(stock_warehouse / stock_barcodes → order_items)。 * @return {Promise} 统一返回结构,data 含 group_count / order_count / same_order_quantity / raw_order_count / warehouse_id / distinguish_express。 */ async fetchableOrderCount(data = {}) { const t0 = Date.now(); const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { return this.fail('未识别到当前仓库上下文', {}, 400); } const model = await this.getOrderModel('pendingOrder', warehouseId); const t1 = Date.now(); const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false); const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0); const sameOrderQuantityInput = requestData.same_order_quantity; const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === ''); const explicitSameOrderQuantity = hasSameOrderQuantityInput ? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0) : 0; const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId); const sameOrderQuantity = explicitSameOrderQuantity > 0 ? explicitSameOrderQuantity : minGroupOrderFetchQuantity; const shopName = this.normalizeShopName(requestData.shop_name); const stockQuery = String(requestData.stock_query || '').trim(); const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, intercept_status: 'none', lock_status: 'none', wave_id: 0, }; if (storeId > 0) { where.store_id = storeId; } if (shopName) { where.shop_nick = { [Op.like]: `%${shopName}%` }; } if (stockQuery) { const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId); if (stockOrderIds.length <= 0) { return this.success('ok', { group_count: 0, order_count: 0, same_order_quantity: sameOrderQuantity, raw_order_count: 0, warehouse_id: warehouseId, distinguish_express: distinguishExpress, }); } where.id = { [Op.in]: stockOrderIds }; } // 仅取分组基准字段,不取明细(与 groupOrderFetchList Phase 1 同表同 where) const rawOrders = await model.findAll({ where, attributes: [ 'id', 'items_hash', 'items', 'sys_logistics_code' ], raw: true, }); const t2 = Date.now(); // 纯内存粗分组:items_hash(缺省回落 items)相同即为同组,distinguish_express 时再叠加快递编码 const coarseGroupSizeMap = new Map(); for (const order of rawOrders) { const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress); if (!coarseKey) { continue; } coarseGroupSizeMap.set(coarseKey, Number(coarseGroupSizeMap.get(coarseKey) || 0) + 1); } // 团购阈值过滤:仅统计同组订单数 >= sameOrderQuantity 的分组 let groupCount = 0; let orderCount = 0; for (const groupSize of coarseGroupSizeMap.values()) { if (groupSize < sameOrderQuantity) { continue; } groupCount += 1; orderCount += groupSize; } const t3 = Date.now(); this.ctx.logger.info('[wave.fetchableOrderCount] 链路耗时', { warehouseId, params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, stockQuery: stockQuery || null }, counts: { rawOrders: rawOrders.length, coarseGroups: coarseGroupSizeMap.size, fetchableGroups: groupCount, fetchableOrders: orderCount, }, timing_ms: { getModel: t1 - t0, queryOrders: t2 - t1, counting: t3 - t2, total: t3 - t0, }, }); return this.success('ok', { group_count: groupCount, order_count: orderCount, same_order_quantity: sameOrderQuantity, raw_order_count: rawOrders.length, warehouse_id: warehouseId, distinguish_express: distinguishExpress, }); } /** * 查询当前仓库波次策略列表。 * * 仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 * * @param {Object} [data={}] 请求参数。 * @param {Object} [data.pagination] 分页参数。 * @return {Promise} 波次策略列表及分页信息。 */ async waveStrategyList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; let normalizedStrategyType; if (rawType !== undefined && rawType !== null && `${rawType}` !== '') { normalizedStrategyType = Number(rawType); if (![ 1, 2 ].includes(normalizedStrategyType)) { throw new Error('strategy_type 仅支持 1(散单) 或 2(团购)'); } } const calculateNextFetchOrderCount = Number( requestData.calculate_next_fetch_order_count ?? requestData.calculateNextFetchOrderCount ?? 0 ) === 1; const debugEnabled = Number(requestData.debug ?? 0) === 1; const { page, pageSize } = this.normalizePagination(requestData); const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const strategyModel = this.getWaveStrategyModel(); if (!strategyModel || typeof strategyModel.findAndCountAll !== 'function') { throw new Error('波次策略模型不可用'); } const offset = (page - 1) * pageSize; const where = { warehouse_id: contextWarehouseId, }; if (normalizedStrategyType !== undefined) { where.strategy_type = normalizedStrategyType; } const queryResult = await strategyModel.findAndCountAll({ where, order: [ [ 'status', 'DESC' ], [ 'id', 'DESC' ], ], offset, limit: pageSize, raw: true, }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( contextWarehouseId, list ); const nextFetchOrderCountMap = calculateNextFetchOrderCount ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) : new Map(); const debugFetchOrderListMap = debugEnabled ? await this.getWaveStrategyDebugFetchOrderListMap(contextWarehouseId, list) : new Map(); const mergedList = list.map(item => { const strategyId = Number(item && item.id || 0); const debugRow = debugEnabled ? (debugFetchOrderListMap.get(strategyId) || null) : null; return { ...item, matched_order_count_filtered: Number( matchedOrderCountMap.get(strategyId) || 0 ), next_fetch_order_count: calculateNextFetchOrderCount ? Number(nextFetchOrderCountMap.get(strategyId) || 0) : 0, ...(debugEnabled && debugRow ? { next_fetch_order_list: debugRow, } : {}), }; }); const total = Number(queryResult && queryResult.count || 0); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; // 统计本次查询条件下全部策略命中的去重订单总数(info.order_count); // 与行级 matched_order_count_filtered 同口径,仅在该仓库存在策略时执行, // 统计失败时安全降级为 0,不影响列表主流程。 let matchedOrderCountTotal = 0; if (total > 0) { try { matchedOrderCountTotal = await this.getWaveStrategyMatchedOrderCountTotal( contextWarehouseId, { strategyType: normalizedStrategyType } ); } catch (error) { this.ctx.logger.warn('[wave.waveStrategyList] 统计全部命中订单总数失败,降级为 0', { warehouse_id: contextWarehouseId, strategy_type: normalizedStrategyType, error: error && error.message ? error.message : `${error}`, }); } } return this.success('ok', { list: mergedList, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, info: { order_count: matchedOrderCountTotal, }, }); } /** * 批量预演当前页策略“下一个抓取订单数”。 * * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 * * @param {number|string} warehouseId 仓库ID。 * @param {Array} [strategyRows=[]] 策略行数组。 * @return {Promise>} strategy_id 到预演订单数映射。 */ async getWaveStrategyNextFetchOrderCountMap(warehouseId, strategyRows = []) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const rows = Array.isArray(strategyRows) ? strategyRows : []; const countMap = new Map(); await Promise.all(rows.map(async row => { const strategyId = Number(row && row.id || 0); if (!Number.isInteger(strategyId) || strategyId <= 0) { return; } try { const nextFetchOrderCount = await this.previewWaveStrategyNextFetchOrderCount({ warehouseId: normalizedWarehouseId, strategyRow: row, }); countMap.set(strategyId, Number(nextFetchOrderCount || 0)); } catch (error) { this.ctx.logger.warn('[wave.getWaveStrategyNextFetchOrderCountMap] 预演策略抓取数量失败,降级为 0', { warehouse_id: normalizedWarehouseId, strategy_id: strategyId, error: error && error.message ? error.message : `${error}`, }); countMap.set(strategyId, 0); } })); return countMap; } /** * 调试:按策略返回候选订单明细列表(含结构、快递、货主等指标)。 * * @param {number|string} warehouseId 仓库ID。 * @param {Array} [strategyRows=[]] 策略行数组。 * @return {Promise>>} strategy_id 到候选订单明细列表的映射。 */ async getWaveStrategyDebugFetchOrderListMap(warehouseId, strategyRows = []) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const rows = Array.isArray(strategyRows) ? strategyRows : []; const orderListMap = new Map(); const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); await Promise.all(rows.map(async row => { const strategyId = Number(row && row.id || 0); if (!Number.isInteger(strategyId) || strategyId <= 0) { return; } try { const candidateRows = await this.ctx.model.query(` SELECT o.id, o.items_hash, o.items, o.logistics_name, o.logistics_code, o.sys_logistics_code, o.store_id, o.items_count, o.items_total, o.wave_id, o.step, o.status, o.outbound_status, o.post_status, o.storage_status, o.print_status FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id AND o.warehouse_id = :warehouseId AND o.wave_id = 0 AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' AND o.intercept_status = 'none' AND o.lock_status = 'none' WHERE m.warehouse_id = :warehouseId AND m.strategy_id = :strategyId ORDER BY o.id ASC LIMIT 500 `, { replacements: { warehouseId: normalizedWarehouseId, strategyId, }, type: this.ctx.model.QueryTypes.SELECT, }); const normalizedRows = Array.isArray(candidateRows) ? candidateRows : []; const requireSameExpress = Number(row && row.require_same_express || 0) === 1; const filteredRows = requireSameExpress && normalizedRows.length > 0 ? (() => { const expressGroupMap = new Map(); for (const order of normalizedRows) { const expressKey = this.getWaveStrategyQuickScanExpressKey({ sys_logistics_code: order.sys_logistics_code, logistics_code: order.logistics_code, logistics_name: order.logistics_name, }); const key = expressKey || '__empty__'; if (!expressGroupMap.has(key)) { expressGroupMap.set(key, []); } expressGroupMap.get(key).push(order); } const groups = Array.from(expressGroupMap.values()) .sort((a, b) => b.length - a.length); return groups.length > 0 ? groups[0] : normalizedRows; })() : normalizedRows; const detailList = filteredRows.map(order => ({ order_id: Number(order && order.id || 0), structure: { items_hash: String(order && order.items_hash || '').trim(), items: String(order && order.items || '').trim(), }, express: { sys_logistics_code: String(order && order.sys_logistics_code || '').trim(), logistics_code: String(order && order.logistics_code || '').trim(), logistics_name: String(order && order.logistics_name || '').trim(), }, store_id: String(order && order.store_id || '').trim(), items_count: Number(order && order.items_count || 0), items_total: Number(order && order.items_total || 0), wave_id: Number(order && order.wave_id || 0), status: String(order && order.status || '').trim(), outbound_status: String(order && order.outbound_status || '').trim(), post_status: String(order && order.post_status || '').trim(), storage_status: String(order && order.storage_status || '').trim(), })); orderListMap.set(strategyId, { candidate_count: detailList.length, candidate_total: normalizedRows.length, candidates: detailList, }); } catch (error) { this.ctx.logger.warn('[wave.getWaveStrategyDebugFetchOrderListMap] 调试查询失败,降级为空', { warehouse_id: normalizedWarehouseId, strategy_id: strategyId, error: error && error.message ? error.message : `${error}`, }); orderListMap.set(strategyId, { candidate_count: 0, candidates: [], error: error && error.message || `${error}` }); } })); return orderListMap; } /** * 预演单个策略“下一个抓取订单数”。 * * 口径复用自动分流逻辑,但仅计算最终会选中的订单数量,不执行写操作。 * * @param {Object} [params={}] 预演参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Object} params.strategyRow 策略行。 * @return {Promise} 预演可抓取订单数。 */ async previewWaveStrategyNextFetchOrderCount(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; const strategyId = Number(strategyRow.id || 0); if (!Number.isInteger(strategyId) || strategyId <= 0) { return 0; } const strategyType = Number(strategyRow.strategy_type || 0); if (![ 1, 2 ].includes(strategyType)) { return 0; } const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ warehouseId, strategyId, minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), }); if (candidateRows.length <= 0) { return 0; } let groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); if (groupedRows.length <= 0) { return 0; } if (Number(strategyRow.require_same_express || 0) === 1) { const filteredRows = this.filterCandidateOrdersByRequireSameExpress(candidateRows); groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(filteredRows); if (groupedRows.length <= 0) { return 0; } } if (strategyType === 2) { const groupLimitRaw = Number(strategyRow.group_batch_max_orders || 0); const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; const selectedGroups = groupedRows.slice(0, groupLimit); const selectedOrderIds = [ ...new Set(selectedGroups .flatMap(group => group.order_ids) .map(id => Number(id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; return selectedOrderIds.length; } const pickMode = this.resolveWaveStrategyFetchPickMode({ requestData: {}, strategyRow, }); const mergedOrderIds = [ ...new Set(groupedRows .flatMap(group => group.order_ids) .map(id => Number(id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (mergedOrderIds.length <= 0) { return 0; } let selectedOrderIds = []; if (pickMode === 3) { const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ warehouseId, orderIds: mergedOrderIds, }); const skuLimitRaw = Number(strategyRow.batch_max_skus || 0); const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ orderIds: mergedOrderIds, orderSkuMap: skuMap, skuLimit, }); selectedOrderIds = skuResult.selectedOrderIds; } else if (pickMode === 2 || pickMode === 4) { selectedOrderIds = mergedOrderIds; } else { return 0; } const orderLimitRaw = Number(strategyRow.batch_max_orders || 0); const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; const limitedOrderIds = orderLimit > 0 ? selectedOrderIds.slice(0, orderLimit) : selectedOrderIds; return limitedOrderIds.length; } /** * 按策略统计过滤后命中订单数。 * * 过滤口径与抓取候选 SQL(getWaveStrategyFetchCandidateOrders)保持一致: * 1) 仅统计未在波次订单(wave_id = 0); * 2) 仅统计 step != 0 的订单; * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内; * 当 require_same_express = 1 时按「结构(items_hash) + 快递」分组计数, * 否则仅按结构(items_hash)分组计数。 * * @param {number|string} warehouseId 仓库ID。 * @param {Array} strategyRows 当前页策略行数组(含 require_same_express)。 * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 */ async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyRows = []) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const normalizedStrategies = [ ...new Map((Array.isArray(strategyRows) ? strategyRows : []) .map(item => { const strategyId = Number(item && (item.id ?? item.strategy_id) || 0); if (!Number.isInteger(strategyId) || strategyId <= 0) { return null; } return [ strategyId, { id: strategyId, requireSameExpress: Number(item && item.require_same_express || 0) === 1, }]; }) .filter(Boolean)).values() ]; if (normalizedStrategies.length === 0) { return new Map(); } const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const matchedMap = new Map(); const runCountQuery = async (strategyGroup, requireSameExpress) => { const strategyIds = strategyGroup.map(item => item.id); if (strategyIds.length === 0) { return; } const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; const querySql = ` SELECT m.strategy_id, COUNT(DISTINCT m.order_id) AS matched_order_count_filtered FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id AND o.warehouse_id = :warehouseId AND o.wave_id = 0 AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' AND o.intercept_status = 'none' AND o.lock_status = 'none' INNER JOIN ( SELECT src.items_hash AS structure_key${groupKeyExtra}, COUNT(1) AS same_structure_count FROM ${orderTableName} src WHERE src.warehouse_id = :warehouseId AND src.wave_id = 0 AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' AND src.intercept_status = 'none' AND src.lock_status = 'none' GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} ) same_structure ON same_structure.structure_key = o.items_hash${joinKeyExtra} INNER JOIN wms_wave_strategy s ON s.id = m.strategy_id AND s.warehouse_id = :warehouseId WHERE m.warehouse_id = :warehouseId AND m.strategy_id IN (:strategyIds) AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) GROUP BY m.strategy_id `; const queryRows = await this.ctx.model.query(querySql, { replacements: { warehouseId: normalizedWarehouseId, strategyIds, }, type: this.ctx.model.QueryTypes.SELECT, }); (Array.isArray(queryRows) ? queryRows : []).forEach(row => { const strategyId = Number(row && row.strategy_id || 0); const matchedCount = Number(row && row.matched_order_count_filtered || 0); if (!Number.isInteger(strategyId) || strategyId <= 0) { return; } matchedMap.set(strategyId, matchedCount); }); }; await Promise.all([ runCountQuery(normalizedStrategies.filter(item => item.requireSameExpress), true), runCountQuery(normalizedStrategies.filter(item => !item.requireSameExpress), false), ]); return matchedMap; } /** * 统计仓库内全部策略命中的去重订单总数。 * * 口径与 getWaveStrategyMatchedOrderCountFilteredMap 完全一致(订单池过滤、同结构 * 数量区间、require_same_express 分组方式),但不再按策略分组统计,而是汇总 * 查询条件下(仓库 + 可选策略类型)全部策略命中的订单并去重: * 同一订单命中多个策略仅计一次。 * * @param {number|string} warehouseId 仓库ID。 * @param {Object} [options={}] 统计选项。 * @param {number|string|null} [options.strategyType=null] 策略类型过滤(1 散单 / 2 团购),为 null 时不限制。 * @return {Promise} 全部策略命中的去重订单总数。 */ async getWaveStrategyMatchedOrderCountTotal(warehouseId, options = {}) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const normalizedOptions = this.isPlainObject(options) ? options : {}; const strategyTypeRaw = Number(normalizedOptions.strategyType); const strategyType = Number.isInteger(strategyTypeRaw) && [ 1, 2 ].includes(strategyTypeRaw) ? strategyTypeRaw : null; const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const buildMatchedOrderIdSql = requireSameExpress => { const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''; const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; return ` SELECT m.order_id AS order_id FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id AND o.warehouse_id = :warehouseId AND o.wave_id = 0 AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' AND o.intercept_status = 'none' AND o.lock_status = 'none' INNER JOIN ( SELECT src.items_hash AS structure_key${groupKeyExtra}, COUNT(1) AS same_structure_count FROM ${orderTableName} src WHERE src.warehouse_id = :warehouseId AND src.wave_id = 0 AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' AND src.intercept_status = 'none' AND src.lock_status = 'none' GROUP BY src.items_hash${requireSameExpress ? `, ${expressExpr('src')}` : ''} ) same_structure ON same_structure.structure_key = o.items_hash${joinKeyExtra} INNER JOIN wms_wave_strategy s ON s.id = m.strategy_id AND s.warehouse_id = :warehouseId AND COALESCE(s.require_same_express, 0) = ${requireSameExpress ? 1 : 0} AND (:strategyType IS NULL OR s.strategy_type = :strategyType) WHERE m.warehouse_id = :warehouseId AND same_structure.same_structure_count >= COALESCE(NULLIF(s.min_same_structure, 0), 0) AND (s.max_same_structure IS NULL OR s.max_same_structure <= 0 OR same_structure.same_structure_count <= s.max_same_structure) `; }; const countRows = await this.ctx.model.query(` SELECT COUNT(DISTINCT matched.order_id) AS order_count FROM ( ${buildMatchedOrderIdSql(true)} UNION ALL ${buildMatchedOrderIdSql(false)} ) matched `, { replacements: { warehouseId: normalizedWarehouseId, strategyType, }, type: this.ctx.model.QueryTypes.SELECT, }); const totalCount = Number( (Array.isArray(countRows) && countRows[0] && countRows[0].order_count) || 0 ); return Number.isInteger(totalCount) && totalCount >= 0 ? totalCount : 0; } /** * 新增波次策略。 * * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 * * @param {Object} [data={}] 请求参数。 * @return {Promise} 新增结果。 */ async waveStrategyCreate(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const strategyModel = this.getWaveStrategyModel(); if (!strategyModel || typeof strategyModel.create !== 'function') { throw new Error('波次策略模型不可用'); } const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { warehouseId, mode: 'create', }); const operator = this.getOrderLogOperator(); const transaction = await this.ctx.model.transaction(); let created; try { created = await strategyModel.create({ ...payload, warehouse_id: warehouseId, creator_name: String(operator && operator.name || 'system').trim() || 'system', }, { transaction, }); await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); await transaction.commit(); } catch (error) { await transaction.rollback(); throw error; } const createdData = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; return this.success('ok', { data: createdData, code: 200 }); } /** * 修改波次策略。 * * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 * * @param {Object} [data={}] 请求参数。 * @return {Promise} 修改结果。 */ async waveStrategyUpdate(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const strategyModel = this.getWaveStrategyModel(); if (!strategyModel || typeof strategyModel.findOne !== 'function' || typeof strategyModel.update !== 'function') { throw new Error('波次策略模型不可用'); } const strategyId = this.normalizeWaveStrategyId(requestData); const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { warehouseId, mode: 'update', }); if (Object.keys(payload).length === 0) { throw new Error('缺少可更新字段'); } const operator = this.getOrderLogOperator(); const transaction = await this.ctx.model.transaction(); let updated; try { const exists = await strategyModel.findOne({ where: { id: strategyId, warehouse_id: warehouseId, }, raw: true, transaction, }); if (!exists) { throw new Error(`波次策略不存在: ${strategyId}`); } await strategyModel.update({ ...payload, creator_name: String(operator && operator.name || 'system').trim() || 'system', update_time: new Date(), }, { where: { id: strategyId, warehouse_id: warehouseId, }, transaction, }); await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); updated = await strategyModel.findOne({ where: { id: strategyId, warehouse_id: warehouseId, }, raw: true, transaction, }); await transaction.commit(); } catch (error) { await transaction.rollback(); throw error; } return this.success('ok', { data: updated || null, code: 200 }); } /** * 递增仓库波次策略版本并失效相关缓存。 * * 数据更新在事务内执行;当传入事务时,缓存失效动作会在事务提交后执行。 * * @param {number|string} warehouseId 仓库ID。 * @param {Object} [options={}] 处理选项。 * @param {Object} [options.transaction] Sequelize 事务对象。 * @return {Promise} 自增后的版本号。 */ async bumpWaveStrategyVersionAndInvalidateCache(warehouseId, options = {}) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const { transaction } = this.isPlainObject(options) ? options : {}; const settingWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.setting && this.ctx.service.systems.setting.warehouse; const modelContainer = this.ctx.model || this.app.model || {}; const storeModel = modelContainer.Store; if (!storeModel || typeof storeModel.findByPk !== 'function') { throw new Error('Store model 不可用'); } const storeQueryOptions = { attributes: [ 'id', 'subject_config' ], }; if (transaction) { storeQueryOptions.transaction = transaction; if (transaction.LOCK && transaction.LOCK.UPDATE) { storeQueryOptions.lock = transaction.LOCK.UPDATE; } } const store = await storeModel.findByPk(normalizedWarehouseId, storeQueryOptions); if (!store) { throw new Error(`仓库不存在: ${normalizedWarehouseId}`); } const currentSubjectConfig = store.subject_config && typeof store.subject_config === 'object' && !Array.isArray(store.subject_config) ? { ...store.subject_config } : {}; const normalizedSubjectConfig = settingWarehouseService && typeof settingWarehouseService.normalizeSubjectConfigInternalFields === 'function' ? settingWarehouseService.normalizeSubjectConfigInternalFields(currentSubjectConfig) : currentSubjectConfig; const currentVersion = settingWarehouseService && typeof settingWarehouseService.normalizeWaveStrategyVersion === 'function' ? settingWarehouseService.normalizeWaveStrategyVersion(normalizedSubjectConfig.wave_strategy_version, { useDefaultWhenEmpty: true }) : Number(normalizedSubjectConfig.wave_strategy_version || 1); if (!Number.isSafeInteger(currentVersion) || currentVersion < 0) { throw new Error('subject_config.wave_strategy_version 必须是非负整数'); } if (currentVersion >= Number.MAX_SAFE_INTEGER) { throw new Error('subject_config.wave_strategy_version 超出安全整数范围'); } const nextVersion = currentVersion + 1; normalizedSubjectConfig.wave_strategy_version = nextVersion; const subjectConfigForUpdate = typeof storeModel.normalizeSubjectConfig === 'function' ? storeModel.normalizeSubjectConfig(normalizedSubjectConfig) : normalizedSubjectConfig; await store.update({ subject_config: subjectConfigForUpdate, }, { ...(transaction ? { transaction } : {}), }); const invalidateCache = async () => { if (settingWarehouseService && typeof settingWarehouseService.clearWarehouseSettingCache === 'function') { await settingWarehouseService.clearWarehouseSettingCache(normalizedWarehouseId); } const deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; const subjectConfigCacheKey = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfigCacheKey === 'function' ? deliveryOrderService.getStoreSubjectConfigCacheKey(normalizedWarehouseId) : `delivery_order:store:${normalizedWarehouseId}:subject_config`; if (subjectConfigCacheKey) { if (this.app && typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(subjectConfigCacheKey); } else if (this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(subjectConfigCacheKey, null, 0); } } const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; if (this.app && typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(strategyCacheKey); } else if (this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(strategyCacheKey, null, 0); } setImmediate(() => { this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId) .then(scanPayload => { this.ctx.logger.info('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描成功', { warehouseId: normalizedWarehouseId, taskId: String(scanPayload && scanPayload.task_id || '').trim(), state: String(scanPayload && scanPayload.state || '').trim(), }); }) .catch(error => { this.ctx.logger.warn('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描失败,不影响主流程', { warehouseId: normalizedWarehouseId, error: error && error.message ? error.message : `${error}`, }); }); }); }; if (transaction && typeof transaction.afterCommit === 'function') { transaction.afterCommit(async () => { await invalidateCache(); }); } else { await invalidateCache(); } return nextVersion; } /** * 获取波次策略模型。 * * @return {Object|null} 模型对象。 */ getWaveStrategyModel() { return this.ctx.model && ( this.ctx.model.wms_wave_strategy || this.ctx.model.PickingStrategy || this.ctx.model.WmsWaveStrategy ); } /** * 归一化波次策略主键。 * * @param {Object} data 请求参数。 * @return {number} 策略主键。 */ normalizeWaveStrategyId(data = {}) { const rawId = data && (data.id ?? data.strategy_id ?? data.strategyId); return this.normalizeRequiredPositiveInteger(rawId, 'id'); } /** * 归一化波次策略新增/修改入参并执行统一校验。 * * @param {Object} data 请求参数。 * @param {Object} options 处理选项。 * @param {number} options.warehouseId 当前仓库ID。 * @param {string} options.mode 模式:create/update。 * @return {Promise} 可直接写库的载荷。 */ async normalizeWaveStrategyUpsertPayload(data = {}, options = {}) { const requestData = this.isPlainObject(data) ? data : {}; const mode = String(options && options.mode || '').trim().toLowerCase(); const warehouseId = Number(options && options.warehouseId || 0); const payload = {}; if (mode === 'create') { const strategyName = String(requestData.strategy_name || '').trim(); if (!strategyName) { throw new Error('strategy_name 参数不能为空'); } payload.strategy_name = strategyName; if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); payload.wave_prefix = wavePrefix || null; } payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); } else if (payload.strategy_type === 2) { payload.batch_mode = 0; } else { throw new Error('batch_mode 参数不能为空'); } } else { if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_name')) { const strategyName = String(requestData.strategy_name || '').trim(); if (!strategyName) { throw new Error('strategy_name 参数不能为空'); } payload.strategy_name = strategyName; } if (Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { const wavePrefix = String(requestData.wave_prefix || '').trim().slice(0, 5); payload.wave_prefix = wavePrefix || null; } if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_type')) { payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); } if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); } else if (payload.strategy_type === 2) { payload.batch_mode = 0; } } if (Object.prototype.hasOwnProperty.call(requestData, 'status')) { const normalizedStatus = Number(requestData.status); if (![ 0, 1 ].includes(normalizedStatus)) { throw new Error('status 参数不合法,仅支持 0 或 1'); } payload.status = normalizedStatus; } this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_sku'); this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_sku'); this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_qty'); this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_qty'); this.patchWaveStrategyIntegerField(payload, requestData, 'min_same_structure'); this.patchWaveStrategyIntegerField(payload, requestData, 'max_same_structure'); if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_orders')) { const rawBatchMaxOrders = requestData.batch_max_orders; if (rawBatchMaxOrders === null || rawBatchMaxOrders === '') { payload.batch_max_orders = null; } else { payload.batch_max_orders = this.normalizePositiveInteger(rawBatchMaxOrders, 'batch_max_orders'); } } const resolvedStrategyType = Object.prototype.hasOwnProperty.call(payload, 'strategy_type') ? payload.strategy_type : Object.prototype.hasOwnProperty.call(requestData, 'strategy_type') ? this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type') : null; if (resolvedStrategyType === 2) { payload.batch_max_orders = 0; } const resolvedBatchMode = Object.prototype.hasOwnProperty.call(payload, 'batch_mode') ? payload.batch_mode : Object.prototype.hasOwnProperty.call(requestData, 'batch_mode') ? this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode') : null; if (resolvedBatchMode === 2) { if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_skus')) { const rawBatchMaxSkus = requestData.batch_max_skus; if (rawBatchMaxSkus === null || rawBatchMaxSkus === '') { payload.batch_max_skus = null; } else { payload.batch_max_skus = this.normalizePositiveInteger(rawBatchMaxSkus, 'batch_max_skus'); } } } else { payload.batch_max_skus = 0; } if (resolvedStrategyType !== null && resolvedStrategyType !== 2) { payload.group_batch_max_orders = 0; } else if (resolvedStrategyType === 2) { if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { payload.group_batch_max_orders = null; } else { payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); } } } else if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { payload.group_batch_max_orders = null; } else { payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); } } if (Object.prototype.hasOwnProperty.call(requestData, 'require_same_express')) { payload.require_same_express = this.normalizeBoolean(requestData.require_same_express, false); } if (Object.prototype.hasOwnProperty.call(requestData, 'allow_cross_owner')) { payload.allow_cross_owner = this.normalizeBoolean(requestData.allow_cross_owner, true); } if (Object.prototype.hasOwnProperty.call(requestData, 'description')) { payload.description = String(requestData.description || '').trim(); } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); payload.allowed_provinces = list.length > 0 ? list : null; } else if (mode === 'update') { payload.allowed_provinces = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_platforms')) { const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms, false); payload.allowed_platforms = list.length > 0 ? list : null; } else if (mode === 'update') { payload.allowed_platforms = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_owners')) { const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); if (list.length > 0) { await this.validateWaveStrategyAllowedOwners(list, warehouseId); } payload.allowed_owners = list.length > 0 ? list : null; } else if (mode === 'update') { payload.allowed_owners = null; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_expresses')) { const list = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses, false); if (list.length > 0) { await this.validateWaveStrategyAllowedExpresses(list); } payload.allowed_expresses = list.length > 0 ? list : null; } else if (mode === 'update') { payload.allowed_expresses = null; } await this.applyWaveStrategyMaxSameStructureConstraint(payload, warehouseId); delete payload.warehouse_id; delete payload.creator; delete payload.creator_name; return payload; } /** * 归一化波次策略波次前缀。 * * 规则: * 1. 允许为空字符串(表示回退仓库前缀); * 2. 非空时统一转大写; * 3. 非空时仅允许 A-Z0-9,长度 1-5。 * * @param {*} rawWavePrefix 原始波次前缀入参。 * @return {string} 归一化后的波次前缀。 */ normalizeWaveStrategyWavePrefix(rawWavePrefix) { if (rawWavePrefix === undefined || rawWavePrefix === null) { return ''; } const normalizedWavePrefix = String(rawWavePrefix).trim() .toUpperCase(); if (!normalizedWavePrefix) { return ''; } if (normalizedWavePrefix.length < 1 || normalizedWavePrefix.length > 5) { throw new Error('wave_prefix 非空时长度必须为 1-5 个字符'); } if (!/^[A-Z0-9]+$/.test(normalizedWavePrefix)) { throw new Error('wave_prefix 非空时仅支持 A-Z0-9'); } return normalizedWavePrefix; } /** * 解析策略抓取建波使用的前缀(策略优先,仓库前缀兜底)。 * * @param {Object} params 解析参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {number|string} params.strategyType 策略类型(1-散单,2-团购)。 * @param {Object} [params.strategyRow={}] 策略行。 * @return {Promise<{ wavePrefix: string, source: string }>} 前缀及来源。 */ async resolveWaveStrategyFetchWavePrefix(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const strategyType = Number(params.strategyType || 0); const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; const strategyWavePrefix = this.normalizeWaveStrategyWavePrefix(strategyRow.wave_prefix); if (strategyWavePrefix) { return { wavePrefix: strategyWavePrefix, source: 'strategy', }; } const warehouseWavePrefix = strategyType === 2 ? await this.getGroupWavePrefix(warehouseId) : await this.getSingleFetchByIdsWavePrefix(warehouseId); return { wavePrefix: String(warehouseWavePrefix || '').trim() || (strategyType === 2 ? 'B' : 'A'), source: 'warehouse_fallback', }; } /** * 按字段补丁方式归一化波次策略正整数参数。 * * @param {Object} payload 输出载荷。 * @param {Object} requestData 原始请求。 * @param {string} fieldName 字段名。 */ patchWaveStrategyIntegerField(payload = {}, requestData = {}, fieldName = '') { if (!Object.prototype.hasOwnProperty.call(requestData, fieldName)) { return; } const rawValue = requestData[fieldName]; if (rawValue === null || rawValue === '') { payload[fieldName] = null; return; } payload[fieldName] = this.normalizeRequiredPositiveInteger(rawValue, fieldName); } /** * 校验 allowed_owners 是否在系统可用货主范围内。 * * @param {Array} ownerList 货主列表。 * @param {number} warehouseId 当前仓库ID。 * @return {Promise} 无返回值。 */ async validateWaveStrategyAllowedOwners(ownerList = [], warehouseId = 0) { const normalizedOwners = Array.isArray(ownerList) ? ownerList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) : []; if (normalizedOwners.length === 0) { return; } const availableOwnerSet = await this.getWaveStrategyAvailableOwnerSet(warehouseId); const illegalOwners = normalizedOwners.filter(item => !availableOwnerSet.has(item)); if (illegalOwners.length > 0) { throw new Error(`allowed_owners 存在非法值: ${illegalOwners.join(', ')}`); } } /** * 校验 allowed_expresses 是否在系统可用快递范围内。 * * @param {Array} expressList 快递编码列表。 * @return {Promise} 无返回值。 */ async validateWaveStrategyAllowedExpresses(expressList = []) { const normalizedExpresses = Array.isArray(expressList) ? expressList.map(item => String(item || '').trim()).filter(Boolean) : []; if (normalizedExpresses.length === 0) { return; } const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); const availableLowerSet = new Set([ ...availableExpressSet ].map(s => s.toLowerCase())); const illegalExpresses = normalizedExpresses.filter(item => !availableLowerSet.has(String(item).toLowerCase())); if (illegalExpresses.length > 0) { throw new Error(`allowed_expresses 存在非法值: ${illegalExpresses.join(', ')}`); } } /** * 获取当前仓库可用货主集合。 * * 优先复用 systems.store.loadStores,若不可用则回退查询签约表。 * * @param {number} warehouseId 当前仓库ID。 * @return {Promise>} 货主集合(小写字符串)。 */ async getWaveStrategyAvailableOwnerSet(warehouseId = 0) { const availableSet = new Set(); const storeService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.store; if (storeService && typeof storeService.loadStores === 'function') { const rows = await storeService.loadStores(); for (const row of Array.isArray(rows) ? rows : []) { const ownerId = String(row && (row.value ?? row.store_id) || '').trim().toLowerCase(); if (ownerId) { availableSet.add(ownerId); } } } if (availableSet.size > 0) { return availableSet; } const normalizedWarehouseId = Number(warehouseId || 0); const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function') { return availableSet; } const rows = await storeWarehouseModel.findAll({ attributes: [ 'store_id' ], where: { warehouse_id: normalizedWarehouseId, warehouse_use_status: 1, }, raw: true, }); for (const row of Array.isArray(rows) ? rows : []) { const ownerId = String(row && row.store_id || '').trim().toLowerCase(); if (ownerId) { availableSet.add(ownerId); } } return availableSet; } /** * 获取当前仓库可用快递编码集合。 * * 优先复用 systems.express.getExpressList,若不可用则回退系统快递表。 * * @return {Promise>} 快递编码集合(小写字符串)。 */ async getWaveStrategyAvailableExpressSet() { const availableSet = new Set(); const expressService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.express; if (expressService && typeof expressService.getExpressList === 'function') { const rows = await expressService.getExpressList(); for (const row of Array.isArray(rows) ? rows : []) { const code = String(row && (row.code || row.value) || '').trim().toLowerCase(); if (code) { availableSet.add(code); } } } if (availableSet.size > 0) { return availableSet; } const expressModel = this.ctx.model && this.ctx.model.Express; if (!expressModel || typeof expressModel.findAll !== 'function') { return availableSet; } const rows = await expressModel.findAll({ attributes: [ 'code' ], order: [[ 'code', 'ASC' ]], raw: true, }); for (const row of Array.isArray(rows) ? rows : []) { const code = String(row && row.code || '').trim().toLowerCase(); if (code) { availableSet.add(code); } } return availableSet; } /** * 按仓库最小团购抓取量约束 max_same_structure。 * * 当 min_group_order_fetch_quantity 为有效正整数且 * max_same_structure >= min_group_order_fetch_quantity 时, * 自动下调为 min_group_order_fetch_quantity - 1,且最小保持为 1。 * * @param {Object} payload 目标写库载荷。 * @param {number} warehouseId 当前仓库ID。 * @return {Promise} 无返回值。 */ async applyWaveStrategyMaxSameStructureConstraint(payload = {}, warehouseId = 0) { if (!Object.prototype.hasOwnProperty.call(payload, 'max_same_structure')) { return; } const maxSameStructure = payload.max_same_structure; if (maxSameStructure === null || maxSameStructure === undefined || maxSameStructure === '') { return; } const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return; } const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); const minGroupOrderFetchQuantity = Number( this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') ); if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { return; } const normalizedMaxSameStructure = Number(maxSameStructure); if (!Number.isInteger(normalizedMaxSameStructure) || normalizedMaxSameStructure <= 0) { throw new Error('max_same_structure 参数必须为正整数'); } if (normalizedMaxSameStructure >= minGroupOrderFetchQuantity) { payload.max_same_structure = Math.max(minGroupOrderFetchQuantity - 1, 1); } } /** * 校验并标准化兜底订单列表 where 白名单字段。 * * 仅允许与波次策略过滤直接相关的字段;对兼容别名做统一映射, * 例如 delivery_no -> delivery_order_code、tracking_no -> express_numbers。 * * @param {Object} whereData 原始 where 入参。 * @return {Object} 标准化后的 where 条件。 */ normalizeWaveStrategyFallbackOrderListWhere(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; const whereKeys = Object.keys(normalizedWhere); if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); } const allowedFields = Object.keys(WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP); const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); if (invalidFields.length > 0) { throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); } const hasStoreName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'store_name'); const hasOwnerName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'owner_name'); if (hasStoreName && hasOwnerName) { throw new Error('store_name 与 owner_name 不能同时传入,请保留一个货主名称字段'); } const rangeOperatorMap = Object.freeze({ items_count_min: 'ge', items_count_max: 'le', items_total_min: 'ge', items_total_max: 'le', }); const mappedWhere = {}; for (const field of allowedFields) { if (!Object.prototype.hasOwnProperty.call(normalizedWhere, field)) { continue; } if (Object.prototype.hasOwnProperty.call(rangeOperatorMap, field)) { const rawValue = normalizedWhere[field]; const value = this.isPlainObject(rawValue) && Object.prototype.hasOwnProperty.call(rawValue, 'value') ? rawValue.value : rawValue; mappedWhere[field] = { operator: rangeOperatorMap[field], field: WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field], value, }; continue; } mappedWhere[WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field]] = normalizedWhere[field]; } return mappedWhere; } /** * 解析兜底订单列表中的快递号展示值。 * * @param {Object} orderRow 订单行。 * @return {string|null} 快递号。 */ resolveWaveStrategyFallbackTrackingNo(orderRow = {}) { if (!this.isPlainObject(orderRow)) { return null; } const directTrackingNo = String(orderRow.tracking_no || '').trim(); if (directTrackingNo) { return directTrackingNo; } const expressNumbers = Array.isArray(orderRow.express_numbers) ? orderRow.express_numbers : Array.isArray(orderRow.waybill_codes) ? orderRow.waybill_codes : []; const normalizedExpressNumbers = expressNumbers .map(item => String(item || '').trim()) .filter(Boolean); if (normalizedExpressNumbers.length > 0) { return normalizedExpressNumbers[0]; } const expressNumbersText = String(orderRow.express_numbers || '').trim(); if (expressNumbersText) { return expressNumbersText.split(',').map(item => item.trim()).filter(Boolean)[0] || null; } return null; } /** * 解析兜底订单列表中的货主名称展示值。 * * @param {Object} orderRow 订单行。 * @return {string|null} 货主名称。 */ resolveWaveStrategyFallbackStoreName(orderRow = {}) { if (!this.isPlainObject(orderRow)) { return null; } const candidateList = [ orderRow.store_name, orderRow.owner_name, orderRow.shop_nick, orderRow.seller_nick, ]; for (const candidate of candidateList) { const normalizedValue = String(candidate || '').trim(); if (normalizedValue) { return normalizedValue; } } return null; } /** * 解析兜底订单列表中的系统快递名称。 * * @param {Object} orderRow 订单行。 * @return {string|null} 系统快递名称。 */ resolveWaveStrategyFallbackSysLogisticsName(orderRow = {}) { if (!this.isPlainObject(orderRow)) { return null; } const candidateList = [ orderRow.sys_logistics_name, orderRow.logistics_name ]; for (const candidate of candidateList) { const normalizedValue = String(candidate || '').trim(); if (normalizedValue) { return normalizedValue; } } return null; } /** * 构建兜底订单列表单行输出,仅保留波次策略相关字段。 * * @param {Object} orderRow 原始订单行。 * @param {string} itemSnapshot 商品快照文本。 * @return {Object} 裁剪后的订单行。 */ buildWaveStrategyFallbackOrderListItem(orderRow = {}, itemSnapshot = '') { const normalizedOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; // normalizeOrderListItem 已将 lock_status 归一化为 Y/N(none→N,其余→Y), // 这里兼容归一化值(Y/N)与原始值(none/warehouse/store),避免把 N 误判为已锁定。 const lockStatus = String(normalizedOrderRow.lock_status || '').trim(); const isLocked = lockStatus === 'Y' || (lockStatus !== '' && lockStatus !== 'N' && lockStatus !== 'none'); return { id: normalizedOrderRow.id ?? null, delivery_no: normalizedOrderRow.delivery_no ?? normalizedOrderRow.delivery_order_code ?? null, tracking_no: this.resolveWaveStrategyFallbackTrackingNo(normalizedOrderRow), items_count: normalizedOrderRow.items_count ?? null, items_total: normalizedOrderRow.items_total ?? null, items_weight: normalizedOrderRow.items_weight != null ? Number(normalizedOrderRow.items_weight) : null, packages_weight: normalizedOrderRow.packages_weight != null ? Number(normalizedOrderRow.packages_weight) : null, weight_type: this.formatWeightTypeLabel(normalizedOrderRow.weight_type), sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow), store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow), province: normalizedOrderRow.province ?? null, sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, item_snapshot: String(itemSnapshot || ''), wave_index: Number(normalizedOrderRow.wave_index || 0), excluded_reason: isLocked ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.locked : normalizedOrderRow.intercept_status !== 'none' ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.intercepted : normalizedOrderRow.print_status === 'fin' ? WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.printed : WAVE_STRATEGY_FALLBACK_EXCLUDED_REASON_LABELS.no_match, }; } /** * 查询兜底不符合波次策略的订单列表(含已完全打印被排除的订单)。 * * 查询条件:step != 0 且 wave_id = 0,且满足以下任一条件: * - wave_scan_result = 2(未匹配任何波次策略) * - print_status = 'fin'(已完全打印,被策略抓取阶段排除) * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 * * @param {Object} data 请求参数。 * @param {Object} data.pagination 分页参数。 * @param {Object} data.where 查询条件。 * @param {Object} data.sort 排序参数。 * @return {Promise} 列表查询结果,每行含 excluded_reason 标记。 */ async waveStrategyFallbackOrderList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { pagination, where, sort } = requestData; const normalizedPagination = this.normalizePagination(pagination || {}); const { page, pageSize } = normalizedPagination; const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); const contextWarehouseId = this.getWarehouseId(); // 构建基础 WHERE(复用框架 where 解析、快递号虚拟筛选等能力) const { where: ctxWhere } = this.prepareWhereContext( { ...requestData, where: normalizedWhere }, { specialFieldMap: { quickWhere: { bucket: 'quick' } } } ); const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere); const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage); const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterStockQuery); let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { specialFieldMap: { quickWhere: { bucket: 'quick' } }, }); // 处理快递号虚拟筛选 if (expressNumbers.length > 0) { const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); } if (buyerMessageHas !== null) { const buyerMessageCondition = this.buildBuyerMessageHasCondition(buyerMessageHas); queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition); } // 处理 stock_query 虚拟筛选 if (stockQuery) { const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'waveStrategyFallbackOrder', contextWarehouseId); queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds); } // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') const { Sequelize } = this.app; queryWhere = { [Sequelize.Op.and]: [ queryWhere, { [Sequelize.Op.or]: [ { wave_scan_result: 2 }, { print_status: 'fin' }, { lock_status: { [Sequelize.Op.ne]: 'none' } }, { intercept_status: { [Sequelize.Op.ne]: 'none' } }, ], }, ], }; // 获取模型并分页查询 const model = await this.getOrderModel('waveStrategyFallbackOrder', contextWarehouseId); const order = this.buildListOrder(sort, 'waveStrategyFallbackOrder'); const offset = (page - 1) * pageSize; const [ total, sourceList ] = await Promise.all([ model.count({ where: queryWhere }), model.findAll({ where: queryWhere, limit: pageSize, offset, order, raw: true, }), ]); const normalizedList = await this.attachOrderWaveIndex( await this.attachOrderExpressNumbers( sourceList.map(item => this.normalizeOrderListItem(item)) ) ); // 回填 item_snapshot const orderIds = normalizedList .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0); const warehouseId = Number(this.getWarehouseId() || 0); const itemSnapshotMap = new Map(); if (orderIds.length > 0 && Number.isInteger(warehouseId) && warehouseId > 0) { try { const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); const hasValidModel = orderItemsModel && typeof orderItemsModel.findAll === 'function'; const hasOpIn = Op && Object.prototype.hasOwnProperty.call(Op, 'in'); if (hasValidModel && hasOpIn) { const orderItemRows = await orderItemsModel.findAll({ where: { order_id: { [Op.in]: orderIds }, }, attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], raw: true, }); const orderItemsMap = new Map(); for (const row of orderItemRows || []) { const orderId = Number(row && row.order_id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { continue; } if (!orderItemsMap.has(orderId)) { orderItemsMap.set(orderId, []); } orderItemsMap.get(orderId).push(row); } for (const orderId of orderIds) { const itemRows = orderItemsMap.get(orderId) || []; const itemDetails = this.mergeOrderItemDetails(itemRows); itemSnapshotMap.set(orderId, this.buildOrderItemSnapshot(itemDetails)); } } } catch (error) { this.ctx.logger && this.ctx.logger.warn && this.ctx.logger.warn('[wave.waveStrategyFallbackOrderList] 回填 item_snapshot 失败,已降级为空字符串', { warehouseId, orderCount: orderIds.length, error: error && error.message ? error.message : `${error}`, }); } } const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; const list = normalizedList.map(item => { const orderId = Number(item && item.id || 0); return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); }); return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 解析波次列表的货主名称映射(store_id → 名称)。 * * 货主名称口径与售后/库存列表一致:合约表 wms_store_warehouse.store_remask * (货主备注名称,store_id+warehouse_id 维度)优先,无合约或备注为空时回退 * wms_store.company_name(公司全称)。 * * @param {Object[]} batchRows 波次行数据(含 order_total/owner_distinct_count/owner_named_count/owner_store_id)。 * @param {number|string} [warehouseId=0] 当前仓库ID。 * @return {Promise>} store_id → 货主名称。 */ async resolveWaveBatchOwnerStoreNameMap(batchRows = [], warehouseId = 0) { const nameMap = new Map(); const ownerStoreIds = []; for (const batch of batchRows) { const orderCount = Number(batch && batch.order_total || 0); const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); const ownerNamedCount = Number(batch && batch.owner_named_count || 0); const ownerStoreId = Number(batch && batch.owner_store_id || 0); if (orderCount > 0 && ownerDistinctCount === 1 && ownerNamedCount === orderCount && ownerStoreId > 0) { ownerStoreIds.push(ownerStoreId); } } const uniqueStoreIds = [ ...new Set(ownerStoreIds) ]; if (uniqueStoreIds.length === 0) { return nameMap; } const normalizedWarehouseId = Number(warehouseId || 0); try { // 1. 合约表货主备注名称(store_id + warehouse_id 维度) const contractMap = new Map(); if (normalizedWarehouseId > 0) { const contractRows = await this.ctx.model.StoreWarehouse.findAll({ where: { store_id: { [Op.in]: uniqueStoreIds }, warehouse_id: normalizedWarehouseId, }, attributes: [ 'store_id', 'store_remask' ], raw: true, }); for (const row of contractRows) { const remask = String(row.store_remask || '').trim(); if (remask) { contractMap.set(Number(row.store_id), remask); } } } // 2. 货主公司全称兜底 const storeRows = await this.ctx.model.Store.findAll({ where: { id: { [Op.in]: uniqueStoreIds } }, attributes: [ 'id', 'company_name' ], raw: true, }); for (const row of storeRows) { const companyName = String(row.company_name || '').trim(); if (companyName) { nameMap.set(Number(row.id), companyName); } } // 3. 备注名称覆盖公司全称 for (const storeId of uniqueStoreIds) { if (contractMap.has(storeId)) { nameMap.set(storeId, contractMap.get(storeId)); } } } catch (error) { this.ctx.logger?.warn?.('resolveWaveBatchOwnerStoreNameMap 解析货主名称失败:', error?.message || error); } return nameMap; } /** * 波次列表查询。 * * 默认查询状态为 0/1 的波次,并附带订单分配状态汇总。 * * @param {Object} data 请求参数。 * @param {Object} data.pagination 分页参数。 * @return {Promise} 波次列表及分页信息。 */ async batchList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { page, pageSize } = this.normalizePagination(requestData, { maxPageSize: BATCH_LIST_MAX_PAGE_SIZE, }); const waveStatusList = [ 0, 1 ]; const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const offset = (page - 1) * pageSize; const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const whereClause = this.buildBatchListWhereClause(requestData.where); const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus); const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus); const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus); const confirmPrintAssignmentFilterClause = this.buildBatchListConfirmPrintAssignmentFilterClause(whereClause.confirmPrintAssignmentStatus); const claimAssignmentFilterClause = this.buildBatchListClaimAssignmentFilterClause(whereClause.claimAssignmentStatus); const reviewAssignmentFilterClause = this.buildBatchListReviewAssignmentFilterClause(whereClause.reviewAssignmentStatus); const syncAssignmentFilterClause = this.buildBatchListSyncAssignmentFilterClause(whereClause.syncAssignmentStatus); const onlyTodo = Number(requestData.only_todo || 0); const baseBatchWhereSql = ` warehouse_id = :warehouseId AND wave_status IN (:waveStatusList) ${whereClause.sql} `; const storeIdFilter = Array.isArray(whereClause.storeIds) ? whereClause.storeIds : []; const storeIdExcludeFilter = storeIdFilter.length > 0 && whereClause.storeIdOperator === 'notin'; const ownerFilterJoinSql = storeIdFilter.length > 0 && !storeIdExcludeFilter ? ` INNER JOIN ( SELECT candidate_wave.wave_id FROM ( SELECT wave_id FROM wms_wave_batch WHERE ${baseBatchWhereSql} ) candidate_wave INNER JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id AND od.store_id IN (:whereStoreIds) GROUP BY candidate_wave.wave_id ) wave_owner_filter ON wave_owner_filter.wave_id = wb.wave_id ` : ''; // store_id 排除语义(ne/notin):排除包含所选货主订单的波次(无货主订单的波次保留) const ownerExcludeFilterSql = storeIdExcludeFilter ? ` AND wb.wave_id NOT IN ( SELECT DISTINCT od.wave_id FROM ${orderTableName} od WHERE od.wave_id IS NOT NULL AND od.store_id IN (:whereStoreIds) )` : ''; const batchListFromSql = ` FROM ( SELECT wave_id, wave_no, wave_type, wave_status, total_orders, processed_orders, distinguish_express, source, logistics_name, item_snapshot_key, warehouse_id, creator, claim_operator, claim_time, create_time, update_time FROM wms_wave_batch WHERE ${baseBatchWhereSql} ) wb LEFT JOIN ( SELECT candidate_wave.wave_id, COUNT(od.wave_id) AS order_total, SUM(CASE WHEN od.storage_status = 'none' THEN 1 ELSE 0 END) AS storage_none_count, SUM(CASE WHEN od.storage_status = 'fin' THEN 1 ELSE 0 END) AS storage_fin_count, SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count, SUM(CASE WHEN od.post_status = 'none' THEN 1 ELSE 0 END) AS post_none_count, SUM(CASE WHEN od.post_status = 'fin' THEN 1 ELSE 0 END) AS post_fin_count, SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count, SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count, SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count, SUM(CASE WHEN od.confirm_print_status = 'none' THEN 1 ELSE 0 END) AS confirm_print_none_count, SUM(CASE WHEN od.confirm_print_status = 'fin' THEN 1 ELSE 0 END) AS confirm_print_fin_count, SUM(CASE WHEN od.recheck_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count, SUM(CASE WHEN od.recheck_status = 'error' THEN 1 ELSE 0 END) AS review_error_count, SUM(CASE WHEN od.recheck_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count, SUM(CASE WHEN od.sync_status = 'fin' THEN 1 ELSE 0 END) AS sync_fin_count, SUM(CASE WHEN od.sync_status = 'error' THEN 1 ELSE 0 END) AS sync_error_count, SUM(CASE WHEN od.sync_status IS NULL OR od.sync_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS sync_none_count, SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count, SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count, SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count, COUNT(DISTINCT NULLIF(od.store_id, 0)) AS owner_distinct_count, MAX(NULLIF(od.store_id, 0)) AS owner_store_id, SUM(CASE WHEN NULLIF(od.store_id, 0) IS NOT NULL THEN 1 ELSE 0 END) AS owner_named_count FROM ( SELECT wave_id FROM wms_wave_batch WHERE ${baseBatchWhereSql} ) candidate_wave LEFT JOIN ${orderTableName} od ON od.wave_id = candidate_wave.wave_id GROUP BY candidate_wave.wave_id ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id ${ownerFilterJoinSql} LEFT JOIN wms_express e ON e.code = wb.logistics_name WHERE 1 = 1 ${ownerExcludeFilterSql} ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} ${confirmPrintAssignmentFilterClause.sql} ${claimAssignmentFilterClause.sql} ${reviewAssignmentFilterClause.sql} ${syncAssignmentFilterClause.sql} ${onlyTodo === 1 ? '\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0' : ''} `; const listSql = ` SELECT wb.wave_id, wb.wave_no, wb.wave_type, wb.wave_status, wb.total_orders, wb.processed_orders, wb.distinguish_express, wb.source, wb.logistics_name AS logistics_code, COALESCE(e.name, wb.logistics_name) AS logistics_name, wb.item_snapshot_key, wb.warehouse_id, wb.creator, wb.claim_operator, wb.claim_time, wb.create_time, wb.update_time, COALESCE(wave_order_stats.order_total, 0) AS order_total, COALESCE(wave_order_stats.storage_none_count, 0) AS storage_none_count, COALESCE(wave_order_stats.storage_fin_count, 0) AS storage_fin_count, COALESCE(wave_order_stats.storage_error_count, 0) AS storage_error_count, COALESCE(wave_order_stats.post_none_count, 0) AS post_none_count, COALESCE(wave_order_stats.post_fin_count, 0) AS post_fin_count, COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count, COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count, COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count, COALESCE(wave_order_stats.confirm_print_none_count, 0) AS confirm_print_none_count, COALESCE(wave_order_stats.confirm_print_fin_count, 0) AS confirm_print_fin_count, COALESCE(wave_order_stats.review_fin_count, 0) AS review_fin_count, COALESCE(wave_order_stats.review_error_count, 0) AS review_error_count, COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count, COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count, COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count, COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count, COALESCE(wave_order_stats.sync_none_count, 0) AS sync_none_count, COALESCE(wave_order_stats.sync_fin_count, 0) AS sync_fin_count, COALESCE(wave_order_stats.sync_error_count, 0) AS sync_error_count, COALESCE(wave_order_stats.owner_distinct_count, 0) AS owner_distinct_count, wave_order_stats.owner_store_id, COALESCE(wave_order_stats.owner_named_count, 0) AS owner_named_count ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset `; const countSql = ` SELECT COUNT(1) AS total ${batchListFromSql} `; const [ batchRows, totalRows ] = await Promise.all([ this.ctx.model.query(listSql, { replacements: { warehouseId, waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.replacements, ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, ...confirmPrintAssignmentFilterClause.replacements, ...claimAssignmentFilterClause.replacements, ...reviewAssignmentFilterClause.replacements, ...syncAssignmentFilterClause.replacements, ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), limit: pageSize, offset, }, }), this.ctx.model.query(countSql, { replacements: { warehouseId, waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.replacements, ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, ...confirmPrintAssignmentFilterClause.replacements, ...claimAssignmentFilterClause.replacements, ...reviewAssignmentFilterClause.replacements, ...syncAssignmentFilterClause.replacements, ...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}), }, }), ]); const rawList = Array.isArray(batchRows && batchRows[0]) ? batchRows[0] : []; const totalRowList = Array.isArray(totalRows && totalRows[0]) ? totalRows[0] : []; const total = Number(totalRowList[0] && totalRowList[0].total || 0); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; if (rawList.length === 0) { return this.success('ok', { list: [], pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } const ownerStoreNameMap = await this.resolveWaveBatchOwnerStoreNameMap(rawList, warehouseId); const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); const orderCount = Number(batch && batch.order_total || 0); const storageNoneCount = Number(batch && batch.storage_none_count || 0); const storageFinCount = Number(batch && batch.storage_fin_count || 0); const storageErrorCount = Number(batch && batch.storage_error_count || 0); const expressNoneCount = Number(batch && batch.post_none_count || 0); const expressFinCount = Number(batch && batch.post_fin_count || 0); const expressErrorCount = Number(batch && batch.post_error_count || 0); const printNoneCount = Number(batch && batch.print_none_count || 0); const printFinCount = Number(batch && batch.print_fin_count || 0); const confirmPrintNoneCount = Number(batch && batch.confirm_print_none_count || 0); const confirmPrintFinCount = Number(batch && batch.confirm_print_fin_count || 0); const pickNoneCount = Number(batch && batch.pick_none_count || 0); const pickFinCount = Number(batch && batch.pick_fin_count || 0); const pickErrorCount = Number(batch && batch.pick_error_count || 0); const reviewFinCount = Number(batch && batch.review_fin_count || 0); const reviewErrorCount = Number(batch && batch.review_error_count || 0); const syncNoneCount = Number(batch && batch.sync_none_count || 0); const syncFinCount = Number(batch && batch.sync_fin_count || 0); const syncErrorCount = Number(batch && batch.sync_error_count || 0); const unreviewedOrderCount = orderCount - reviewFinCount; const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0); const ownerNamedCount = Number(batch && batch.owner_named_count || 0); const ownerStoreId = Number(batch && batch.owner_store_id || 0); // 货主展示:仅当所有订单均存在货主(store_id)且货主唯一时返回货主名称,否则返回“混合”。 const ownerName = orderCount > 0 && ownerDistinctCount === 1 && ownerNamedCount === orderCount && ownerStoreId > 0 ? (ownerStoreNameMap.get(ownerStoreId) || '') : '混合'; // 复核状态判定:error 统一归入未复核 let reviewAssignmentStatus; if (reviewErrorCount > 0 || orderCount === 0 || reviewFinCount === 0) { reviewAssignmentStatus = 'unreviewed'; } else if (reviewFinCount === orderCount) { reviewAssignmentStatus = 'reviewed'; } else { reviewAssignmentStatus = 'partially_reviewed'; } return { wave_id: waveId, wave_no: String(batch && batch.wave_no || '').trim(), wave_type: Number(batch && batch.wave_type || 0), wave_status: Number(batch && batch.wave_status || 0), total_orders: Number(batch && batch.total_orders || 0), processed_orders: Number(batch && batch.processed_orders || 0), item_detail_machine: String(batch && batch.item_detail_machine || '').trim(), item_part_type: String(batch && batch.item_part_type || '').trim(), item_part: String(batch && batch.item_part || '').trim(), distinguish_express: Number(batch && batch.distinguish_express || 0), source: Number(batch && batch.source || 0), logistics_code: String(batch && batch.logistics_code || '').trim(), logistics_name: String(batch && batch.logistics_name || '').trim(), item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), warehouse_id: Number(batch && batch.warehouse_id || 0), creator: String(batch && batch.creator || '').trim(), create_time: batch && batch.create_time || null, update_time: batch && batch.update_time || null, order_count: orderCount, storage_assignment_status: this.resolveAssignmentStatus(orderCount, storageNoneCount, storageFinCount, storageErrorCount), express_assignment_status: this.resolveAssignmentStatus(orderCount, expressNoneCount, expressFinCount, expressErrorCount), print_assignment_status: this.resolveAssignmentStatus(orderCount, printNoneCount, printFinCount, 0, { none: '未打印', partial: '部分打印', finished: '已打印', }), confirm_print_assignment_status: this.resolveAssignmentStatus(orderCount, confirmPrintNoneCount, confirmPrintFinCount, 0, { none: '未确认打印', partial: '部分确认打印', finished: '已确认打印', }), claim_assignment_status: batch && batch.claim_time ? '已领料' : '未领料', claim_time: batch && batch.claim_time || null, claim_operator: String(batch && batch.claim_operator || '').trim(), pick_assignment_status: this.resolveAssignmentStatus(orderCount, pickNoneCount, pickFinCount, pickErrorCount, { none: '未拣货', partial: '部分拣货', finished: '已拣货', error: '拣货异常', }), review_assignment_status: reviewAssignmentStatus, sync_assignment_status: this.resolveAssignmentStatus(orderCount, syncNoneCount, syncFinCount, syncErrorCount, { none: '未同步', partial: '部分同步', finished: '已同步', error: '同步异常', }), unreviewed_order_count: unreviewedOrderCount, store_name: ownerName, }; }); return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 获取确认打印未领单波次版本号的缓存 key。 * * @param {number} warehouseId 仓库ID。 * @return {string} 缓存 key。 */ getConfirmPrintUnclaimedVersionKey(warehouseId) { return `${CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX}${warehouseId}`; } /** * 递增确认打印未领单波次版本号。 * * 确认打印(print.confirmWavePrint)与领单(pick.waveClaimScan)会改变统计结果, * 操作成功后调用本方法,驱动 confirmPrintUnclaimedWaveCount 长轮询立即返回新值。 * Redis 不可用或失败仅记录 warn,不影响主流程(长轮询端会降级为轮询 DB)。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async bumpConfirmPrintUnclaimedWaveVersion(warehouseId) { try { const client = this.app && this.app.redis && typeof this.app.redis.get === 'function' ? this.app.redis.get('cache') : null; if (client && typeof client.incr === 'function') { await client.incr(this.getConfirmPrintUnclaimedVersionKey(warehouseId)); } } catch (error) { this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号递增失败', { warehouseId, error: error && error.message ? error.message : `${error}`, }); } } /** * 读取确认打印未领单波次版本号。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 版本号,读取失败或不存在时返回 null。 */ async getConfirmPrintUnclaimedWaveVersion(warehouseId) { try { const client = this.app && this.app.redis && typeof this.app.redis.get === 'function' ? this.app.redis.get('cache') : null; if (!client || typeof client.get !== 'function') { return null; } const rawValue = await client.get(this.getConfirmPrintUnclaimedVersionKey(warehouseId)); const value = Number(rawValue); return Number.isFinite(value) && value > 0 ? value : null; } catch (error) { this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号读取失败', { warehouseId, error: error && error.message ? error.message : `${error}`, }); return null; } } /** * 查询「已确认打印但未领单」的波次数量(波次表驱动口径)。 * * 口径说明: * - 未领单:以波次表为准(wb.claim_time IS NULL)。历史领单发生在 wms_wave_batch * 增加 claim_time 字段之前时,订单维度 claim_status 可能已是 'fin' 但波次表无 * 记录,故不能用订单 claim_status 判断「波次是否领单」。 * - 已确认打印:波次下存在 confirm_print_status='fin' 的非取消订单。 * - 仅统计 wave_status 0/1 的波次(与波次列表一致)。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 波次数量。 */ async queryConfirmPrintUnclaimedWaveCount(warehouseId) { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const rows = await this.ctx.model.query( `SELECT COUNT(*) AS wave_count FROM wms_wave_batch wb WHERE wb.warehouse_id = :warehouseId AND wb.wave_status IN (0, 1) AND wb.claim_time IS NULL AND EXISTS ( SELECT 1 FROM ${orderTableName} od WHERE od.wave_id = wb.wave_id AND od.warehouse_id = wb.warehouse_id AND od.status <> 'cancel' AND od.confirm_print_status = 'fin' )`, { replacements: { warehouseId } } ); const rawList = Array.isArray(rows && rows[0]) ? rows[0] : []; return Number(rawList[0] && rawList[0].wave_count || 0); } /** * 确认打印扫描(与领单 pick.waveClaimScan 操作一致): * 扫波次内任一订单面单号,将波次下已打印且非拦截的订单批量置 * confirm_print_status='fin' 并写订单操作日志。 * * 实际复用 print.confirmWavePrint 实现,避免重复维护; * 成功后递增统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询。 * * @param {Object} data 入参。 * @param {string} data.waybill_no 面单号/运单号(必填)。 * @return {Promise} 统一返回结构。 */ async confirmPrintScan(data = {}) { const printService = this.ctx.service && this.ctx.service.systemMethods && this.ctx.service.systemMethods.print; if (!printService || typeof printService.confirmWavePrint !== 'function') { return this.fail('确认打印服务不可用', {}, 500); } return await printService.confirmWavePrint(data); } /** * 快速查询「已确认打印但未领单」的波次数量(波次表驱动口径: * 未领单以 wms_wave_batch.claim_time IS NULL 为准,已确认打印以波次下存在 * confirm_print_status='fin' 的订单为准)。 * * 长轮询语义(参考工作台扫码登录): * - 不传 last_count:立即返回当前值(status=current); * - 传 last_count 且与当前值不同:立即返回新值(status=changed); * - 传 last_count 且与当前值相同:进入等待,每 1s 检查一次版本号(确认打印/领单 * 成功会递增版本号),最长等待 60s;期间变化立即返回新值(status=changed), * 超时未变化则重查一次返回当前值(status=timeout)。 * * @param {Object} [data={}] 入参。 * @param {number|string} [data.last_count] 上次调用返回的 count(可选基线)。 * @return {Promise} 统一返回结构,data 含 count / warehouse_id / status。 */ async confirmPrintUnclaimedWaveCount(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { return this.fail('未识别到当前仓库上下文', {}, 400); } const rawLastCount = requestData.last_count === undefined ? requestData.lastCount : requestData.last_count; const hasBaseline = rawLastCount !== undefined && rawLastCount !== null && rawLastCount !== ''; const lastCount = hasBaseline ? Number(rawLastCount) : NaN; let currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); // 未带基线或基线非法:直接返回当前值(快速查询) if (!hasBaseline || !Number.isFinite(lastCount)) { return this.success('ok', { count: currentCount, warehouse_id: warehouseId, status: 'current', }); } // 已变化:立即返回新值 if (currentCount !== lastCount) { return this.success('ok', { count: currentCount, warehouse_id: warehouseId, status: 'changed', }); } // 等待变化:优先轮询版本号(低成本),版本号不可用时降级为轮询 DB const baselineVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId); const startedAt = Date.now(); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); while (Date.now() - startedAt < CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS) { await sleep(CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS); const currentVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId); if (baselineVersion !== null && currentVersion !== null && currentVersion !== baselineVersion) { currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); return this.success('ok', { count: currentCount, warehouse_id: warehouseId, status: 'changed', }); } // 版本号不可用:降级为直接对比 count if (baselineVersion === null || currentVersion === null) { currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); if (currentCount !== lastCount) { return this.success('ok', { count: currentCount, warehouse_id: warehouseId, status: 'changed', }); } } } // 超时兜底:重查一次返回当前值(若期间恰好变化也返回新值) currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId); return this.success('ok', { count: currentCount, warehouse_id: warehouseId, status: currentCount !== lastCount ? 'changed' : 'timeout', }); } /** * 拣货任务列表查询。 * * 基于 wms_wave_pick_task 主表按当前仓库维度分页查询,默认按 create_time 倒序。 * * @param {Object} [data={}] 请求参数。 * @param {number|string} [data.page] 页码(兼容 current)。 * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 * @param {Object} [data.where] 查询过滤。 * @return {Promise} 列表与分页结果;每项 list 元素包含 wave_list 数组(wave_id / wave_no / box_no / status / bind_time / pick_time)。 */ async wavePickTaskList(data = {}) { try { const requestData = this.isPlainObject(data) ? data : {}; const { page, pageSize } = this.normalizeWavePickTaskListPagination(requestData); const normalizedRequest = this.normalizeWavePickTaskListRequest(requestData); const warehouseId = normalizedRequest.warehouseId; const whereClause = this.buildWavePickTaskListWhereClause(normalizedRequest.where); const offset = (page - 1) * pageSize; const listSql = ` SELECT t.id, t.task_no, t.warehouse_id, t.wave_id, t.pick_mode, t.status, t.review_status, t.source, t.wave_count, t.order_count, t.box_count, t.pick_user_id, t.pick_user_name, t.review_user_id, t.review_user_name, t.current_cart_id, t.current_cart_code_snapshot, c.cart_name AS cart_name, t.batch_no, t.claim_operator_id, t.claim_operator, t.device_id, t.start_time, t.finish_time, t.review_start_time, t.review_finish_time, t.create_time, t.update_time FROM wms_wave_pick_task t LEFT JOIN wms_pick_cart c ON c.id = t.current_cart_id AND c.warehouse_id = t.warehouse_id WHERE t.warehouse_id = :warehouseId ${whereClause.sql} ORDER BY t.create_time DESC LIMIT :limit OFFSET :offset `; const countSql = ` SELECT COUNT(1) AS total FROM wms_wave_pick_task t WHERE t.warehouse_id = :warehouseId ${whereClause.sql} `; const replacements = { warehouseId, ...whereClause.replacements, }; const [ listRows, countRows ] = await Promise.all([ this.ctx.model.query(listSql, { replacements: { ...replacements, limit: pageSize, offset, }, }), this.ctx.model.query(countSql, { replacements, }), ]); const sourceList = Array.isArray(listRows && listRows[0]) ? listRows[0] : []; const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; const total = Number(totalRowList[0] && totalRowList[0].total || 0); // 批量查询 wave_list:收集任务ID,从关联表获取波次详情 const taskIds = sourceList .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0); const taskWaveMap = new Map(); if (taskIds.length > 0) { const taskWaveRows = await this.ctx.model.query(` SELECT ptw.task_id, ptw.wave_id, ptw.wave_no, ptw.box_no, ptw.status, ptw.bind_time, ptw.pick_time FROM wms_wave_pick_task_wave ptw WHERE ptw.task_id IN (:taskIds) AND ptw.warehouse_id = :warehouseId ORDER BY ptw.id ASC `, { replacements: { taskIds, warehouseId }, type: this.ctx.model.QueryTypes.SELECT, }); const normalizedTaskWaveRows = Array.isArray(taskWaveRows) ? taskWaveRows : []; for (const row of normalizedTaskWaveRows) { const taskId = Number(row && row.task_id || 0); if (!Number.isInteger(taskId) || taskId <= 0) { continue; } if (!taskWaveMap.has(taskId)) { taskWaveMap.set(taskId, []); } taskWaveMap.get(taskId).push({ wave_id: Number(row && row.wave_id || 0), wave_no: String(row && row.wave_no || '').trim(), box_no: Number(row && row.box_no || 0), status: Number(row && row.status || 0), bind_time: row && row.bind_time || null, pick_time: row && row.pick_time || null, }); } } // 回退:对于 wms_wave_pick_task_wave 无记录的任务, // 尝试从主表 wave_id / wms_wave_batch 查询波次信息。 // 兼容场景:散单旧数据未写入关联表、已取消任务关联记录被删除等。 const missingWaveTaskIds = sourceList .map(item => { const taskId = Number(item && item.id || 0); return Number.isInteger(taskId) && taskId > 0 && !taskWaveMap.has(taskId) ? { taskId, waveId: Number(item && item.wave_id || 0) } : null; }) .filter(Boolean); if (missingWaveTaskIds.length > 0) { // 优先走 wms_wave_batch 回退(主表 wave_id 有值时) const batchFallbackIds = missingWaveTaskIds.filter(m => m.waveId > 0); if (batchFallbackIds.length > 0) { const fallbackWaveIds = [ ...new Set(batchFallbackIds.map(m => m.waveId)) ]; const fallbackWaveRows = await this.ctx.model.query(` SELECT wave_id, wave_no FROM wms_wave_batch WHERE wave_id IN (:waveIds) AND warehouse_id = :warehouseId `, { replacements: { waveIds: fallbackWaveIds, warehouseId }, type: this.ctx.model.QueryTypes.SELECT, }); const waveNoMap = new Map(); const normalizedFallbackRows = Array.isArray(fallbackWaveRows) ? fallbackWaveRows : []; for (const row of normalizedFallbackRows) { const waveId = Number(row && row.wave_id || 0); if (!Number.isInteger(waveId) || waveId <= 0) { continue; } waveNoMap.set(waveId, String(row && row.wave_no || '').trim()); } for (const { taskId, waveId } of batchFallbackIds) { const waveNo = waveNoMap.get(waveId) || ''; taskWaveMap.set(taskId, [{ wave_id: waveId, wave_no: waveNo, box_no: 0, status: 0, bind_time: null, pick_time: null, }]); } } // 剩余仍未回退到的任务(wave_id 为空或 wms_wave_batch 也无记录), // 检查其 batch_no(散单模式下冗余了 wave_no) const remainingFallbackTaskIds = missingWaveTaskIds .filter(m => !taskWaveMap.has(m.taskId)) .map(m => m.taskId); if (remainingFallbackTaskIds.length > 0) { for (const taskId of remainingFallbackTaskIds) { const item = sourceList.find(s => Number(s && s.id || 0) === taskId); const batchNo = String(item && item.batch_no || '').trim(); if (batchNo) { taskWaveMap.set(taskId, [{ wave_id: 0, wave_no: batchNo, box_no: 0, status: 0, bind_time: null, pick_time: null, }]); } } } } const list = sourceList.map(item => ({ task_id: Number(item && item.id || 0), task_no: String(item && item.task_no || '').trim(), warehouse_id: Number(item && item.warehouse_id || 0), pick_mode: Number(item && item.pick_mode || 0), status: Number(item && item.status || 0), review_status: Number(item && item.review_status || 0), source: Number(item && item.source || 0), wave_count: Number(item && item.wave_count || 0), order_count: Number(item && item.order_count || 0), box_count: Number(item && item.box_count || 0), pick_user_id: Number(item && item.pick_user_id || 0), pick_user_name: String(item && item.pick_user_name || '').trim(), operator_id: Number(item && item.pick_user_id || 0), operator_name: String(item && item.pick_user_name || '').trim(), review_user_id: Number(item && item.review_user_id || 0), review_user_name: String(item && item.review_user_name || '').trim(), current_cart_id: Number(item && item.current_cart_id || 0), current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), cart_name: String(item && item.cart_name || '').trim(), batch_no: String(item && item.batch_no || '').trim(), claim_operator_id: Number(item && item.claim_operator_id || 0) || null, claim_operator: String(item && item.claim_operator || '').trim() || null, device_id: String(item && item.device_id || '').trim(), start_time: item && item.start_time || null, start_at: item && item.start_time || null, finish_time: item && item.finish_time || null, finish_at: item && item.finish_time || null, review_start_time: item && item.review_start_time || null, review_finish_time: item && item.review_finish_time || null, create_time: item && item.create_time || null, created_at: item && item.create_time || null, update_time: item && item.update_time || null, wave_list: taskWaveMap.get(Number(item && item.id || 0)) || [], })); return this.success('ok', { list, total, page, page_size: pageSize, }); } catch (error) { const errorMessage = String(error && error.message || '').trim(); const isBadRequest = /参数|上下文|不支持/.test(errorMessage); return this.fail(`查询拣货任务列表失败: ${errorMessage || '未知错误'}`, {}, isBadRequest ? 400 : 500); } } /** * 批量解除波次任务提交接口。 * * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 * 提交前校验:波次属于活动拣货任务、波次内存在已拣货完成或拣货中的订单、 * 或波次状态已进入拣货中及后续环节时,拒绝取消波次。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 * @return {Promise} 任务提交结果。 */ async batchCancel(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { throw new Error('warehouse_id 参数不合法'); } if (requestWarehouseId !== contextWarehouseId) { throw new Error('warehouse_id 与当前仓库上下文不一致'); } const warehouseId = requestWarehouseId; const normalizedWaveIds = this.normalizeBatchCancelWaveIds(data); if (normalizedWaveIds.length === 0) { throw new Error('wave_ids 参数不能为空或格式错误'); } const activeTaskWaves = await this.ctx.model.query( `SELECT ptw.wave_id FROM wms_wave_pick_task_wave ptw INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id WHERE ptw.wave_id IN (:waveIds) AND pt.status IN (0, 1) LIMIT 1`, { replacements: { waveIds: normalizedWaveIds }, type: this.ctx.model.QueryTypes.SELECT, } ); if (activeTaskWaves.length > 0) { throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); } // 业务规则校验:波次内存在已拣货完成或拣货中的订单时禁止取消波次 const orderModelForGuard = await this.getOrderModel('pendingOrder', warehouseId); const pickedOrderRows = await orderModelForGuard.findAll({ attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status' ], where: { warehouse_id: warehouseId, wave_id: { [Op.in]: normalizedWaveIds }, pick_status: { [Op.in]: [ 'padding', 'fin' ] }, }, raw: true, }); const normalizedPickedOrderRows = Array.isArray(pickedOrderRows) ? pickedOrderRows : []; if (normalizedPickedOrderRows.length > 0) { const blockedWaveIds = [ ...new Set(normalizedPickedOrderRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; const blockedOrderIds = normalizedPickedOrderRows .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); const shownOrderIds = blockedOrderIds.slice(0, 20).join(', '); const orderIdSuffix = blockedOrderIds.length > 20 ? ' 等' : ''; return this.fail( `波次内存在已拣货完成或拣货中的订单,禁止取消波次:波次 ${blockedWaveIds.join(', ')},订单 ${shownOrderIds}${orderIdSuffix}`, { wave_ids: blockedWaveIds, order_ids: blockedOrderIds, }, 400 ); } // 兜底校验:波次状态已进入拣货中及后续环节(拣货中/拣货完成/复核完成/打包完成)时禁止取消 const advancedWaveRows = await this.ctx.model.query( `SELECT wave_id, wave_no, wave_status FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) AND wave_status >= 3`, { replacements: { warehouseId, waveIds: normalizedWaveIds, }, type: this.ctx.model.QueryTypes.SELECT, } ); const normalizedAdvancedWaveRows = Array.isArray(advancedWaveRows) ? advancedWaveRows : []; if (normalizedAdvancedWaveRows.length > 0) { const blockedWaveIds = normalizedAdvancedWaveRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0); return this.fail( `波次已进入拣货或后续环节,禁止取消波次:波次 ${blockedWaveIds.join(', ')}`, { wave_ids: blockedWaveIds }, 400 ); } const requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); if (existingTask) { return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', message: '批量解除波次任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } const acceptedAt = new Date().toISOString(); await this.setBatchCancelTaskProgress(taskId, 'submitted', { warehouse_id: warehouseId, wave_ids: normalizedWaveIds.join(','), wave_id_list: normalizedWaveIds, total_wave_count: normalizedWaveIds.length, processed_wave_count: 0, progress_percent: 0, submitted_at: Date.now(), accepted_at: acceptedAt, result: null, error: '', error_code: '', }); this.ctx.logger.info('[wave.batchCancel] 任务提交成功', { taskId, warehouseId, waveCount: normalizedWaveIds.length, }); setImmediate(() => { this.runBatchCancelTask({ taskId, warehouseId, waveIds: normalizedWaveIds, }).catch(error => { this.ctx.logger.error('[wave.batchCancel] 后台任务异常', { taskId, warehouseId, waveCount: normalizedWaveIds.length, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: warehouseId, message: '批量解除波次任务已提交。', accepted_at: acceptedAt, }); } /** * 查询批量解除波次任务进度。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度响应。 */ async batchCancelTaskProgress(data = {}) { const taskId = this.normalizeBatchCancelTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getBatchCancelTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, state: 'not_found', }); } const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; const payload = { task_id: taskId, state, warehouse_id: Number(cachedProgress.warehouse_id || 0), submitted_at: cachedProgress.submitted_at || null, start_time: cachedProgress.start_time || null, end_time: cachedProgress.end_time || null, }; if (state === 'submitted' || state === 'running') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); } if (state === 'success') { const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; payload.progress_percent = Number(cachedProgress.progress_percent || 100); payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; payload.affected_order_count = Number(result.affected_order_count || 0); payload.canceled_wave_count = Number(result.canceled_wave_count || 0); payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); } if (state === 'failed') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.error_message = String(cachedProgress.error || '').trim(); payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_CANCEL_FAILED'; payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); payload.duration_ms = Number(cachedProgress.duration_ms || 0); } return this.success('ok', payload); } /** * 批次分配快递号任务提交接口。 * * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 * @return {Promise} 任务受理结果。 */ async batchAllocateExpress(data = {}) { const traceId = this.buildBatchAllocateExpressTraceId(data); const requestSnapshot = { warehouse_id: data && (data.warehouse_id ?? data.warehouseId), wave_ids: data && (data.wave_ids ?? data.waveIds ?? data.ids), task_id: data && (data.task_id ?? data.taskId), }; this.ctx.logger.info('[wave.batchAllocateExpress] 入口请求', { traceId, requestSnapshot, }); try { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-仓库上下文缺失', { traceId, contextWarehouseId, requestSnapshot, }); throw new Error('未识别到当前仓库上下文'); } const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 非法', { traceId, contextWarehouseId, requestWarehouseId, requestSnapshot, }); throw new Error('warehouse_id 参数不合法'); } if (requestWarehouseId !== contextWarehouseId) { this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-warehouse_id 与上下文不一致', { traceId, contextWarehouseId, requestWarehouseId, requestSnapshot, }); throw new Error('warehouse_id 与当前仓库上下文不一致'); } const warehouseId = requestWarehouseId; const normalizedWaveIds = this.normalizeBatchAllocateExpressWaveIds(data); if (normalizedWaveIds.length === 0) { this.ctx.logger.warn('[wave.batchAllocateExpress] 参数校验失败-wave_ids 为空', { traceId, warehouseId, requestSnapshot, }); throw new Error('wave_ids 参数不能为空或格式错误'); } const requestedTaskId = this.normalizeBatchAllocateExpressTaskId(data); const taskId = requestedTaskId || this.generateBatchAllocateExpressTaskId(warehouseId); const existingTask = await this.getBatchAllocateExpressTaskProgress(taskId); if (existingTask) { this.ctx.logger.info('[wave.batchAllocateExpress] 命中幂等任务缓存,直接返回', { traceId, taskId, warehouseId, waveIds: normalizedWaveIds, cachedState: String(existingTask.state || '').trim() || 'submitted', }); return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', message: '批量分配快递任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } const acceptedAt = new Date().toISOString(); await this.setBatchAllocateExpressTaskProgress(taskId, 'submitted', { warehouse_id: warehouseId, wave_ids: normalizedWaveIds.join(','), wave_id_list: normalizedWaveIds, total_wave_count: normalizedWaveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, submitted_at: Date.now(), accepted_at: acceptedAt, result: null, error: '', error_code: '', trace_id: traceId, }); this.ctx.logger.info('[wave.batchAllocateExpress] 任务提交成功', { traceId, taskId, warehouseId, waveCount: normalizedWaveIds.length, waveIds: normalizedWaveIds, }); setImmediate(() => { this.runBatchAllocateExpressTask({ taskId, warehouseId, waveIds: normalizedWaveIds, trace_id: traceId, }).catch(error => { this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务异常', { traceId, taskId, warehouseId, waveCount: normalizedWaveIds.length, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: warehouseId, message: '批量分配快递任务已提交。', accepted_at: acceptedAt, }); } catch (error) { this.ctx.logger.error('[wave.batchAllocateExpress] 入口处理异常', { traceId, requestSnapshot, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); throw error; } } /** * 查询批次分配快递号任务进度。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度响应。 */ async batchAllocateExpressTaskProgress(data = {}) { const taskId = this.normalizeBatchAllocateExpressTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getBatchAllocateExpressTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, state: 'not_found', }); } const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; const payload = { task_id: taskId, state, warehouse_id: Number(cachedProgress.warehouse_id || 0), submitted_at: cachedProgress.submitted_at || null, start_time: cachedProgress.start_time || null, end_time: cachedProgress.end_time || null, }; if (state === 'submitted' || state === 'running') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); } if (state === 'success') { const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; payload.progress_percent = Number(cachedProgress.progress_percent || 100); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.success_order_count = Number(cachedProgress.success_order_count || 0); payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); payload.allocated_order_count = Number(result.allocated_order_count || 0); payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); payload.message = String(result.message || '').trim(); } if (state === 'failed') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.success_order_count = Number(cachedProgress.success_order_count || 0); payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); payload.error_message = String(cachedProgress.error || '').trim(); payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED'; payload.duration_ms = Number(cachedProgress.duration_ms || 0); } return this.success('ok', payload); } /** * 批次分配储位任务提交接口。 * * 仅接收当前仓库下波次ID,提交后立即返回 task_id,实际分配由后台异步执行。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 * @return {Promise} 任务受理结果。 */ async batchAllocateStorage(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { throw new Error('warehouse_id 参数不合法'); } if (requestWarehouseId !== contextWarehouseId) { throw new Error('warehouse_id 与当前仓库上下文不一致'); } const warehouseId = requestWarehouseId; const normalizedWaveIds = this.normalizeBatchAllocateStorageWaveIds(data); if (normalizedWaveIds.length === 0) { throw new Error('wave_ids 参数不能为空或格式错误'); } const requestedTaskId = this.normalizeBatchAllocateStorageTaskId(data); const taskId = requestedTaskId || this.generateBatchAllocateStorageTaskId(warehouseId); const existingTask = await this.getBatchAllocateStorageTaskProgress(taskId); if (existingTask) { return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', message: '批量分配储位任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } const acceptedAt = new Date().toISOString(); await this.setBatchAllocateStorageTaskProgress(taskId, 'submitted', { warehouse_id: warehouseId, wave_ids: normalizedWaveIds.join(','), wave_id_list: normalizedWaveIds, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_wave_count: normalizedWaveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, submitted_at: Date.now(), accepted_at: acceptedAt, result: null, error: '', error_code: '', }); this.ctx.logger.info('[wave.batchAllocateStorage] 任务提交成功', { taskId, warehouseId, waveCount: normalizedWaveIds.length, }); setImmediate(() => { this.runBatchAllocateStorageTask({ taskId, warehouseId, waveIds: normalizedWaveIds, }).catch(error => { this.ctx.logger.error('[wave.batchAllocateStorage] 后台任务异常', { taskId, warehouseId, waveCount: normalizedWaveIds.length, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: warehouseId, message: '批量分配储位任务已提交。', accepted_at: acceptedAt, }); } /** * 查询批次分配储位任务进度。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度响应。 */ async batchAllocateStorageTaskProgress(data = {}) { const taskId = this.normalizeBatchAllocateStorageTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getBatchAllocateStorageTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, state: 'not_found', }); } const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; const payload = { task_id: taskId, state, warehouse_id: Number(cachedProgress.warehouse_id || 0), submitted_at: cachedProgress.submitted_at || null, start_time: cachedProgress.start_time || null, end_time: cachedProgress.end_time || null, }; const cachedBusinessId = Number(cachedProgress.business_id || 0); const cachedBusinessIds = this.normalizeIdsInput(cachedProgress.business_ids); if (cachedBusinessId > 0) { payload.business_id = cachedBusinessId; } if (cachedBusinessIds.length > 0) { payload.business_ids = cachedBusinessIds; } if (state === 'submitted' || state === 'running') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); } if (state === 'success') { const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; payload.progress_percent = Number(cachedProgress.progress_percent || 100); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.success_order_count = Number(cachedProgress.success_order_count || 0); payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); payload.allocated_order_count = Number(result.allocated_order_count || cachedProgress.allocated_order_count || 0); payload.affected_order_count = Number(result.affected_order_count || cachedProgress.affected_order_count || 0); payload.allocated_order_ids = this.normalizeIdsInput( result.allocated_order_ids !== undefined ? result.allocated_order_ids : cachedProgress.allocated_order_ids ); payload.shortage_order_ids = this.normalizeIdsInput( result.shortage_order_ids !== undefined ? result.shortage_order_ids : cachedProgress.shortage_order_ids ); payload.affected_order_ids = this.normalizeIdsInput( result.affected_order_ids !== undefined ? result.affected_order_ids : cachedProgress.affected_order_ids ); const successBusinessId = Number(result.business_id || payload.business_id || 0); const successBusinessIds = this.normalizeIdsInput( result.business_ids !== undefined ? result.business_ids : payload.business_ids ); if (successBusinessId > 0) { payload.business_id = successBusinessId; } if (successBusinessIds.length > 0) { payload.business_ids = successBusinessIds; } payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); payload.message = String(result.message || '').trim(); } if (state === 'failed') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.success_order_count = Number(cachedProgress.success_order_count || 0); payload.failed_order_count = Number(cachedProgress.failed_order_count || 0); payload.error_message = String(cachedProgress.error || '').trim(); payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED'; payload.duration_ms = Number(cachedProgress.duration_ms || 0); } return this.success('ok', payload); } /** * 按仓库提交波次策略快速扫描异步任务。 * * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接复用已有任务。 * * @param {number|string} [warehouseId=0] 仓库ID,未传时优先使用上下文仓库ID。 * @param {Object} [options={}] 提交选项。 * @param {Array|number|string} [options.orderIds] 可选订单ID数组。 * @param {boolean} [options.wait=false] 是否等待任务执行完成后再返回最终进度快照。 * @return {Promise} 任务受理结果(plain object)。 */ async submitWaveStrategyQuickScanForWarehouse(warehouseId = 0, options = {}) { const normalizedWarehouseId = Number(warehouseId || this.getWarehouseId() || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const normalizedOptions = this.isPlainObject(options) ? options : {}; const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); const wait = this.normalizeBoolean(normalizedOptions.wait, false); const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId); if (runningTask && runningTask.task_id) { const existingTaskId = String(runningTask.task_id || '').trim(); const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; if (![ 'success', 'failed' ].includes(existingState)) { return { task_id: existingTaskId, warehouse_id: normalizedWarehouseId, state: existingState, message: '已有快速扫描任务在运行中。请稍后重试或查询现有任务进度。', accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), }; } await this.clearWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, existingTaskId); } const taskId = this.generateWaveStrategyQuickScanTaskId(normalizedWarehouseId); const acceptedAt = new Date().toISOString(); await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { warehouse_id: normalizedWarehouseId, total_order_count: 0, processed_order_count: 0, matched_order_count: 0, unmatched_order_count: 0, progress_percent: 0, submitted_at: Date.now(), accepted_at: acceptedAt, start_time: null, end_time: null, ...(orderIds.length > 0 ? { order_ids: orderIds } : {}), error: '', error_code: '', result: null, ...(forceRescan ? { force_rescan: true } : {}), }); await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { state: 'submitted', accepted_at: acceptedAt, }); if (wait) { await this.runWaveStrategyQuickScanTask({ taskId, warehouseId: normalizedWarehouseId, ...(orderIds.length > 0 ? { orderIds } : {}), ...(forceRescan ? { forceRescan } : {}), }); const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}; return { ...finalProgress, task_id: taskId, warehouse_id: normalizedWarehouseId, accepted_at: acceptedAt, }; } setImmediate(() => { this.runWaveStrategyQuickScanTask({ taskId, warehouseId: normalizedWarehouseId, ...(orderIds.length > 0 ? { orderIds } : {}), ...(forceRescan ? { forceRescan } : {}), }).catch(error => { this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { taskId, warehouseId: normalizedWarehouseId, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return { task_id: taskId, warehouse_id: normalizedWarehouseId, state: 'submitted', message: '快速扫描任务已提交。', accepted_at: acceptedAt, }; } /** * 提交波次策略快速扫描异步任务。 * * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接返回已有 task_id。 * * @return {Promise} 任务受理结果。 */ async waveStrategyQuickScan() { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); return this.success('ok', { status: 'success', ...submitPayload, }); } /** * 查询波次策略快速扫描任务进度。 * * @param {Object} [data={}] 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度信息。 */ async waveStrategyQuickScanTaskProgress(data = {}) { const taskId = this.normalizeWaveStrategyQuickScanTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, state: 'not_found', }); } return this.success('ok', { task_id: taskId, state: String(cachedProgress.state || 'submitted').trim() || 'submitted', warehouse_id: Number(cachedProgress.warehouse_id || 0), total_order_count: Number(cachedProgress.total_order_count || 0), processed_order_count: Number(cachedProgress.processed_order_count || 0), matched_order_count: Number(cachedProgress.matched_order_count || 0), unmatched_order_count: Number(cachedProgress.unmatched_order_count || 0), progress_percent: Number(cachedProgress.progress_percent || 0), submitted_at: cachedProgress.submitted_at || null, start_time: cachedProgress.start_time || null, end_time: cachedProgress.end_time || null, error_message: String(cachedProgress.error || '').trim(), error_code: String(cachedProgress.error_code || '').trim(), duration_ms: Number(cachedProgress.duration_ms || 0), }); } /** * 构建快速扫描订单查询条件。 * * @param {number} warehouseId 仓库ID。 * @param {number} strategyVersion 当前策略版本号。 * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 * @param {boolean} [forceRescan=false] 是否强制全量重扫(忽略版本号条件)。 * @return {Object} 订单查询 where 条件。 */ buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = [], forceRescan = false) { const normalizedOrderIds = this.normalizeIdsInput(orderIds); const where = { warehouse_id: warehouseId, step: { [Op.ne]: 0 }, wave_id: 0, intercept_status: 'none', lock_status: 'none', print_status: { [Op.ne]: 'fin' }, }; if (!forceRescan) { where[Op.or] = [ { wave_strategy_version: { [Op.ne]: strategyVersion } }, { wave_strategy_version: { [Op.is]: null } }, ]; } if (normalizedOrderIds.length > 0) { where.id = { [Op.in]: normalizedOrderIds, }; } return where; } /** * 获取快速扫描可用策略行(带缓存)。 * * @param {number} warehouseId 仓库ID。 * @return {Promise>} 策略原始行数组。 */ async getWaveStrategyQuickScanStrategyRows(warehouseId) { const strategyModel = this.ctx.model && ( this.ctx.model.wms_wave_strategy || this.ctx.model.PickingStrategy || this.ctx.model.WmsWaveStrategy ); if (!strategyModel || typeof strategyModel.findAll !== 'function') { throw new Error('波次策略模型不可用'); } const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${warehouseId}`; const cachedStrategyRows = this.app && typeof this.app.getCacheAsync === 'function' ? await this.app.getCacheAsync(strategyCacheKey) : null; if (Array.isArray(cachedStrategyRows)) { return cachedStrategyRows; } const strategyRows = await strategyModel.findAll({ where: { warehouse_id: warehouseId, status: 1, }, order: [[ 'id', 'ASC' ]], raw: true, }); if (this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(strategyCacheKey, strategyRows, WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS); } return strategyRows; } /** * 获取波次策略快速扫描命中副表模型。 * * @return {Object|null} 命中副表模型;若不可用返回 null。 */ getWaveStrategyQuickScanMatchModel() { const modelContext = this.ctx && this.ctx.model; if (!modelContext || typeof modelContext !== 'object') { return null; } return modelContext.wms_order_wave_strategy_match || modelContext.OrderWaveStrategyMatch || modelContext.WmsOrderWaveStrategyMatch || null; } /** * 同步快速扫描命中策略到副表(先删后写)。 * * @param {number|string} warehouseId 仓库ID。 * @param {Array|number|string} [orderIds=[]] 扫描范围订单ID。 * @param {Object} [matchedStrategyIdsByOrder={}] 订单命中策略映射。 * @return {Promise} 无返回值。 */ async syncWaveStrategyQuickScanMatchedStrategies(warehouseId, orderIds = [], matchedStrategyIdsByOrder = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedOrderIds = this.normalizeIdsInput(orderIds); if (normalizedOrderIds.length === 0) { return; } const matchModel = this.getWaveStrategyQuickScanMatchModel(); if (!matchModel || typeof matchModel.destroy !== 'function' || typeof matchModel.bulkCreate !== 'function') { throw new Error('波次策略命中副表模型不可用'); } for (let i = 0; i < normalizedOrderIds.length; i += 500) { const orderChunk = normalizedOrderIds.slice(i, i + 500); await matchModel.destroy({ where: { warehouse_id: normalizedWarehouseId, order_id: { [Op.in]: orderChunk }, }, }); } const normalizedMatchedMap = this.isPlainObject(matchedStrategyIdsByOrder) ? matchedStrategyIdsByOrder : {}; const orderScopeSet = new Set(normalizedOrderIds); const dedupeSet = new Set(); const createTime = this.getCurrentDateTime ? this.getCurrentDateTime() : new Date(); const rows = []; Object.keys(normalizedMatchedMap).forEach(orderKey => { const orderId = Number(orderKey); if (!Number.isInteger(orderId) || orderId <= 0 || !orderScopeSet.has(orderId)) { return; } const strategyIds = Array.isArray(normalizedMatchedMap[orderKey]) ? normalizedMatchedMap[orderKey] : []; strategyIds.forEach(strategyIdItem => { const strategyId = Number(strategyIdItem); if (!Number.isInteger(strategyId) || strategyId <= 0) { return; } const dedupeKey = `${orderId}:${strategyId}`; if (dedupeSet.has(dedupeKey)) { return; } dedupeSet.add(dedupeKey); rows.push({ warehouse_id: normalizedWarehouseId, order_id: orderId, strategy_id: strategyId, create_time: createTime, }); }); }); for (let i = 0; i < rows.length; i += 500) { const rowChunk = rows.slice(i, i + 500); await matchModel.bulkCreate(rowChunk); } } /** * 清理波次策略快速扫描命中副表过期数据。 * * @param {Object} [options={}] 清理参数。 * @param {number|string} [options.expireHours=24] 过期小时数。 * @param {number|string} [options.warehouseId] 可选仓库ID。 * @return {Promise} 删除条数。 */ async cleanupWaveStrategyQuickScanMatchedStrategies(options = {}) { const normalizedOptions = this.isPlainObject(options) ? options : {}; const expireHoursRaw = Number(normalizedOptions.expireHours); const expireHours = Number.isFinite(expireHoursRaw) && expireHoursRaw > 0 ? expireHoursRaw : 24; const warehouseId = Number(normalizedOptions.warehouseId || 0); const expireAt = new Date(Date.now() - Math.floor(expireHours * 60 * 60 * 1000)); const matchModel = this.getWaveStrategyQuickScanMatchModel(); if (!matchModel || typeof matchModel.destroy !== 'function') { throw new Error('波次策略命中副表模型不可用'); } const where = { create_time: { [Op.lt]: expireAt, }, }; if (Number.isInteger(warehouseId) && warehouseId > 0) { where.warehouse_id = warehouseId; } const deletedCount = await matchModel.destroy({ where }); // 清理后重建 if (Number.isInteger(warehouseId) && warehouseId > 0) { setImmediate(() => { this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message); }); }); } return Number(deletedCount || 0); } /** * 按仓库 + 订单ID集合清理波次策略快速扫描命中副表数据。 * * @param {number|string} [warehouseId=0] 仓库ID。 * @param {Array|number|string} [orderIds=[]] 订单ID集合。 * @return {Promise} 删除条数。 */ async cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds(warehouseId = 0, orderIds = []) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedOrderIds = this.normalizeIdsInput(orderIds); if (normalizedOrderIds.length === 0) { return 0; } const matchModel = this.getWaveStrategyQuickScanMatchModel(); if (!matchModel || typeof matchModel.destroy !== 'function') { throw new Error('波次策略命中副表模型不可用'); } let totalDeletedCount = 0; for (let i = 0; i < normalizedOrderIds.length; i += 500) { const orderChunk = normalizedOrderIds.slice(i, i + 500); if (orderChunk.length === 0) { continue; } const deletedCount = await matchModel.destroy({ where: { warehouse_id: normalizedWarehouseId, order_id: { [Op.in]: orderChunk }, }, }); totalDeletedCount += Number(deletedCount || 0); } return totalDeletedCount; } /** * 异步处理订单变更后的波次策略快速扫描副表清理与触发。 * * @param {number|string} [warehouseId=0] 仓库ID。 * @param {Array|number|string} [orderIds=[]] 订单ID集合。 * @param {Object} [options={}] 处理选项。 * @param {boolean} [options.triggerScan=false] 是否触发快速扫描。 * @param {string} [options.source=''] 调用来源。 * @return {void} 无返回值。 */ enqueueWaveStrategyQuickScanPostOrderChange(warehouseId = 0, orderIds = [], options = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedOrderIds = this.normalizeIdsInput(orderIds); if (normalizedOrderIds.length === 0) { return; } const normalizedOptions = this.isPlainObject(options) ? options : {}; const triggerScan = this.normalizeBoolean(normalizedOptions.triggerScan, false); const source = String(normalizedOptions.source || '').trim(); setImmediate(() => { Promise.resolve() .then(async () => { const deletedCount = await this.cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds( normalizedWarehouseId, normalizedOrderIds ); if (triggerScan) { await this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId, { orderIds: normalizedOrderIds, }); } this.ctx.logger.info('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理完成', { warehouseId: normalizedWarehouseId, orderCount: normalizedOrderIds.length, deletedCount, triggerScan, source, }); }) .catch(error => { this.ctx.logger.warn('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理失败,不影响主流程', { warehouseId: normalizedWarehouseId, orderCount: normalizedOrderIds.length, triggerScan, source, error: error && error.message ? error.message : `${error}`, }); }); }); } /** * 执行快速扫描核心流程。 * * @param {Object} [options={}] 执行参数。 * @param {number} options.warehouseId 仓库ID。 * @param {number} options.strategyVersion 当前策略版本。 * @param {Array} [options.orderIds] 可选订单ID数组。 * @param {string} [options.taskId] 任务ID。 * @return {Promise} 扫描执行结果。 */ async executeWaveStrategyQuickScan(options = {}) { const normalizedOptions = this.isPlainObject(options) ? options : {}; const warehouseId = Number(normalizedOptions.warehouseId || 0); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion); const taskId = String(normalizedOptions.taskId || '').trim(); const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false); const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderRows = await orderModel.findAll({ attributes: [ 'id', 'store_id', 'items_count', 'items_total', 'items_hash', 'items', 'logistics_code', 'sys_logistics_code', 'logistics_name', 'province', 'sys_platform_code', 'source_platform_code', ], where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds, forceRescan), raw: true, }); const scanResult = await runWaveStrategyQuickScanRunner({ orders: orderRows, strategyList, getStructureKey: order => this.getWaveStrategyQuickScanStructureKey(order), getExpressKey: order => this.getWaveStrategyQuickScanExpressKey(order), getMatchedStrategyIds: (order, normalizedStrategyList, context) => this.getWaveStrategyQuickScanMatchedStrategyIds( order, normalizedStrategyList, context ), isOrderMatched: (order, normalizedStrategyList, context) => this.isWaveStrategyQuickScanOrderMatched( order, normalizedStrategyList, context ), onProgress: taskId ? async payload => { const totalOrderCount = Number(payload && payload.totalOrderCount || 0); const processedOrderCount = Number(payload && payload.processedOrderCount || 0); const matchedOrderCount = Number(payload && payload.matchedOrderCount || 0); const unmatchedOrderCount = Number(payload && payload.unmatchedOrderCount || 0); const progressPercent = totalOrderCount > 0 ? Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)) : 0; await this.setWaveStrategyQuickScanTaskProgress(taskId, 'running', { warehouse_id: warehouseId, total_order_count: totalOrderCount, processed_order_count: processedOrderCount, matched_order_count: matchedOrderCount, unmatched_order_count: unmatchedOrderCount, progress_percent: progressPercent, }); } : null, }); const matchedOrderIds = this.normalizeIdsInput(scanResult.matchedOrderIds); const unmatchedOrderIds = this.normalizeIdsInput(scanResult.unmatchedOrderIds); const matchedStrategyIdsByOrder = this.isPlainObject(scanResult.matchedStrategyIdsByOrder) ? Object.keys(scanResult.matchedStrategyIdsByOrder).reduce((acc, key) => { const orderId = Number(key); if (!Number.isInteger(orderId) || orderId <= 0) { return acc; } const rawStrategyIds = scanResult.matchedStrategyIdsByOrder[key]; const normalizedStrategyIds = [ ...new Set((Array.isArray(rawStrategyIds) ? rawStrategyIds : []) .map(item => Number(item)) .filter(item => Number.isInteger(item) && item > 0)) ]; acc[orderId] = normalizedStrategyIds; return acc; }, {}) : {}; const scanScopeOrderIds = orderIds.length > 0 ? orderIds : [ ...new Set([ ...matchedOrderIds, ...unmatchedOrderIds ]) ]; await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { wave_strategy_version: strategyVersion, wave_scan_result: 1, }); await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { wave_strategy_version: strategyVersion, wave_scan_result: 2, }); await this.syncWaveStrategyQuickScanMatchedStrategies( warehouseId, scanScopeOrderIds, matchedStrategyIdsByOrder ); return { strategyVersion, totalOrderCount: Number(scanResult.totalOrderCount || 0), processedOrderCount: Number(scanResult.processedOrderCount || 0), matchedOrderCount: matchedOrderIds.length, unmatchedOrderCount: unmatchedOrderIds.length, matchedOrderIds, unmatchedOrderIds, matchedStrategyIdsByOrder, }; } /** * 执行波次策略快速扫描后台任务。 * * 扫描范围:当前仓库 + step != 0 + wave_id = 0 + wave_strategy_version != 当前策略版本。 * * @param {Object} [params={}] 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID。 * @param {Array} [params.orderIds] 订单ID数组(驼峰写法)。 * @param {Array} [params.order_ids] 订单ID数组(下划线写法)。 * @param {Array} [params.ids] 订单ID数组(兼容写法)。 * @return {Promise} 无返回值。 */ async runWaveStrategyQuickScanTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getWaveStrategyQuickScanTaskProgress(normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', }); return; } const startTime = Date.now(); await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId, { state: 'running', }); await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_order_count: 0, processed_order_count: 0, matched_order_count: 0, unmatched_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, error: '', error_code: '', result: null, }); try { const normalizedParams = this.isPlainObject(params) ? params : {}; const rawOrderIds = normalizedParams.orderIds !== undefined ? normalizedParams.orderIds : normalizedParams.order_ids !== undefined ? normalizedParams.order_ids : normalizedParams.ids; const orderIds = this.normalizeIdsInput(rawOrderIds); const forceRescan = this.normalizeBoolean( normalizedParams.forceRescan ?? normalizedParams.force_rescan, false ); const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') ); const scanResult = await this.executeWaveStrategyQuickScan({ warehouseId, strategyVersion, orderIds, taskId: normalizedTaskId, forceRescan, }); if (scanResult.totalOrderCount === 0) { const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_order_count: 0, processed_order_count: 0, matched_order_count: 0, unmatched_order_count: 0, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { strategy_version: strategyVersion, duration_ms: durationMs, message: '未找到需要扫描的订单', }, }); return; } const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_order_count: scanResult.totalOrderCount, processed_order_count: scanResult.processedOrderCount, matched_order_count: scanResult.matchedOrderCount, unmatched_order_count: scanResult.unmatchedOrderCount, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { strategy_version: strategyVersion, total_order_count: scanResult.totalOrderCount, processed_order_count: scanResult.processedOrderCount, matched_order_count: scanResult.matchedOrderCount, unmatched_order_count: scanResult.unmatchedOrderCount, matched_order_ids: scanResult.matchedOrderIds, unmatched_order_ids: scanResult.unmatchedOrderIds, duration_ms: durationMs, message: '波次策略快速扫描完成', }, }); } catch (error) { await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_STRATEGY_QUICK_SCAN_FAILED', }); } finally { await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId); // 方案 C:扫描完成后检查是否有新订单需要扫描 try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const currentVersion = this.normalizeWaveStrategyQuickScanVersion( this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') ); const pendingCount = await orderModel.count({ where: { warehouse_id: warehouseId, step: { [Op.ne]: 0 }, wave_id: 0, intercept_status: 'none', lock_status: 'none', print_status: { [Op.ne]: 'fin' }, [Op.or]: [ { wave_strategy_version: { [Op.ne]: currentVersion } }, { wave_strategy_version: { [Op.is]: null } }, ], }, }); if (pendingCount > 0) { this.ctx.logger.info( '[wave.runWaveStrategyQuickScanTask] 检测到遗漏订单,触发新一轮扫描', { warehouseId, previousTaskId: normalizedTaskId, pendingCount, } ); setImmediate(() => { this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(error => { this.ctx.logger.warn( '[wave.runWaveStrategyQuickScanTask] 触发新一轮扫描失败', { warehouseId, error: error && error.message ? error.message : `${error}`, } ); }); }); } } catch (checkError) { this.ctx.logger.warn( '[wave.runWaveStrategyQuickScanTask] 遗漏订单检查失败', { warehouseId, taskId: normalizedTaskId, error: checkError && checkError.message ? checkError.message : `${checkError}`, } ); } } } /** * 批量更新快速扫描结果。 * * @param {Object} orderModel 订单模型。 * @param {Array} orderIds 订单ID数组。 * @param {Object} updatePayload 更新字段。 * @return {Promise} 无返回值。 */ async batchUpdateWaveStrategyQuickScanOrders(orderModel, orderIds = [], updatePayload = {}) { const normalizedOrderIds = this.normalizeIdsInput(orderIds); if (normalizedOrderIds.length === 0) { return; } for (let i = 0; i < normalizedOrderIds.length; i += 500) { const chunkIds = normalizedOrderIds.slice(i, i + 500); if (chunkIds.length === 0) { continue; } await orderModel.update(updatePayload, { where: { id: { [Op.in]: chunkIds, }, }, }); } } /** * 生成波次策略快速扫描任务ID。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 任务ID。 */ generateWaveStrategyQuickScanTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const timestamp = Math.floor(Date.now() / 1000); const randomPart = Math.random().toString(36).slice(2, 6); return `wave_quick_scan_${safeWarehouseId}_${timestamp}_${randomPart}`; } /** * 归一化波次策略快速扫描任务ID。 * * @param {Object} [data={}] 请求参数。 * @return {string} 归一化后的任务ID。 */ normalizeWaveStrategyQuickScanTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 获取波次策略快速扫描任务缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getWaveStrategyQuickScanTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入波次策略快速扫描任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {string} state 任务状态。 * @param {Object} payload 进度数据。 * @return {Promise} 无返回值。 */ async setWaveStrategyQuickScanTaskProgress(taskId = '', state = 'submitted', payload = {}) { const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); if (!cacheKey) { return; } const safePayload = this.isPlainObject(payload) ? payload : {}; const mergedPayload = { ...(await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}), ...safePayload, task_id: String(taskId || '').trim(), state: String(state || '').trim() || 'submitted', update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, mergedPayload, WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取波次策略快速扫描任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 缓存对象。 */ async getWaveStrategyQuickScanTaskProgress(taskId = '') { const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 获取波次策略快速扫描仓库锁缓存键。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 缓存键。 */ getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return ''; } return `${WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; } /** * 写入波次策略快速扫描仓库锁。 * * @param {number|string} warehouseId 仓库ID。 * @param {string} taskId 任务ID。 * @param {Object} [extra={}] 附加字段。 * @return {Promise} 无返回值。 */ async setWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '', extra = {}) { const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); const normalizedTaskId = String(taskId || '').trim(); if (!cacheKey || !normalizedTaskId) { return; } const extraPayload = this.isPlainObject(extra) ? extra : {}; const lockPayload = { warehouse_id: Number(warehouseId || 0), task_id: normalizedTaskId, state: String(extraPayload.state || 'running').trim() || 'running', accepted_at: extraPayload.accepted_at || undefined, update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, lockPayload, WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入仓库锁缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取波次策略快速扫描仓库锁。 * * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 锁信息。 */ async getWaveStrategyQuickScanWarehouseLock(warehouseId = 0) { const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取仓库锁缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 清理波次策略快速扫描仓库锁。 * * 仅当当前锁 owner 与传入 taskId 一致时才删除,防止误删并发任务锁。 * * @param {number|string} warehouseId 仓库ID。 * @param {string} [taskId=''] 当前任务ID。 * @return {Promise} 无返回值。 */ async clearWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '') { const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); if (!cacheKey) { return; } try { const cachedLock = await this.app.getCacheAsync(cacheKey); const lockTaskId = String(cachedLock && cachedLock.task_id || '').trim(); const currentTaskId = String(taskId || '').trim(); if (lockTaskId && currentTaskId && lockTaskId !== currentTaskId) { return; } if (typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(cacheKey); } else { await this.app.setCacheAsync(cacheKey, null, 0); } } catch (error) { this.ctx.logger.warn('[wave.waveStrategyQuickScan] 清理仓库锁缓存失败: %s', error && error.message ? error.message : error); } } /** * 将仓库策略版本号归一化为非负整数。 * * @param {*} value 原始版本号。 * @return {number} 归一化版本号。 */ normalizeWaveStrategyQuickScanVersion(value) { const versionNumber = Number(value); if (!Number.isFinite(versionNumber)) { return 0; } const safeVersion = Math.floor(versionNumber); return Number.isInteger(safeVersion) && safeVersion >= 0 ? safeVersion : 0; } /** * 归一化快速扫描策略列表。 * * @param {*} strategyRows 策略行数组。 * @return {Array} 标准化策略列表。 */ normalizeWaveStrategyQuickScanList(strategyRows) { const list = Array.isArray(strategyRows) ? strategyRows : []; return list.map(row => { const normalizedRow = this.isPlainObject(row) ? row : {}; const strategyId = Number(normalizedRow.strategy_id || normalizedRow.strategyId || normalizedRow.id || 0); return { strategy_id: Number.isInteger(strategyId) && strategyId > 0 ? strategyId : null, order_min_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_sku), order_max_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_sku), order_min_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_qty), order_max_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_qty), min_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.min_same_structure), max_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.max_same_structure), allowed_owners: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_owners), allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses, false), allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms, false), require_same_express: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.require_same_express, false), allow_cross_owner: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.allow_cross_owner, true), }; }); } /** * 归一化为可为空的数值。 * * @param {*} value 原始数值。 * @return {number|null} 数值或 null。 */ normalizeWaveStrategyQuickScanNumberOrNull(value) { if (value === undefined || value === null || value === '') { return null; } const normalizedValue = Number(value); if (!Number.isFinite(normalizedValue)) { return null; } return normalizedValue; } /** * 归一化快速扫描布尔值。 * * @param {*} value 原始值。 * @param {boolean} [defaultValue=false] 默认值。 * @return {boolean} 布尔值。 */ normalizeWaveStrategyQuickScanBoolean(value, defaultValue = false) { if (typeof value === 'boolean') { return value; } if (value === undefined || value === null || value === '') { return defaultValue; } const normalizedValue = String(value).trim().toLowerCase(); if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalizedValue)) { return true; } if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalizedValue)) { return false; } return defaultValue; } /** * 归一化快速扫描字符串数组。 * * 支持数组、JSON 字符串、逗号分隔字符串。 * * @param {*} value 原始值。 * @param {boolean} [toLowerCase=true] 是否转为小写,默认 true 保持向后兼容。 * @return {Array} 归一化字符串数组(去重)。 */ normalizeWaveStrategyQuickScanStringList(value, toLowerCase = true) { let rawList = []; if (Array.isArray(value)) { rawList = value; } else if (typeof value === 'string') { const trimmed = value.trim(); if (!trimmed) { rawList = []; } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) { try { const parsed = JSON.parse(trimmed); rawList = Array.isArray(parsed) ? parsed : []; } catch (error) { rawList = trimmed.split(/[,,;|\n\r]+/); } } else { rawList = trimmed.split(/[,,;|\n\r]+/); } } else if (value !== undefined && value !== null) { rawList = [ value ]; } return [ ...new Set(rawList .map(item => { const s = String(item || '').trim(); return toLowerCase ? s.toLowerCase() : s; }) .filter(Boolean)) ]; } /** * 计算订单结构 key(items_hash 优先,其次 items)。 * * @param {Object} order 订单记录。 * @return {string} 结构 key。 */ getWaveStrategyQuickScanStructureKey(order = {}) { const itemsHash = String(order && order.items_hash || '').trim(); if (itemsHash) { return itemsHash; } return String(order && order.items || '').trim(); } /** * 计算订单快递 key。 * * 优先级:sys_logistics_code > logistics_code > logistics_name,与 SQL 中 expressExpr 的 COALESCE 口径保持一致。 * * @param {Object} order 订单记录。 * @return {string} 快递 key(去首尾空格后结果,空值返回空字符串)。 */ getWaveStrategyQuickScanExpressKey(order = {}) { const orderObj = order && typeof order === 'object' ? order : {}; const candidates = [ String(orderObj.sys_logistics_code || '').trim(), String(orderObj.logistics_code || '').trim(), String(orderObj.logistics_name || '').trim(), ]; return candidates.find(Boolean) || ''; } /** * 当 require_same_express=1 时,按快递分组候选订单,仅保留最大快递组的订单。 * * 分组 key 使用 getWaveStrategyQuickScanExpressKey(sys_logistics_code > logistics_code > logistics_name), * 空 key 的订单不参与筛选(直接丢弃)。 * * @param {Array} candidateRows 候选订单数组。 * @return {Array} 按快递筛选后的候选订单数组(仅含最大快递组)。 */ filterCandidateOrdersByRequireSameExpress(candidateRows = []) { const rows = Array.isArray(candidateRows) ? candidateRows : []; if (rows.length === 0) { return []; } const expressGroups = new Map(); for (const row of rows) { const expressKey = this.getWaveStrategyQuickScanExpressKey(row); if (!expressKey) { continue; } if (!expressGroups.has(expressKey)) { expressGroups.set(expressKey, []); } expressGroups.get(expressKey).push(row); } if (expressGroups.size === 0) { return []; } let maxGroup = []; for (const groupOrders of expressGroups.values()) { if (groupOrders.length > maxGroup.length) { maxGroup = groupOrders; } } return maxGroup; } /** * 判断订单是否命中任一快速扫描策略。 * * @param {Object} order 订单记录。 * @param {Array} strategyList 策略列表。 * @param {Object} context 统计上下文。 * @return {boolean} 是否命中。 */ isWaveStrategyQuickScanOrderMatched(order = {}, strategyList = [], context = {}) { const matchedStrategyIds = this.getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context); return matchedStrategyIds.length > 0; } /** * 获取订单命中的快速扫描策略ID列表。 * * 全量遍历 strategyList,不提前返回,收集所有命中策略的 strategy_id。 * * @param {Object} order 订单记录。 * @param {Array} strategyList 策略列表。 * @param {Object} [context={}] 统计上下文。 * @return {Array} 去重后的正整数策略ID列表。 */ getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context = {}) { const list = Array.isArray(strategyList) ? strategyList : []; if (list.length === 0) { return []; } const matchedStrategyIds = []; for (const strategy of list) { if (!this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { continue; } const strategyId = Number(strategy && strategy.strategy_id || 0); if (Number.isInteger(strategyId) && strategyId > 0) { matchedStrategyIds.push(strategyId); } } return [ ...new Set(matchedStrategyIds) ]; } /** * 判断订单是否命中单条快速扫描策略。 * * @param {Object} order 订单记录。 * @param {Object} strategy 策略配置。 * @param {Object} context 统计上下文。 * @return {boolean} 是否命中。 */ isWaveStrategyQuickScanOrderMatchedSingleStrategy(order = {}, strategy = {}, context = {}) { const normalizedOrder = this.isPlainObject(order) ? order : {}; const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map ? context.structurePrimaryOwnerMap : null; const structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); if (!structureKey) { return false; } const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); if (normalizedStrategy.allow_cross_owner === false) { if (structurePrimaryOwnerMap instanceof Map) { const primaryOwnerStoreId = String(structurePrimaryOwnerMap.get(structureKey) || '').trim().toLowerCase(); if (!primaryOwnerStoreId || storeId !== primaryOwnerStoreId) { return false; } } else { const ownerSet = structureStoreSetMap.get(structureKey); if (ownerSet instanceof Set && ownerSet.size > 1) { return false; } } } const itemsCount = Number(normalizedOrder.items_count || 0); const itemsTotal = Number(normalizedOrder.items_total || 0); if (!this.isWaveStrategyQuickScanValueInRange(itemsCount, normalizedStrategy.order_min_sku, normalizedStrategy.order_max_sku)) { return false; } if (!this.isWaveStrategyQuickScanValueInRange(itemsTotal, normalizedStrategy.order_min_qty, normalizedStrategy.order_max_qty)) { return false; } if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { return false; } const expressCandidates = [ String(normalizedOrder.sys_logistics_code || '').trim().toLowerCase(), String(normalizedOrder.logistics_code || '').trim().toLowerCase(), String(normalizedOrder.logistics_name || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_expresses.length > 0) { const allowedLower = (normalizedStrategy.allowed_expresses || []).map(s => String(s).toLowerCase()); const hitExpress = expressCandidates.some(code => allowedLower.includes(code)); if (!hitExpress) { return false; } } const province = String(normalizedOrder.province || '').trim().toLowerCase(); if (normalizedStrategy.allowed_provinces.length > 0 && !normalizedStrategy.allowed_provinces.includes(province)) { return false; } const platformCandidates = [ String(normalizedOrder.sys_platform_code || '').trim().toLowerCase(), String(normalizedOrder.source_platform_code || '').trim().toLowerCase(), ].filter(Boolean); if (normalizedStrategy.allowed_platforms.length > 0) { const allowedPlatformsLower = normalizedStrategy.allowed_platforms.map(s => String(s).toLowerCase()); const hitPlatform = platformCandidates.some(code => allowedPlatformsLower.includes(code)); if (!hitPlatform) { return false; } } return true; } /** * 判断值是否命中区间。 * * @param {number} value 待判断值。 * @param {number|null} min 最小值。 * @param {number|null} max 最大值。 * @return {boolean} 是否命中。 */ isWaveStrategyQuickScanValueInRange(value, min, max) { const normalizedValue = Number(value); if (!Number.isFinite(normalizedValue)) { return false; } const hasMin = Number.isFinite(Number(min)); const hasMax = Number.isFinite(Number(max)); if (hasMin && normalizedValue < Number(min)) { return false; } if (hasMax && normalizedValue > Number(max)) { return false; } return true; } /** * 过滤 singleFetchByIds 中属于团购候选结构的订单。 * * 规则:同结构(items_hash/items)待处理订单数达到最小团购阈值时,视为团购候选。 * 为避免误抓,singleFetchByIds 默认排除这些订单,仅允许显式团购入口处理。 * * @param {Object} orderModel 订单模型。 * @param {number} warehouseId 仓库ID。 * @param {Array} orderRows 待过滤订单行。 * @return {Promise} 需排除的订单ID集合。 */ async resolveGroupCandidateOrderIdsForSingleFetch(orderModel, warehouseId, orderRows = []) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedRows = Array.isArray(orderRows) ? orderRows.filter(row => Number.isInteger(Number(row && row.id || 0)) && Number(row && row.id || 0) > 0) : []; if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedRows.length === 0) { return []; } const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); if (!Number.isInteger(Number(minGroupOrderFetchQuantity)) || Number(minGroupOrderFetchQuantity) <= 1) { return []; } const itemHashValues = [ ...new Set(normalizedRows .map(row => String(row && row.items_hash || '').trim()) .filter(Boolean)) ]; const itemValues = [ ...new Set(normalizedRows .map(row => String(row && row.items || '').trim()) .filter(Boolean)) ]; if (itemHashValues.length === 0 && itemValues.length === 0) { return []; } const candidateWhereList = []; if (itemHashValues.length > 0) { candidateWhereList.push({ items_hash: { [Op.in]: itemHashValues }, }); } if (itemValues.length > 0) { candidateWhereList.push({ items: { [Op.in]: itemValues }, }); } if (candidateWhereList.length === 0) { return []; } const candidateRows = await orderModel.findAll({ attributes: [ 'id', 'items_hash', 'items', 'logistics_name' ], where: { wave_id: 0, step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, [Op.or]: candidateWhereList, }, raw: true, }); const buildItemKey = row => { const itemHash = String(row && row.items_hash || '').trim(); const itemText = String(row && row.items || '').trim(); if (itemHash) { return `items_hash:${itemHash}`; } if (itemText) { return `items:${itemText}`; } return ''; }; const itemCountMap = new Map(); for (const row of Array.isArray(candidateRows) ? candidateRows : []) { const itemKey = buildItemKey(row); if (!itemKey) { continue; } itemCountMap.set(itemKey, Number(itemCountMap.get(itemKey) || 0) + 1); } const excludedOrderIds = []; const normalizedThreshold = Number(minGroupOrderFetchQuantity); for (const row of normalizedRows) { const orderId = Number(row && row.id || 0); const itemKey = buildItemKey(row); if (!itemKey) { continue; } const itemGroupCount = Number(itemCountMap.get(itemKey) || 0); if (itemGroupCount >= normalizedThreshold) { excludedOrderIds.push(orderId); } } return [ ...new Set(excludedOrderIds) ].sort((a, b) => a - b); } /** * 按订单ID集合抓取到一个散单波次。 * * 规则: * 1. 仅处理当前仓库上下文订单; * 2. 传入 ids 中已存在波次(wave_id>0)的订单会被排除; * 3. 不区分快递,所有可抓取订单统一写入同一个新波次; * 4. 除已在波次中的订单外,其余传入且存在的订单均可抓取; * 5. 成功抓取后批量写入订单操作日志。 * * @param {Object} data 请求参数。 * @param {Array|number|string} data.ids 订单ID集合(优先)。 * @param {Array|number|string} data.order_ids 订单ID集合别名。 * @param {Array|number|string} data.orderIds 订单ID集合别名。 * @return {Promise} 抓取结果。 */ async singleFetchByIds(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const logOperator = this.getOrderLogOperator() || {}; const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null; const grabOperator = String(logOperator.name || '').trim() || null; const rawIds = data && ( data.ids !== undefined ? data.ids : data.order_ids !== undefined ? data.order_ids : data.orderIds ); const normalizedIds = this.normalizeIdsInput(rawIds); if (normalizedIds.length === 0) { throw new Error('ids 参数不能为空或格式错误'); } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const transaction = await this.ctx.model.transaction(); try { const orderRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no', 'step', 'status', 'outbound_status', 'items_hash', 'items', 'logistics_name', 'intercept_status', 'lock_status' ], where: { id: { [Op.in]: normalizedIds }, }, raw: true, transaction, lock: transaction.LOCK.UPDATE, }); const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : []; const foundOrderIds = [ ...new Set(normalizedOrderRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; const existingWaveRows = normalizedOrderRows .filter(row => Number(row && row.wave_id || 0) > 0); const excludedExistingWaveOrderIds = [ ...new Set(existingWaveRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); const excludedInterceptedOrderIds = [ ...new Set(normalizedOrderRows .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); const excludedLockedOrderIds = [ ...new Set(normalizedOrderRows .filter(row => this.isLockedOrderStatus(row && row.lock_status)) .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); const fetchableRows = normalizedOrderRows.filter(row => { const orderId = Number(row && row.id || 0); const waveId = Number(row && row.wave_id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return false; } if (waveId > 0) { return false; } // 拦截流程中的订单不允许分配波次 if (this.isInterceptedOrderStatus(row && row.intercept_status)) { return false; } // 已锁定的订单不允许抓取波次 if (this.isLockedOrderStatus(row && row.lock_status)) { return false; } return true; }); const fetchableOrderIds = [ ...new Set(fetchableRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); const notFoundOrderIds = normalizedIds.filter(id => !foundOrderIds.includes(id)); const skippedOrderIds = normalizedIds.filter(id => !fetchableOrderIds.includes(id)); if (fetchableOrderIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, wave_id: 0, wave_no: '', fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, excluded_intercepted_order_ids: excludedInterceptedOrderIds, excluded_locked_order_ids: excludedLockedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); } const singleFetchByIdsWavePrefix = await this.getSingleFetchByIdsWavePrefix(warehouseId); const { waveId, waveNo } = await this.createWaveBatchReady({ warehouseId, totalOrders: fetchableOrderIds.length, itemDetailMachine: `manual_single_ids_${Date.now()}`, itemPartType: 'manual_ids', itemPart: `ids_${fetchableOrderIds.length}`, waveType: 2, distinguishExpress: false, logisticsName: '', itemSnapshotKey: 'manual_single_ids', wavePrefix: singleFetchByIdsWavePrefix, transaction, }); await orderModel.update({ wave_id: waveId, wave_no: waveNo, wave_scope: this.resolveWaveScopeByWaveMeta(2, 0), grab_operator_id: grabOperatorId, grab_operator: grabOperator, }, { where: { id: { [Op.in]: fetchableOrderIds }, wave_id: 0, }, transaction, }); const grabbedRows = await orderModel.findAll({ where: { id: { [Op.in]: fetchableOrderIds }, wave_id: waveId, }, attributes: [ 'id' ], raw: true, transaction, }); const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (grabbedOrderIds.length <= 0) { await this.ctx.model.query(` DELETE FROM wms_wave_batch WHERE wave_id = :waveId `, { replacements: { waveId }, transaction, }); await transaction.commit(); return this.success('ok', { ids: normalizedIds, wave_id: 0, wave_no: '', fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); } if (grabbedOrderIds.length !== fetchableOrderIds.length) { await this.ctx.model.query(` UPDATE wms_wave_batch SET total_orders = :totalOrders, update_time = NOW() WHERE wave_id = :waveId `, { replacements: { waveId, totalOrders: grabbedOrderIds.length, }, transaction, }); } await this.rebuildOrderWaveIndex({ warehouseId, waveId, orderIds: grabbedOrderIds, orderModel, transaction, }); await transaction.commit(); await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ orderId, operationCode: 'ORDER_WAVE_ASSIGN', message: `订单被分配到波次 ${waveNo}`, })), { warehouseId, scene: 'singleFetchByIds', }); this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { triggerScan: false, source: 'singleFetchByIds', }); return this.success('ok', { ids: normalizedIds, wave_id: waveId, wave_no: waveNo, fetched_order_ids: grabbedOrderIds, fetched_order_count: grabbedOrderIds.length, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, excluded_intercepted_order_ids: excludedInterceptedOrderIds, excluded_locked_order_ids: excludedLockedOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); } catch (error) { await transaction.rollback(); throw error; } } /** * 批量将订单从波次中移出。 * * 仅处理当前仓库待处理订单中 step in [1,2,3] 且已分配波次(wave_id>0)的订单。 * 全流程使用事务,确保订单更新与波次统计回写一致。 * * @param {Object} data 请求参数。 * @param {Array|number|string} data.ids 订单ID集合(优先)。 * @param {Array|number|string} data.order_ids 订单ID集合别名。 * @param {Array|number|string} data.orderIds 订单ID集合别名。 * @param {Array|number|string} data.order_id 订单ID集合别名。 * @param {Array|number|string} data.orderId 订单ID集合别名。 * @param {Array|number|string} data.id 订单ID集合别名。 * @return {Promise} 批量移出结果。 */ async batchRemoveOrders(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const rawIds = data && ( data.ids !== undefined ? data.ids : data.order_ids !== undefined ? data.order_ids : data.orderIds !== undefined ? data.orderIds : data.order_id !== undefined ? data.order_id : data.orderId !== undefined ? data.orderId : data.id ); const normalizedIds = this.normalizeIdsInput(rawIds); if (normalizedIds.length === 0) { throw new Error('ids 参数不能为空或格式错误'); } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const removableRowsForCheck = await orderModel.findAll({ attributes: [ 'wave_id' ], where: { id: { [Op.in]: normalizedIds }, step: { [Op.in]: [ 1, 2, 3 ] }, wave_id: { [Op.gt]: 0 }, }, raw: true, }); const affectedWaveIdsForCheck = [ ...new Set((Array.isArray(removableRowsForCheck) ? removableRowsForCheck : []) .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; if (affectedWaveIdsForCheck.length > 0) { const activeTaskWaves = await this.ctx.model.query( `SELECT ptw.wave_id FROM wms_wave_pick_task_wave ptw INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id WHERE ptw.wave_id IN (:waveIds) AND pt.status IN (0, 1) LIMIT 1`, { replacements: { waveIds: affectedWaveIdsForCheck }, type: this.ctx.model.QueryTypes.SELECT, } ); if (activeTaskWaves.length > 0) { throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); } } const transaction = await this.ctx.model.transaction(); try { const removableRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no' ], where: { id: { [Op.in]: normalizedIds }, step: { [Op.in]: [ 1, 2, 3 ] }, wave_id: { [Op.gt]: 0 }, }, raw: true, transaction, }); const removableOrderRows = Array.isArray(removableRows) ? removableRows : []; const removablePendingIds = [ ...new Set(removableOrderRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; const removedOrderIds = [ ...new Set(removablePendingIds) ]; const affectedWaveIds = [ ...new Set(removableOrderRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; const removeOrderLogItems = removableOrderRows .map(row => { const orderId = Number(row && row.id || 0); const waveNo = String(row && row.wave_no || '').trim() || '未知波次'; if (!Number.isInteger(orderId) || orderId <= 0) { return null; } return { orderId, operationCode: 'ORDER_WAVE_REMOVE', message: `订单从波次 ${waveNo} 中移除`, }; }) .filter(Boolean); if (removablePendingIds.length === 0 || affectedWaveIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, removed_order_ids: [], removed_order_count: 0, affected_wave_ids: [], updated_wave_ids: [], emptied_wave_ids: [], }); } const orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', wave_scope: 0, wave_strategy_version: 0, wave_scan_result: 0, }, { where: { id: { [Op.in]: removablePendingIds }, }, transaction, }); const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); // 重建受影响波次的订单索引(wave_index 重新排序),并获取各波次剩余订单数量 const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: affectedWaveIds, orderModel, transaction, }); const updatedWaveIds = []; const emptiedWaveIds = []; for (const waveId of affectedWaveIds) { const remainingCount = Number(remainingCountMap.get(waveId) || 0); if (remainingCount > 0) { updatedWaveIds.push(waveId); } else { emptiedWaveIds.push(waveId); } } for (const waveId of updatedWaveIds) { const remainingCount = Number(remainingCountMap.get(waveId) || 0); const updateWaveSql = ` UPDATE wms_wave_batch SET total_orders = :remainingCount, processed_orders = LEAST(processed_orders, :remainingCount), update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id = :waveId `; await this.ctx.model.query(updateWaveSql, { replacements: { warehouseId, waveId, remainingCount, }, transaction, }); } if (emptiedWaveIds.length > 0) { const emptyWaveSql = ` UPDATE wms_wave_batch SET total_orders = 0, processed_orders = 0, wave_status = -1, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) `; await this.ctx.model.query(emptyWaveSql, { replacements: { warehouseId, waveIds: emptiedWaveIds, }, transaction, }); } await transaction.commit(); await this.batchCreateOrderOperationLogs(removeOrderLogItems, { warehouseId, scene: 'batchRemoveOrders', }); this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { triggerScan: true, source: 'batchRemoveOrders', }); return this.success('ok', { ids: normalizedIds, removed_order_ids: removedOrderIds, removed_order_count: Number.isInteger(updatedOrderCount) && updatedOrderCount > 0 ? updatedOrderCount : 0, affected_wave_ids: affectedWaveIds, updated_wave_ids: updatedWaveIds, emptied_wave_ids: emptiedWaveIds, }); } catch (error) { await transaction.rollback(); throw error; } } /** * 强制重排指定波次的订单索引(wave_index)。 * * 用于修正历史数据中因各种原因导致的 wave_index 不连续问题。 * 内部调用 replaceOrderWaveIndexByWaveIds 完成索引重建,并同步更新 wms_wave_batch.total_orders。 * * @param {Object} data 请求参数。 * @param {Array|number|string} [data.wave_ids] 波次ID集合。 * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 * @return {Promise} 重排结果,含各波次重排前后的订单数量。 */ async resortWaveIndex(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const rawWaveIds = data && ( data.wave_ids !== undefined ? data.wave_ids : data.waveIds !== undefined ? data.waveIds : data.wave_id !== undefined ? data.wave_id : data.waveId !== undefined ? data.waveId : null ); const normalizedWaveIds = this.normalizeIdsInput(rawWaveIds); if (normalizedWaveIds.length === 0) { throw new Error('wave_ids 参数不能为空或格式错误'); } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const transaction = await this.ctx.model.transaction(); try { // 重排前记录各波次每单的 wave_index,用于对比是否实际发生重排 const beforeRows = await this.ctx.model.query(` SELECT wave_id, order_id, wave_index FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) ORDER BY wave_id, order_id `, { replacements: { warehouseId, waveIds: normalizedWaveIds }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const beforeIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) const beforeCountMap = new Map(); for (const row of (Array.isArray(beforeRows) ? beforeRows : [])) { const waveId = Number(row && row.wave_id || 0); const orderId = Number(row && row.order_id || 0); const waveIndex = Number(row && row.wave_index || 0); if (!Number.isInteger(waveId) || waveId <= 0) continue; if (!beforeIndexMap.has(waveId)) beforeIndexMap.set(waveId, new Map()); if (Number.isInteger(orderId) && orderId > 0) { beforeIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); } beforeCountMap.set(waveId, (beforeCountMap.get(waveId) || 0) + 1); } // 重建波次索引(内部先删后插,wave_index 从 1 开始连续编号) const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: normalizedWaveIds, orderModel, transaction, }); // 重排后查询各波次每单的 wave_index,用于对比是否实际发生变化 const afterRows = await this.ctx.model.query(` SELECT wave_id, order_id, wave_index FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) ORDER BY wave_id, order_id `, { replacements: { warehouseId, waveIds: normalizedWaveIds }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const afterIndexMap = new Map(); // waveId -> Map(orderId -> wave_index) for (const row of (Array.isArray(afterRows) ? afterRows : [])) { const waveId = Number(row && row.wave_id || 0); const orderId = Number(row && row.order_id || 0); const waveIndex = Number(row && row.wave_index || 0); if (!Number.isInteger(waveId) || waveId <= 0) continue; if (!afterIndexMap.has(waveId)) afterIndexMap.set(waveId, new Map()); if (Number.isInteger(orderId) && orderId > 0) { afterIndexMap.get(waveId).set(orderId, Number.isInteger(waveIndex) ? waveIndex : 0); } } // 同步更新 wms_wave_batch.total_orders const waveDetails = []; for (const waveId of normalizedWaveIds) { const remainingCount = Number(remainingCountMap.get(waveId) || 0); const beforeCount = Number(beforeCountMap.get(waveId) || 0); if (remainingCount > 0) { await this.ctx.model.query(` UPDATE wms_wave_batch SET total_orders = :remainingCount, processed_orders = LEAST(processed_orders, :remainingCount), update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id = :waveId `, { replacements: { warehouseId, waveId, remainingCount }, transaction, }); } else { await this.ctx.model.query(` UPDATE wms_wave_batch SET total_orders = 0, processed_orders = 0, wave_status = -1, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id = :waveId `, { replacements: { warehouseId, waveId }, transaction, }); } // 对比每单重排前后的 wave_index,判断是否实际发生变化 const beforeOrderMap = beforeIndexMap.get(waveId) || new Map(); const afterOrderMap = afterIndexMap.get(waveId) || new Map(); const allOrderIds = new Set([ ...beforeOrderMap.keys(), ...afterOrderMap.keys() ]); let hasChanged = beforeCount !== remainingCount; if (!hasChanged) { for (const oid of allOrderIds) { if (beforeOrderMap.get(oid) !== afterOrderMap.get(oid)) { hasChanged = true; break; } } } waveDetails.push({ wave_id: waveId, before_index_count: beforeCount, after_index_count: remainingCount, reordered: hasChanged, }); } await transaction.commit(); const totalBefore = waveDetails.reduce((sum, w) => sum + w.before_index_count, 0); const totalAfter = waveDetails.reduce((sum, w) => sum + w.after_index_count, 0); return this.success('ok', { warehouse_id: warehouseId, wave_count: normalizedWaveIds.length, total_before_index_count: totalBefore, total_after_index_count: totalAfter, waves: waveDetails, }); } catch (error) { await transaction.rollback(); throw error; } } /** * 批量移除异常订单任务提交接口。 * * 仅处理当前登录仓库下命中波次中的异常订单,提交后异步执行。 * 异常判定与订单模块待处理异常定义保持一致:仅 step=3。 * 实际移除动作复用既有 batchRemoveOrders 流水线,不重复实现解绑逻辑。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 * @param {number|string} [data.warehouseId] 仓库ID(驼峰写法)。 * @param {Array|number|string} [data.wave_ids] 波次ID集合(下划线写法,优先)。 * @param {Array|number|string} [data.waveIds] 波次ID集合(驼峰写法)。 * @param {Array|number|string} [data.ids] 波次ID集合(兼容写法)。 * @param {string} [data.task_id] 外部指定任务ID(用于幂等提交)。 * @param {string} [data.taskId] 外部指定任务ID(驼峰写法)。 * @return {Promise} 任务提交结果。 */ async batchRemoveExceptionOrders(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const requestWarehouseId = Number(data && (data.warehouse_id ?? data.warehouseId) || contextWarehouseId); if (!Number.isInteger(requestWarehouseId) || requestWarehouseId <= 0) { throw new Error('warehouse_id 参数不合法'); } if (requestWarehouseId !== contextWarehouseId) { throw new Error('warehouse_id 与当前仓库上下文不一致'); } const warehouseId = requestWarehouseId; const normalizedWaveIds = this.normalizeBatchRemoveExceptionOrdersWaveIds(data); if (normalizedWaveIds.length === 0) { throw new Error('wave_ids 参数不能为空或格式错误'); } const requestedTaskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); const taskId = requestedTaskId || this.generateBatchRemoveExceptionOrdersTaskId(warehouseId); const existingTask = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); if (existingTask) { return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', message: '批量移除异常订单任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } const acceptedAt = new Date().toISOString(); await this.setBatchRemoveExceptionOrdersTaskProgress(taskId, 'submitted', { warehouse_id: warehouseId, wave_ids: normalizedWaveIds.join(','), wave_id_list: normalizedWaveIds, total_wave_count: normalizedWaveIds.length, processed_wave_count: 0, total_order_count: 0, processed_order_count: 0, removed_order_count: 0, progress_percent: 0, submitted_at: Date.now(), accepted_at: acceptedAt, result: null, error: '', error_code: '', }); this.ctx.logger.info('[wave.batchRemoveExceptionOrders] 任务提交成功', { taskId, warehouseId, waveCount: normalizedWaveIds.length, }); setImmediate(() => { this.runBatchRemoveExceptionOrdersTask({ taskId, warehouseId, waveIds: normalizedWaveIds, }).catch(error => { this.ctx.logger.error('[wave.batchRemoveExceptionOrders] 后台任务异常', { taskId, warehouseId, waveCount: normalizedWaveIds.length, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return this.success('ok', { status: 'success', task_id: taskId, warehouse_id: warehouseId, message: '批量移除异常订单任务已提交。', accepted_at: acceptedAt, }); } /** * 查询批量移除异常订单任务进度。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度响应。 */ async batchRemoveExceptionOrdersTaskProgress(data = {}) { const taskId = this.normalizeBatchRemoveExceptionOrdersTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getBatchRemoveExceptionOrdersTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, state: 'not_found', }); } const state = String(cachedProgress.state || 'submitted').trim() || 'submitted'; const payload = { task_id: taskId, state, warehouse_id: Number(cachedProgress.warehouse_id || 0), submitted_at: cachedProgress.submitted_at || null, start_time: cachedProgress.start_time || null, end_time: cachedProgress.end_time || null, }; if (state === 'submitted' || state === 'running') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); } if (state === 'success') { const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; payload.progress_percent = Number(cachedProgress.progress_percent || 100); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); payload.total_order_count = Number(result.total_order_count || 0); payload.processed_order_count = Number(result.processed_order_count || 0); payload.removed_order_count = Number(result.removed_order_count || 0); payload.removed_order_ids = Array.isArray(result.removed_order_ids) ? result.removed_order_ids : []; payload.affected_wave_ids = Array.isArray(result.affected_wave_ids) ? result.affected_wave_ids : []; payload.updated_wave_ids = Array.isArray(result.updated_wave_ids) ? result.updated_wave_ids : []; payload.emptied_wave_ids = Array.isArray(result.emptied_wave_ids) ? result.emptied_wave_ids : []; payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0); } if (state === 'failed') { payload.progress_percent = Number(cachedProgress.progress_percent || 0); payload.total_wave_count = Number(cachedProgress.total_wave_count || 0); payload.processed_wave_count = Number(cachedProgress.processed_wave_count || 0); payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); payload.total_order_count = Number(cachedProgress.total_order_count || 0); payload.removed_order_count = Number(cachedProgress.removed_order_count || 0); payload.error_message = String(cachedProgress.error || '').trim(); payload.error_code = String(cachedProgress.error_code || '').trim() || 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED'; payload.failed_wave_id = Number(cachedProgress.failed_wave_id || 0); payload.failed_wave_no = String(cachedProgress.failed_wave_no || '').trim(); payload.duration_ms = Number(cachedProgress.duration_ms || 0); } return this.success('ok', payload); } /** * 生成可追踪的批量取消任务ID。 * * 格式:wave_cancel_{warehouseId}_{timestamp}_{rand}。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 任务ID。 */ generateBatchCancelTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const timestamp = Math.floor(Date.now() / 1000); const randomPart = Math.random().toString(36).slice(2, 6); return `wave_cancel_${safeWarehouseId}_${timestamp}_${randomPart}`; } /** * 归一化批量取消任务ID。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {string} 归一化后的任务ID。 */ normalizeBatchCancelTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 生成可追踪的批量移除异常订单任务ID。 * * 格式:wave_remove_exception_orders_{warehouseId}_{timestamp}_{rand}。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 任务ID。 */ generateBatchRemoveExceptionOrdersTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const timestamp = Math.floor(Date.now() / 1000); const randomPart = Math.random().toString(36).slice(2, 6); return `wave_remove_exception_orders_${safeWarehouseId}_${timestamp}_${randomPart}`; } /** * 归一化批量移除异常订单任务ID。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {string} 归一化后的任务ID。 */ normalizeBatchRemoveExceptionOrdersTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 归一化批量移除异常订单的波次ID参数。 * * @param {Object} data 请求参数。 * @return {Array} 归一化后的波次ID数组。 */ normalizeBatchRemoveExceptionOrdersWaveIds(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const rawWaveIds = normalizedData.wave_ids !== undefined ? normalizedData.wave_ids : normalizedData.waveIds !== undefined ? normalizedData.waveIds : normalizedData.ids !== undefined ? normalizedData.ids : normalizedData.wave_id !== undefined ? normalizedData.wave_id : normalizedData.waveId; return this.normalizeIdsInput(rawWaveIds); } /** * 获取批量移除异常订单任务缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getBatchRemoveExceptionOrdersTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入批量移除异常订单任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {string} status 任务状态(submitted|running|success|failed)。 * @param {Object} data 进度或结果数据。 * @return {Promise} 无返回值。 */ async setBatchRemoveExceptionOrdersTaskProgress(taskId = '', status = 'submitted', data = {}) { const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); if (!cacheKey) { return; } const safeData = this.isPlainObject(data) ? data : {}; const mergedPayload = { ...(await this.getBatchRemoveExceptionOrdersTaskProgress(taskId) || {}), ...safeData, task_id: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_REMOVE_EXCEPTION_ORDERS_TASK_CACHE_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取批量移除异常订单任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 缓存对象。 */ async getBatchRemoveExceptionOrdersTaskProgress(taskId = '') { const cacheKey = this.getBatchRemoveExceptionOrdersTaskCacheKey(taskId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.batchRemoveExceptionOrders] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 判断订单是否属于异常可移除范围。 * * 与订单模块“待处理异常”语义保持一致:仅 step=3。 * * @param {Object} row 订单行数据。 * @return {boolean} 是否为异常可移除订单。 */ isExceptionRemovableOrder(row = {}) { const step = Number(row && row.step || 0); return step === 3; } /** * 执行批量移除异常订单后台任务。 * * 先按波次聚合异常订单,再复用 batchRemoveOrders 流水线执行解绑与波次统计回写。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 * @return {Promise} 无返回值。 */ async runBatchRemoveExceptionOrdersTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); const waveIds = this.normalizeIdsInput( cachedTask && cachedTask.wave_ids !== undefined ? cachedTask.wave_ids : params && params.waveIds ); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', }); return; } if (waveIds.length === 0) { await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, end_time: Date.now(), error: 'wave_ids 参数不能为空或格式错误', error_code: 'INVALID_WAVE_IDS', }); return; } const startTime = Date.now(); await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, total_wave_count: waveIds.length, processed_wave_count: 0, total_order_count: 0, processed_order_count: 0, removed_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', failed_wave_id: 0, failed_wave_no: '', }); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no', 'step' ], where: { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }, raw: true, }); const waveInfoById = new Map(); const exceptionOrderIds = []; for (const row of (Array.isArray(orderRows) ? orderRows : [])) { const orderId = Number(row && row.id || 0); const waveId = Number(row && row.wave_id || 0); const waveNo = String(row && row.wave_no || '').trim(); if (!Number.isInteger(orderId) || orderId <= 0 || !Number.isInteger(waveId) || waveId <= 0) { continue; } if (!waveInfoById.has(waveId)) { waveInfoById.set(waveId, { wave_id: waveId, wave_no: waveNo || '未知波次', }); } if (this.isExceptionRemovableOrder(row)) { exceptionOrderIds.push(orderId); } } const targetWaves = waveIds .map(waveId => waveInfoById.get(waveId)) .filter(Boolean); const normalizedExceptionOrderIds = [ ...new Set(exceptionOrderIds) ]; await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: targetWaves.length, total_order_count: normalizedExceptionOrderIds.length, processed_order_count: normalizedExceptionOrderIds.length, progress_percent: targetWaves.length === 0 ? 100 : 80, }); if (normalizedExceptionOrderIds.length === 0) { const durationMs = Date.now() - startTime; await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: targetWaves.length, total_order_count: 0, processed_order_count: 0, removed_order_count: 0, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, removed_order_ids: [], removed_order_count: 0, affected_wave_ids: [], updated_wave_ids: [], emptied_wave_ids: [], total_order_count: 0, processed_order_count: 0, duration_ms: durationMs, message: '未找到可移除的异常订单', }, }); return; } const removeResult = await this.batchRemoveOrders({ ids: normalizedExceptionOrderIds, }); const resultPayload = this.isPlainObject(removeResult) ? removeResult : {}; const removedOrderIds = Array.isArray(resultPayload.removed_order_ids) ? resultPayload.removed_order_ids : []; const affectedWaveIds = Array.isArray(resultPayload.affected_wave_ids) ? resultPayload.affected_wave_ids : []; const updatedWaveIds = Array.isArray(resultPayload.updated_wave_ids) ? resultPayload.updated_wave_ids : []; const emptiedWaveIds = Array.isArray(resultPayload.emptied_wave_ids) ? resultPayload.emptied_wave_ids : []; const removedOrderCount = Number(resultPayload.removed_order_count || removedOrderIds.length || 0); const durationMs = Date.now() - startTime; await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: targetWaves.length, total_order_count: normalizedExceptionOrderIds.length, processed_order_count: normalizedExceptionOrderIds.length, removed_order_count: removedOrderCount, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, removed_order_ids: removedOrderIds, removed_order_count: removedOrderCount, affected_wave_ids: affectedWaveIds, updated_wave_ids: updatedWaveIds, emptied_wave_ids: emptiedWaveIds, total_order_count: normalizedExceptionOrderIds.length, processed_order_count: normalizedExceptionOrderIds.length, duration_ms: durationMs, message: `已移除 ${removedOrderCount} 条异常订单`, }, }); } catch (error) { await this.setBatchRemoveExceptionOrdersTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_REMOVE_EXCEPTION_ORDERS_FAILED', }); } } /** * 归一化批量取消波次ID参数。 * * @param {Object} data 请求参数。 * @return {Array} 归一化后的波次ID数组。 */ normalizeBatchCancelWaveIds(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const rawWaveIds = normalizedData.wave_ids !== undefined ? normalizedData.wave_ids : normalizedData.waveIds !== undefined ? normalizedData.waveIds : normalizedData.ids !== undefined ? normalizedData.ids : normalizedData.wave_id !== undefined ? normalizedData.wave_id : normalizedData.waveId; return this.normalizeIdsInput(rawWaveIds); } /** * 获取批量取消任务缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getBatchCancelTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${BATCH_CANCEL_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入批量取消任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {string} status 任务状态(submitted|running|success|failed)。 * @param {Object} data 进度或结果数据。 * @return {Promise} 无返回值。 */ async setBatchCancelTaskProgress(taskId = '', status = 'submitted', data = {}) { const cacheKey = this.getBatchCancelTaskCacheKey(taskId); if (!cacheKey) { return; } const safeData = this.isPlainObject(data) ? data : {}; const mergedPayload = { ...(await this.getBatchCancelTaskProgress(taskId) || {}), ...safeData, task_id: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_CANCEL_TASK_CACHE_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.batchCancel] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取批量取消任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 缓存对象。 */ async getBatchCancelTaskProgress(taskId = '') { const cacheKey = this.getBatchCancelTaskCacheKey(taskId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.batchCancel] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 执行批量解除波次后台任务。 * * 逐个波次处理:波次已进入拣货中及后续环节、或波次内存在已拣货完成/拣货中的订单时, * 跳过该波次并记录到 skipped_waves,避免删除已拣货波次;其余波次正常取消。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 * @return {Promise} 无返回值。 */ async runBatchCancelTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getBatchCancelTaskProgress(normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); const waveIds = this.normalizeIdsInput( cachedTask && cachedTask.wave_ids !== undefined ? cachedTask.wave_ids : params && params.waveIds ); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', }); return; } if (waveIds.length === 0) { await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, end_time: Date.now(), error: 'wave_ids 参数不能为空或格式错误', error_code: 'INVALID_WAVE_IDS', }); return; } const startTime = Date.now(); await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, total_wave_count: waveIds.length, processed_wave_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', failed_wave_id: 0, failed_wave_no: '', }); const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const querySql = ` SELECT wave_id, wave_no, wave_status FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:ids) `; const queryRows = await this.ctx.model.query(querySql, { replacements: { warehouseId, ids: waveIds, }, type: this.ctx.model.QueryTypes.SELECT, }); const targetWaves = (Array.isArray(queryRows) ? queryRows : []) .map(row => ({ wave_id: Number(row && row.wave_id || 0), wave_no: String(row && row.wave_no || '').trim(), wave_status: Number(row && row.wave_status || 0), })) .filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0); if (targetWaves.length === 0) { await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: 0, processed_wave_count: 0, progress_percent: 100, end_time: Date.now(), duration_ms: Date.now() - startTime, result: { ids: waveIds, affected_wave_ids: [], affected_order_count: 0, canceled_wave_count: 0, skipped_wave_ids: [], skipped_wave_count: 0, duration_ms: Date.now() - startTime, }, }); return; } let processedWaveCount = 0; let affectedOrderCount = 0; let canceledWaveCount = 0; const affectedWaveIds = []; const removedOrderIdSet = new Set(); const skippedWaves = []; for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); const waveNo = String(wave.wave_no || '').trim() || '未知波次'; const waveStatus = Number(wave.wave_status || 0); // 兜底校验:波次已进入拣货中及后续环节时跳过取消,避免删除已拣货波次 if (waveStatus >= 3) { skippedWaves.push({ wave_id: waveId, wave_no: waveNo, reason: 'wave_status_blocked', wave_status: waveStatus, }); processedWaveCount += 1; await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: processedWaveCount, progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), }); continue; } const transaction = await this.ctx.model.transaction(); try { // 业务规则校验:波次内存在已拣货完成或拣货中的订单时跳过取消,防止删除已拣货波次 const pickedOrderGuardRows = await orderModel.findAll({ attributes: [ 'id', 'pick_status' ], where: { wave_id: waveId, pick_status: { [Op.in]: [ 'padding', 'fin' ] }, }, raw: true, transaction, }); const normalizedPickedOrderGuardRows = Array.isArray(pickedOrderGuardRows) ? pickedOrderGuardRows : []; if (normalizedPickedOrderGuardRows.length > 0) { await transaction.rollback(); skippedWaves.push({ wave_id: waveId, wave_no: waveNo, reason: 'picked_orders_exist', picked_order_count: normalizedPickedOrderGuardRows.length, }); processedWaveCount += 1; await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: processedWaveCount, progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), }); continue; } const affectedOrderRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no' ], where: { wave_id: waveId, }, raw: true, transaction, }); const cancelOrderLogItems = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return null; } return { orderId, operationCode: 'ORDER_WAVE_CANCEL', message: `波次 ${waveNo} 被删除,订单移出波次`, }; }) .filter(Boolean); const orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', wave_scope: 0, wave_strategy_version: 0, wave_scan_result: 0, }, { where: { wave_id: waveId, }, transaction, }); const currentAffectedOrderCount = Number( Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 ); // wave_status < 3 守卫:解波只作用于待拣货口径的波次,避免覆盖并发流程 // (自动终结写入的 5、已进入拣货及后续环节的状态)导致状态互相打架 const cancelSql = ` UPDATE wms_wave_batch SET wave_status = -1, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id = :waveId AND wave_status < 3 `; const cancelResult = await this.ctx.model.query(cancelSql, { replacements: { warehouseId, waveId, }, transaction, }); const cancelMeta = Array.isArray(cancelResult) ? cancelResult[1] : null; const currentCanceledWaveCount = Number( cancelMeta && (cancelMeta.affectedRows || cancelMeta.affectedCount || cancelMeta.rowCount) || 0 ); await this.deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds: [ waveId ], transaction, }); await transaction.commit(); await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { warehouseId, scene: 'batchCancel', }); const currentRemovedOrderIds = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0); for (const orderId of currentRemovedOrderIds) { removedOrderIdSet.add(orderId); } processedWaveCount += 1; affectedOrderCount += Number.isInteger(currentAffectedOrderCount) && currentAffectedOrderCount > 0 ? currentAffectedOrderCount : 0; canceledWaveCount += Number.isInteger(currentCanceledWaveCount) && currentCanceledWaveCount > 0 ? currentCanceledWaveCount : 0; if (currentCanceledWaveCount > 0) { affectedWaveIds.push(waveId); } const progressPercent = Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)); await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: processedWaveCount, progress_percent: progressPercent, }); } catch (error) { await transaction.rollback(); await this.setBatchCancelTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: processedWaveCount, progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), end_time: Date.now(), duration_ms: Date.now() - startTime, failed_wave_id: waveId, failed_wave_no: waveNo, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_CANCEL_FAILED', result: { ids: waveIds, affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, skipped_wave_ids: skippedWaves.map(item => item.wave_id), skipped_wave_count: skippedWaves.length, skipped_waves: skippedWaves, duration_ms: Date.now() - startTime, }, }); return; } } const removedOrderIds = [ ...removedOrderIdSet ].sort((a, b) => a - b); this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { triggerScan: true, source: 'batchCancel', }); const durationMs = Date.now() - startTime; await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: targetWaves.length, processed_wave_count: processedWaveCount, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { ids: waveIds, affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, skipped_wave_ids: skippedWaves.map(item => item.wave_id), skipped_wave_count: skippedWaves.length, skipped_waves: skippedWaves, duration_ms: durationMs, }, }); } /** * 生成可追踪的批次分配快递号任务ID。 * * 格式:wave_allocate_express_{warehouseId}_{timestamp}_{rand}。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 任务ID。 */ generateBatchAllocateExpressTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const timestamp = Math.floor(Date.now() / 1000); const randomPart = Math.random().toString(36).slice(2, 6); return `wave_allocate_express_${safeWarehouseId}_${timestamp}_${randomPart}`; } /** * 归一化批次分配快递号任务ID。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {string} 归一化后的任务ID。 */ normalizeBatchAllocateExpressTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 归一化批次分配快递号波次ID参数。 * * @param {Object} data 请求参数。 * @return {Array} 归一化后的波次ID数组。 */ normalizeBatchAllocateExpressWaveIds(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const rawWaveIds = normalizedData.wave_ids !== undefined ? normalizedData.wave_ids : normalizedData.waveIds !== undefined ? normalizedData.waveIds : normalizedData.ids !== undefined ? normalizedData.ids : normalizedData.wave_id !== undefined ? normalizedData.wave_id : normalizedData.waveId; return this.normalizeIdsInput(rawWaveIds); } /** * 获取批次分配快递号任务缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getBatchAllocateExpressTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入批次分配快递号任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {string} status 任务状态(submitted|running|success|failed)。 * @param {Object} data 进度或结果数据。 * @return {Promise} 无返回值。 */ async setBatchAllocateExpressTaskProgress(taskId = '', status = 'submitted', data = {}) { const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); if (!cacheKey) { return; } const safeData = this.isPlainObject(data) ? data : {}; const mergedPayload = { ...(await this.getBatchAllocateExpressTaskProgress(taskId) || {}), ...safeData, task_id: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', update_time: Date.now(), }; const traceId = this.buildBatchAllocateExpressTraceId(safeData, taskId); try { this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写前', { traceId, taskId: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', warehouseId: Number(mergedPayload.warehouse_id || 0), waveIds: mergedPayload.wave_id_list || mergedPayload.wave_ids || '', totalOrderCount: Number(mergedPayload.total_order_count || 0), processedOrderCount: Number(mergedPayload.processed_order_count || 0), }); await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS); this.ctx.logger.info('[wave.batchAllocateExpress] 缓存回写后', { traceId, taskId: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', }); } catch (error) { this.ctx.logger.warn('[wave.batchAllocateExpress] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取批次分配快递号任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 缓存对象。 */ async getBatchAllocateExpressTaskProgress(taskId = '') { const cacheKey = this.getBatchAllocateExpressTaskCacheKey(taskId); if (!cacheKey) { return null; } try { this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取前', { traceId: this.buildBatchAllocateExpressTraceId({}, taskId), taskId: String(taskId || '').trim(), }); const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-未命中', { traceId: this.buildBatchAllocateExpressTraceId({}, taskId), taskId: String(taskId || '').trim(), }); return null; } this.ctx.logger.info('[wave.batchAllocateExpress] 缓存读取后-命中', { traceId: this.buildBatchAllocateExpressTraceId(cached, taskId), taskId: String(taskId || '').trim(), state: String(cached.state || '').trim() || 'submitted', }); return cached; } catch (error) { this.ctx.logger.warn('[wave.batchAllocateExpress] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 生成可追踪的批次分配储位任务ID。 * * 格式:wave_allocate_storage_{warehouseId}_{timestamp}_{rand}。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 任务ID。 */ generateBatchAllocateStorageTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const timestamp = Math.floor(Date.now() / 1000); const randomPart = Math.random().toString(36).slice(2, 6); return `wave_allocate_storage_${safeWarehouseId}_${timestamp}_${randomPart}`; } /** * 归一化批次分配储位任务ID。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {string} 归一化后的任务ID。 */ normalizeBatchAllocateStorageTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 归一化批次分配储位波次ID参数。 * * @param {Object} data 请求参数。 * @return {Array} 归一化后的波次ID数组。 */ normalizeBatchAllocateStorageWaveIds(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const rawWaveIds = normalizedData.wave_ids !== undefined ? normalizedData.wave_ids : normalizedData.waveIds !== undefined ? normalizedData.waveIds : normalizedData.ids !== undefined ? normalizedData.ids : normalizedData.wave_id !== undefined ? normalizedData.wave_id : normalizedData.waveId; return this.normalizeIdsInput(rawWaveIds); } /** * 归一化批次分配储位任务数量。 * * @param {*} value 原始数量值。 * @param {number} [defaultValue=0] 默认值。 * @return {number} 非负整数数量。 */ normalizeBatchAllocateStorageTaskCount(value, defaultValue = 0) { const normalizedValue = Number(value); if (!Number.isFinite(normalizedValue)) { return Math.max(0, Number(defaultValue || 0)); } const safeValue = Math.floor(normalizedValue); if (!Number.isInteger(safeValue) || safeValue < 0) { return 0; } return safeValue; } /** * 构建批次分配储位 running 状态的进度写入数据。 * * running 阶段的 progress_percent 强制上限 99,避免在任务真正完成前提前显示 100%。 * * @param {Object} payload 进度回调载荷。 * @param {Object} cachedProgress 当前缓存中的任务进度。 * @return {{ total_order_count: number, processed_order_count: number, progress_percent: number }} 进度写入数据。 */ buildBatchAllocateStorageRunningProgressPayload(payload = {}, cachedProgress = {}) { const normalizedPayload = this.isPlainObject(payload) ? payload : {}; const normalizedCache = this.isPlainObject(cachedProgress) ? cachedProgress : {}; const totalOrderCount = this.normalizeBatchAllocateStorageTaskCount( normalizedPayload.total_count, normalizedCache.total_order_count ); const rawProcessedOrderCount = this.normalizeBatchAllocateStorageTaskCount( normalizedPayload.processed_count, normalizedCache.processed_order_count ); const processedOrderCount = totalOrderCount > 0 ? Math.min(rawProcessedOrderCount, totalOrderCount) : rawProcessedOrderCount; const fallbackProgressPercent = this.normalizeBatchAllocateStorageTaskCount( normalizedPayload.progress_percent, normalizedCache.progress_percent ); const calculatedProgressPercent = totalOrderCount > 0 ? Math.round((processedOrderCount / totalOrderCount) * 100) : fallbackProgressPercent; return { total_order_count: totalOrderCount, processed_order_count: processedOrderCount, progress_percent: Math.max(0, Math.min(99, calculatedProgressPercent)), }; } /** * 归一化批次分配储位成功态订单ID列表。 * * @param {*} value 原始订单ID集合。 * @return {Array} 去重后的订单ID列表。 */ normalizeBatchAllocateStorageOrderIds(value) { return [ ...new Set(this.normalizeIdsInput(value)) ]; } /** * 获取批次分配储位任务缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getBatchAllocateStorageTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 获取批次分配储位仓库并发锁键。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 锁键。 */ getBatchAllocateStorageWarehouseLockKey(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return ''; } return `wave_allocate_storage_lock_${normalizedWarehouseId}`; } /** * 尝试获取批次分配储位仓库维度并发锁。 * * 该锁仅在当前 Node.js 进程内生效,用于避免同仓库并发触发多个大事务。 * * @param {number|string} warehouseId 仓库ID。 * @param {string} [taskId=''] 当前任务ID。 * @return {{ acquired: boolean, ownerTaskId: string }} 获取结果。 */ tryAcquireBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); if (!lockKey) { return { acquired: false, ownerTaskId: '', }; } if (BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.has(lockKey)) { return { acquired: false, ownerTaskId: String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(), }; } BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.set(lockKey, String(taskId || '').trim()); return { acquired: true, ownerTaskId: String(taskId || '').trim(), }; } /** * 释放批次分配储位仓库维度并发锁。 * * @param {number|string} warehouseId 仓库ID。 * @param {string} [taskId=''] 当前任务ID。 * @return {void} */ releaseBatchAllocateStorageWarehouseLock(warehouseId = 0, taskId = '') { const lockKey = this.getBatchAllocateStorageWarehouseLockKey(warehouseId); if (!lockKey) { return; } const ownerTaskId = String(BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.get(lockKey) || '').trim(); const normalizedTaskId = String(taskId || '').trim(); if (!ownerTaskId || ownerTaskId === normalizedTaskId) { BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP.delete(lockKey); } } /** * 写入批次分配储位任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {string} status 任务状态(submitted|running|success|failed)。 * @param {Object} data 进度或结果数据。 * @return {Promise} 无返回值。 */ async setBatchAllocateStorageTaskProgress(taskId = '', status = 'submitted', data = {}) { const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); if (!cacheKey) { return; } const safeData = this.isPlainObject(data) ? data : {}; const mergedPayload = { ...(await this.getBatchAllocateStorageTaskProgress(taskId) || {}), ...safeData, task_id: String(taskId || '').trim(), state: String(status || '').trim() || 'submitted', update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.batchAllocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取批次分配储位任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 缓存对象。 */ async getBatchAllocateStorageTaskProgress(taskId = '') { const cacheKey = this.getBatchAllocateStorageTaskCacheKey(taskId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.batchAllocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 判断是否为 business_key 列不存在错误。 * * 兼容 MySQL/Sequelize 常见报错文案,例如: * Unknown column 'business_key' in 'field list' * * @param {Error|Object} error 异常对象。 * @return {boolean} 是否为 business_key 缺列错误。 */ isMissingBusinessKeyColumnError(error) { const messageList = [ error && error.message, error && error.parent && error.parent.message, error && error.original && error.original.message, error && error.sqlMessage, ] .map(item => String(item || '').toLowerCase()) .filter(Boolean); return messageList.some(message => { const hasUnknownColumn = message.includes('unknown column') || message.includes('column does not exist'); const hasBusinessKey = message.includes('business_key'); return hasUnknownColumn && hasBusinessKey; }); } /** * 执行批次分配快递号后台任务。 * * 任务会等待快递分配流水线中所有批次真正完成分配(awaitTasks=true)后 * 才写入 success 状态,避免进度接口在分配尚未完成时提前返回完成。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 * @return {Promise} 无返回值。 */ async runBatchAllocateExpressTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getBatchAllocateExpressTaskProgress(normalizedTaskId); const traceId = this.buildBatchAllocateExpressTraceId(cachedTask || params, normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); const waveIds = this.normalizeIdsInput( cachedTask && cachedTask.wave_ids !== undefined ? cachedTask.wave_ids : params && params.waveIds ); this.ctx.logger.info('[wave.batchAllocateExpress] 后台任务入口', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, paramsSnapshot: { warehouseId: params && params.warehouseId, waveIds: params && params.waveIds, }, }); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-warehouse_id 非法', { traceId, taskId: normalizedTaskId, warehouseId, }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', trace_id: traceId, }); return; } if (waveIds.length === 0) { this.ctx.logger.warn('[wave.batchAllocateExpress] 后台任务参数校验失败-wave_ids 为空', { traceId, taskId: normalizedTaskId, warehouseId, }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, end_time: Date.now(), error: 'wave_ids 参数不能为空或格式错误', error_code: 'INVALID_WAVE_IDS', trace_id: traceId, }); return; } const startTime = Date.now(); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, total_wave_count: waveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', trace_id: traceId, }); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }; let orderRows = []; let useBusinessKeyColumn = true; try { orderRows = await orderModel.findAll({ attributes: [ 'id', 'business_key', 'intercept_status', 'lock_status' ], where: baseOrderWhere, raw: true, }); } catch (error) { if (!this.isMissingBusinessKeyColumnError(error)) { throw error; } useBusinessKeyColumn = false; this.ctx.logger.warn('[wave.batchAllocateExpress] 订单分表缺少 business_key 列,降级为仅查询 id', { traceId, taskId: normalizedTaskId, warehouseId, }); orderRows = await orderModel.findAll({ attributes: [ 'id', 'intercept_status', 'lock_status' ], where: baseOrderWhere, raw: true, }); } this.ctx.logger.info('[wave.batchAllocateExpress] 订单筛选完成', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, useBusinessKeyColumn, matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); const skippedInterceptedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) .filter(row => this.isInterceptedOrderStatus(row && row.intercept_status)) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] .sort((a, b) => a - b); const skippedInterceptedOrderIdSet = new Set(skippedInterceptedOrderIds); if (skippedInterceptedOrderIds.length > 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 跳过拦截订单', { traceId, taskId: normalizedTaskId, warehouseId, skippedInterceptedOrderIds, }); } const skippedLockedOrderIds = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) .filter(row => this.isLockedOrderStatus(row && row.lock_status)) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] .sort((a, b) => a - b); const skippedLockedOrderIdSet = new Set(skippedLockedOrderIds); if (skippedLockedOrderIds.length > 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 跳过锁定订单', { traceId, taskId: normalizedTaskId, warehouseId, skippedLockedOrderIds, }); } const normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0 || skippedInterceptedOrderIdSet.has(orderId) || skippedLockedOrderIdSet.has(orderId)) { return null; } const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 1); return { order_id: orderId, business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, }; }) .filter(Boolean); if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, skippedInterceptedOrderIds, skippedLockedOrderIds, }); const durationMs = Date.now() - startTime; await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: waveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, skipped_need_oms_waybill_order_ids: [], duration_ms: durationMs, message: skippedInterceptedOrderIds.length > 0 || skippedLockedOrderIds.length > 0 ? `拦截/锁定订单已跳过,未找到可分配快递号的订单(拦截 ${skippedInterceptedOrderIds.length} 单,锁定 ${skippedLockedOrderIds.length} 单)` : '未找到可分配快递号的订单', }, trace_id: traceId, }); return; } await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: waveIds.length, total_order_count: normalizedOrders.length, trace_id: traceId, }); this.ctx.logger.info('[wave.batchAllocateExpress] 即将调用快递号分配流水线', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, totalOrderCount: normalizedOrders.length, sampleOrderIds: normalizedOrders.slice(0, 20).map(item => Number(item && item.order_id || 0)).filter(Boolean), }); // awaitTasks=true:等待所有批次真正分配完成后再返回,避免任务被提前标记 success。 // warehouseId 显式传入:后台任务运行在 setImmediate 异步上下文中,ctx.user 可能已失效, // 防止 getCurrentWarehouseId() 返回 0 导致跨仓/无效仓查询。 const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders, { awaitTasks: true, warehouseId, }); const durationMs = Date.now() - startTime; this.ctx.logger.info('[wave.batchAllocateExpress] 快递号分配流水线执行完成', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, totalOrderCount: normalizedOrders.length, durationMs, pipelineResult, }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: waveIds.length, total_order_count: normalizedOrders.length, processed_order_count: normalizedOrders.length, success_order_count: normalizedOrders.length, failed_order_count: 0, skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: normalizedOrders.length, skipped_intercepted_order_ids: skippedInterceptedOrderIds, skipped_locked_order_ids: skippedLockedOrderIds, skipped_need_oms_waybill_order_ids: pipelineResult && Array.isArray(pipelineResult.skipped_need_oms_waybill_order_ids) ? pipelineResult.skipped_need_oms_waybill_order_ids : [], duration_ms: durationMs, message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), }, trace_id: traceId, }); } catch (error) { this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', trace_id: traceId, }); } } /** * 执行批次分配储位后台任务。 * * 任务仅负责按波次拉取订单并提交储位分配流水线,实际分配过程复用储位分配服务。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 * @return {Promise} 无返回值。 */ async runBatchAllocateStorageTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); const waveIds = this.normalizeIdsInput( cachedTask && cachedTask.wave_ids !== undefined ? cachedTask.wave_ids : params && params.waveIds ); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', }); return; } if (waveIds.length === 0) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, end_time: Date.now(), error: 'wave_ids 参数不能为空或格式错误', error_code: 'INVALID_WAVE_IDS', }); return; } const startTime = Date.now(); const lockResult = this.tryAcquireBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); if (!lockResult.acquired) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: lockResult.ownerTaskId ? `同仓库存在执行中的批量储位分配任务,请稍后重试(running_task_id=${lockResult.ownerTaskId})` : '同仓库存在执行中的批量储位分配任务,请稍后重试', error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_WAREHOUSE_CONFLICT', }); return; } await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_wave_count: waveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', }); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderRows = await orderModel.findAll({ attributes: [ 'id', 'lock_status' ], where: { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }, raw: true, }); const skippedLockedOrderIdSet = new Set((Array.isArray(orderRows) ? orderRows : []) .filter(row => this.isLockedOrderStatus(row && row.lock_status)) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)); const normalizedOrders = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] .filter(orderId => !skippedLockedOrderIdSet.has(orderId)) .map(orderId => ({ order_id: orderId, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, })); const normalizedOrderIds = normalizedOrders.map(item => Number(item.order_id || 0)).filter(Boolean); if (normalizedOrderIds.length === 0) { const durationMs = Date.now() - startTime; await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: waveIds.length, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, affected_order_ids: [], affected_order_count: 0, allocated_order_ids: [], allocated_order_count: 0, shortage_order_ids: [], progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, affected_order_ids: [], affected_order_count: 0, allocated_order_ids: [], allocated_order_count: 0, shortage_order_ids: [], duration_ms: durationMs, message: '未找到可分配储位的订单', }, }); return; } await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: waveIds.length, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_order_count: normalizedOrderIds.length, }); const progressCallback = async callbackPayload => { const latestProgress = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); const runningProgressPayload = this.buildBatchAllocateStorageRunningProgressPayload( callbackPayload, latestProgress || { total_order_count: normalizedOrderIds.length, processed_order_count: 0, progress_percent: 0, } ); await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_wave_count: waveIds.length, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, ...runningProgressPayload, }); }; const pipelineResult = await this.service.systems.orderStorageAllocation.allocateStorage({ ids: normalizedOrderIds, orders: normalizedOrders, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, progress_callback: progressCallback, }); if (!this.isPlainObject(pipelineResult) || Number(pipelineResult.code) !== 200) { throw new Error(String(pipelineResult && pipelineResult.message || '储位分配任务提交失败').trim()); } const resultData = this.isPlainObject(pipelineResult.data) ? pipelineResult.data : {}; const pendingOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.pending_order_ids); const affectedOrderIds = pendingOrderIds.length > 0 ? pendingOrderIds : this.normalizeBatchAllocateStorageOrderIds(normalizedOrderIds); const allocatedOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.allocated_order_ids); const shortageOrderIds = this.normalizeBatchAllocateStorageOrderIds(resultData.shortage_order_ids); const affectedOrderCount = affectedOrderIds.length; const successOrderCount = allocatedOrderIds.length; const failedOrderCount = shortageOrderIds.length > 0 ? shortageOrderIds.length : Math.max(0, affectedOrderCount - successOrderCount); const durationMs = Date.now() - startTime; await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_wave_count: waveIds.length, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_order_count: affectedOrderCount, processed_order_count: affectedOrderCount, success_order_count: successOrderCount, failed_order_count: failedOrderCount, affected_order_ids: affectedOrderIds, affected_order_count: affectedOrderCount, allocated_order_ids: allocatedOrderIds, allocated_order_count: successOrderCount, shortage_order_ids: shortageOrderIds, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, affected_order_ids: affectedOrderIds, affected_order_count: affectedOrderCount, allocated_order_ids: allocatedOrderIds, allocated_order_count: successOrderCount, shortage_order_ids: shortageOrderIds, duration_ms: durationMs, message: String(pipelineResult && pipelineResult.message || '分配储位任务已提交').trim(), }, }); } catch (error) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_FAILED', }); } finally { this.releaseBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); } } /** * 批量将波次状态改为“自动加团中”。 * * 仅处理当前登录仓库下命中的波次状态,不修改订单表 wave_id。 * * @param {Object} data 请求参数。 * @param {Array|number|string} data.ids 波次ID集合。 * @return {Promise} 批量更新结果。 */ async batchAutoGrouping(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const normalizedIds = this.normalizeIdsInput(data && data.ids); if (normalizedIds.length === 0) { throw new Error('ids 参数不能为空或格式错误'); } const maxWaveQuantity = await this.getDefaultWaveQuantity(warehouseId); const transaction = await this.ctx.model.transaction(); try { const querySql = ` SELECT wave_id, wave_status, total_orders FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:ids) `; const queryRows = await this.ctx.model.query(querySql, { replacements: { warehouseId, ids: normalizedIds, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const affectedRows = Array.isArray(queryRows) ? queryRows : []; const affectedWaveIds = [ ...new Set(affectedRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; const skippedDetails = []; const skippedWaveIds = []; const updatableWaveIds = []; for (const row of affectedRows) { const waveId = Number(row && row.wave_id || 0); if (!Number.isInteger(waveId) || waveId <= 0) { continue; } const waveStatus = Number(row && row.wave_status || 0); const totalOrders = Number(row && row.total_orders || 0); if (waveStatus >= 2) { skippedWaveIds.push(waveId); skippedDetails.push({ wave_id: waveId, reason: 'printed_or_after_printed', }); continue; } if (totalOrders >= maxWaveQuantity) { skippedWaveIds.push(waveId); skippedDetails.push({ wave_id: waveId, reason: 'reach_max_wave_quantity', }); continue; } updatableWaveIds.push(waveId); } if (affectedWaveIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: [], skipped_wave_ids: [], skipped_wave_count: 0, skipped_details: [], updated_wave_count: 0, }); } if (updatableWaveIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: affectedWaveIds, skipped_wave_ids: skippedWaveIds, skipped_wave_count: skippedWaveIds.length, skipped_details: skippedDetails, updated_wave_count: 0, }); } const updateSql = ` UPDATE wms_wave_batch SET wave_status = 0, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) `; const updateResult = await this.ctx.model.query(updateSql, { replacements: { warehouseId, waveIds: updatableWaveIds, }, transaction, }); const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) || updatableWaveIds.length ); await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: affectedWaveIds, skipped_wave_ids: skippedWaveIds, skipped_wave_count: skippedWaveIds.length, skipped_details: skippedDetails, updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, }); } catch (error) { await transaction.rollback(); throw error; } } /** * 批量结束“自动加团中”状态。 * * 仅处理当前登录仓库下命中的波次,且仅将 wave_status=0 的波次更新为 1(已就绪)。 * * @param {Object} data 请求参数。 * @param {Array|number|string} data.ids 波次ID集合。 * @return {Promise} 批量结束结果。 */ async batchFinishAutoGrouping(data = {}) { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const normalizedIds = this.normalizeIdsInput(data && data.ids); if (normalizedIds.length === 0) { throw new Error('ids 参数不能为空或格式错误'); } const transaction = await this.ctx.model.transaction(); try { const querySql = ` SELECT wave_id, wave_status FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:ids) `; const queryRows = await this.ctx.model.query(querySql, { replacements: { warehouseId, ids: normalizedIds, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const affectedRows = Array.isArray(queryRows) ? queryRows : []; const affectedWaveIds = [ ...new Set(affectedRows .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; if (affectedWaveIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: [], updated_wave_ids: [], updated_wave_count: 0, }); } const updatedWaveIds = [ ...new Set(affectedRows .filter(row => Number(row && row.wave_status || 0) === 0) .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; if (updatedWaveIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: affectedWaveIds, updated_wave_ids: [], updated_wave_count: 0, }); } // 关闭自动加团前,重建波次订单索引(wave_index 重新排序),确保序号连续 const orderModel = await this.getOrderModel('pendingOrder', warehouseId); await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: updatedWaveIds, orderModel, transaction, }); const updateSql = ` UPDATE wms_wave_batch SET wave_status = 1, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) AND wave_status = 0 `; const updateResult = await this.ctx.model.query(updateSql, { replacements: { warehouseId, waveIds: updatedWaveIds, }, transaction, }); const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) || updatedWaveIds.length ); await transaction.commit(); return this.success('ok', { ids: normalizedIds, affected_wave_ids: affectedWaveIds, updated_wave_ids: updatedWaveIds, updated_wave_count: Number.isInteger(updatedWaveCount) && updatedWaveCount > 0 ? updatedWaveCount : 0, }); } catch (error) { await transaction.rollback(); throw error; } } /** * 生成可追踪的抓取任务ID。 * * @param {number|string} warehouseId 仓库ID。 * @return {string} 抓取任务ID。 */ generateFetchTaskId(warehouseId = 0) { const normalizedWarehouseId = Number(warehouseId || 0); const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 ? normalizedWarehouseId : 0; const waveIdSeed = this.generateWaveId(); return `wave_fetch_${safeWarehouseId}_${waveIdSeed}`; } /** * 归一化抓取任务ID。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {string} 归一化后的任务ID。 */ normalizeFetchTaskId(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; return String(normalizedData.task_id || normalizedData.taskId || '').trim(); } /** * 获取抓取任务进度缓存键。 * * @param {string} taskId 任务ID。 * @return {string} 缓存键。 */ getFetchTaskCacheKey(taskId = '') { const normalizedTaskId = String(taskId || '').trim(); if (!normalizedTaskId) { return ''; } return `${FETCH_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入抓取任务进度缓存。 * * @param {string} taskId 任务ID。 * @param {Object} payload 进度数据。 * @return {Promise} 无返回值。 */ async setFetchTaskProgress(taskId = '', payload = {}) { const cacheKey = this.getFetchTaskCacheKey(taskId); if (!cacheKey) { return; } const safePayload = this.isPlainObject(payload) ? payload : {}; const progressPayload = { ...safePayload, task_id: String(taskId || '').trim(), update_time: Date.now(), }; try { await this.app.setCacheAsync(cacheKey, progressPayload, FETCH_TASK_CACHE_TTL_SECONDS); } catch (error) { this.ctx.logger.warn('[wave.fetch] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); } } /** * 读取抓取任务进度缓存。 * * @param {string} taskId 任务ID。 * @return {Promise} 任务进度缓存。 */ async getFetchTaskProgress(taskId = '') { const cacheKey = this.getFetchTaskCacheKey(taskId); if (!cacheKey) { return null; } try { const cached = await this.app.getCacheAsync(cacheKey); if (!this.isPlainObject(cached)) { return null; } return cached; } catch (error) { this.ctx.logger.warn('[wave.fetch] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); return null; } } /** * 查询抓取任务进度。 * * @param {Object} data 请求参数。 * @param {string} data.task_id 任务ID(下划线写法)。 * @param {string} data.taskId 任务ID(驼峰写法)。 * @return {Promise} 任务进度响应。 */ async fetchTaskProgress(data = {}) { const taskId = this.normalizeFetchTaskId(data); if (!taskId) { return this.fail('task_id 参数不能为空', 400); } const cachedProgress = await this.getFetchTaskProgress(taskId); if (!cachedProgress) { return this.success('ok', { task_id: taskId, status: 'not_found', }); } return this.success('ok', { task_id: taskId, ...cachedProgress, status: String(cachedProgress.status || 'unknown').trim() || 'unknown', }); } /** * 执行异步抓取任务。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number} params.warehouseId 仓库ID。 * @param {number} params.defaultQuantity 默认抓取数量。 * @param {Array} params.structures 结构化抓取请求。 * @param {string} [params.fetchMode='group'] 抓取模式:group|single。 * @param {number} [params.maxFetchQuantity=0] single 模式最大抓取订单数上限。 * @return {Promise} 无返回值。 */ async runFetchTask({ taskId = '', warehouseId = 0, defaultQuantity = DEFAULT_MAX_WAVE_QUANTITY, structures = [], fetchMode = 'group', maxFetchQuantity = 0, } = {}) { const normalizedTaskId = String(taskId || '').trim(); const normalizedWarehouseId = Number(warehouseId || 0); const structureList = Array.isArray(structures) ? structures : []; const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 ? Number(maxFetchQuantity) : 0; if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { throw new Error('warehouseId 参数不合法'); } if (structureList.length === 0) { throw new Error('structures 不能为空'); } if (normalizedFetchMode === 'single' && normalizedMaxFetchQuantity <= 0) { throw new Error('single 模式要求 maxFetchQuantity 为正整数'); } this.ctx.logger.info('[wave.fetch] 后台任务开始', { taskId: normalizedTaskId, warehouseId: normalizedWarehouseId, structureCount: structureList.length, defaultQuantity: Number(defaultQuantity || 0), fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, }); const startedAt = Date.now(); await this.setFetchTaskProgress(normalizedTaskId, { status: 'running', warehouse_id: normalizedWarehouseId, structure_count: structureList.length, finished_structure_count: 0, progress_percent: 0, default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), started_at: startedAt, }); try { const groupWavePrefix = await this.getGroupWavePrefix(normalizedWarehouseId); const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(normalizedWarehouseId); const model = await this.getOrderModel('pendingOrder', normalizedWarehouseId); const results = []; let totalFetchedQuantity = 0; let reachedLimit = false; for (let i = 0; i < structureList.length; i++) { if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { reachedLimit = true; break; } const structure = structureList[i]; const remainingFetchQuantity = normalizedFetchMode === 'single' ? normalizedMaxFetchQuantity - totalFetchedQuantity : 0; const result = await this.fetchSingleStructure( model, structure, normalizedWarehouseId, groupWavePrefix, normalizedFetchMode === 'single' ? 1 : minGroupOrderFetchQuantity, { maxFetchQuantity: remainingFetchQuantity, } ); results.push(result); totalFetchedQuantity += Number(result.fetched_quantity || 0); if (normalizedFetchMode === 'single' && totalFetchedQuantity >= normalizedMaxFetchQuantity) { reachedLimit = true; } const finishedStructureCount = results.length; const progressPercent = Math.min( 100, Math.round((finishedStructureCount / structureList.length) * 100) ); await this.setFetchTaskProgress(normalizedTaskId, { status: 'running', warehouse_id: normalizedWarehouseId, structure_count: structureList.length, finished_structure_count: finishedStructureCount, progress_percent: progressPercent, total_fetched_quantity: totalFetchedQuantity, default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), started_at: startedAt, }); } const totalRequestQuantity = results.reduce((sum, item) => sum + Number(item.request_quantity || 0), 0); const durationMs = Date.now() - startedAt; const finishedStructureCount = results.length; const progressPercent = structureList.length > 0 ? Math.min(100, Math.round((finishedStructureCount / structureList.length) * 100)) : 100; await this.setFetchTaskProgress(normalizedTaskId, { status: 'success', warehouse_id: normalizedWarehouseId, structure_count: structureList.length, finished_structure_count: finishedStructureCount, progress_percent: progressPercent, total_request_quantity: totalRequestQuantity, total_fetched_quantity: totalFetchedQuantity, default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), ...(normalizedFetchMode === 'single' ? { limit_reached: reachedLimit } : {}), ...(normalizedFetchMode === 'single' && reachedLimit ? { stop_reason: '达到最大抓取上限' } : {}), started_at: startedAt, duration_ms: durationMs, }); this.ctx.logger.info('[wave.fetch] 后台任务完成', { taskId: normalizedTaskId, warehouseId: normalizedWarehouseId, structureCount: structureList.length, defaultQuantity: Number(defaultQuantity || 0), fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, reachedLimit, totalRequestQuantity, totalFetchedQuantity, durationMs, }); } catch (error) { await this.setFetchTaskProgress(normalizedTaskId, { status: 'failed', warehouse_id: normalizedWarehouseId, structure_count: structureList.length, default_quantity: Number(defaultQuantity || 0), fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), started_at: startedAt, duration_ms: Date.now() - startedAt, error: error && error.message ? error.message : `${error}`, }); throw error; } } /** * 提交异步抓取任务。 * * @param {Object} data 请求参数。 * @param {'group'|'single'} [fetchMode='group'] 抓取模式。 * @param {number} [maxFetchQuantity=0] single 模式最大抓取订单数。 * @return {Promise} 任务提交结果。 */ async submitFetchTask(data = {}, fetchMode = 'group', maxFetchQuantity = 0) { const warehouseId = this.getWarehouseId(); const defaultQuantity = await this.getDefaultWaveQuantity(warehouseId); const structures = this.normalizeFetchStructureRequests(data, defaultQuantity); const taskId = this.generateFetchTaskId(warehouseId); const normalizedFetchMode = String(fetchMode || 'group').trim() === 'single' ? 'single' : 'group'; const normalizedMaxFetchQuantity = Number.isInteger(Number(maxFetchQuantity)) && Number(maxFetchQuantity) > 0 ? Number(maxFetchQuantity) : 0; await this.setFetchTaskProgress(taskId, { status: 'submitted', warehouse_id: Number(warehouseId || 0), structure_count: structures.length, finished_structure_count: 0, progress_percent: 0, default_quantity: defaultQuantity, fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), submitted_at: Date.now(), }); this.ctx.logger.info('[wave.fetch] 任务提交成功', { taskId, warehouseId: Number(warehouseId || 0), structureCount: structures.length, defaultQuantity, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, }); setImmediate(() => { this.runFetchTask({ taskId, warehouseId: Number(warehouseId || 0), defaultQuantity, structures, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, }).catch(error => { this.ctx.logger.error('[wave.fetch] 后台任务异常', { taskId, warehouseId: Number(warehouseId || 0), structureCount: structures.length, defaultQuantity, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, error: error && error.message ? error.message : error, stack: error && error.stack ? error.stack : '', }); }); }); return this.success('ok', { task_id: taskId, warehouse_id: Number(warehouseId || 0), structure_count: structures.length, default_quantity: defaultQuantity, fetch_mode: normalizedFetchMode, ...(normalizedFetchMode === 'single' ? { max_fetch_quantity: normalizedMaxFetchQuantity } : {}), message: '任务已提交,后端异步处理中', }); } /** * 团购抓取波次:按机器结构标识批量抓取订单。 * * @param {Object} data 请求参数。 * @param {Array} data.structure_list 结构请求数组。 * @return {Promise} 任务提交结果。 */ async groupFetch(data = {}) { return this.submitFetchTask(data, 'group', 0); } /** * 散单抓取波次:支持按订单数上限停止。 * * @param {Object} data 请求参数。 * @param {Array} data.structure_list 结构请求数组。 * @param {number|string} data.max_fetch_quantity 最大抓取订单数(必填正整数)。 * @return {Promise} 任务提交结果。 */ async singleFetch(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const maxFetchQuantity = this.normalizeRequiredPositiveInteger( normalizedData.max_fetch_quantity ?? normalizedData.maxFetchQuantity, 'max_fetch_quantity' ); return this.submitFetchTask(normalizedData, 'single', maxFetchQuantity); } /** * 按策略与策略类型推导本次抓取的拣货模式。 * * 优先使用显式入参 pick_mode/pickMode,其次回退到策略字段(strategy_type、batch_mode)。 * * @param {Object} options 推导参数。 * @param {Object} [options.requestData={}] 请求参数。 * @param {Object} [options.strategyRow={}] 策略行数据。 * @return {number} 归一化后的拣货模式(1-5,异常时为 0)。 */ resolveWaveStrategyFetchPickMode(options = {}) { const requestData = this.isPlainObject(options && options.requestData) ? options.requestData : {}; const strategyRow = this.isPlainObject(options && options.strategyRow) ? options.strategyRow : {}; const explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { return explicitPickMode; } const strategyType = Number(strategyRow.strategy_type || 0); const batchMode = Number(strategyRow.batch_mode || 0); const groupBatchMaxOrders = Number(strategyRow.group_batch_max_orders || 0); if (strategyType === 2) { if (groupBatchMaxOrders > 1) { return 1; } return 5; } if (batchMode === 1) { return 2; } if (batchMode === 2) { return 3; } if ([ 3, 4, 5, 6 ].includes(batchMode)) { return 4; } return 0; } /** * 构建抓取策略的框分配规则(最小可执行结构)。 * * @param {Object} options 构建参数。 * @param {number} options.pickMode 拣货模式。 * @param {Array} [options.selectedWaveIds=[]] 预抓波次ID集合。 * @param {number} [options.boxLimit=0] 最大可用框数。 * @return {Array} 框分配规则列表。 */ buildWaveStrategyFetchBoxAssignments(options = {}) { const pickMode = Number(options && options.pickMode || 0); const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) ? options.selectedWaveIds : []; const boxLimit = Number(options && options.boxLimit || 0); if (pickMode === 1) { return selectedWaveIds.map((waveId, index) => ({ wave_id: waveId, box_no: index + 1, rule: 'one_wave_one_box', })); } if (selectedWaveIds.length > 0) { return [{ wave_id: selectedWaveIds[0], box_no: 1, rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', }]; } return [{ wave_id: 0, box_no: 1, rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', box_limit: Number.isInteger(boxLimit) && boxLimit > 0 ? boxLimit : 1, }]; } /** * 策略抓取前置预处理:统一输出标准化 plan。 * * 仅做策略与参数预处理,不执行任务写库。 * * @param {Object} params 预处理入参。 * @param {number|string} params.strategyId 策略ID。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Object} [params.operator={}] 操作人信息。 * @param {string} [params.source='unknown'] 来源标识(pda/admin)。 * @param {Object} [params.data={}] 原始请求参数。 * @return {Promise} 标准化抓取 plan。 */ async prepareWaveStrategyFetchPlan(params = {}) { const strategyId = this.normalizeRequiredPositiveInteger(params && params.strategyId, 'strategy_id'); const warehouseId = this.normalizeRequiredPositiveInteger(params && params.warehouseId, 'warehouse_id'); const source = String(params && params.source || 'unknown').trim() || 'unknown'; const operator = this.isPlainObject(params && params.operator) ? params.operator : {}; const requestData = this.isPlainObject(params && params.data) ? params.data : {}; const hasExplicitWaveSelectionInput = [ 'selected_wave_ids', 'selectedWaveIds', 'wave_ids', 'waveIds', 'wave_id', 'waveId', ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); const plan = { strategy_id: strategyId, warehouse_id: warehouseId, source, operator, pick_mode: 0, wave_limit: 0, order_limit: 0, sku_limit: 0, box_limit: 0, selected_wave_ids: [], box_assignments: [], dynamic_append: false, validation_errors: [], }; let strategyRows = []; try { strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); } catch (error) { strategyRows = []; } let strategyRow = (Array.isArray(strategyRows) ? strategyRows : []).find(item => { const currentId = Number(item && (item.id ?? item.strategy_id ?? item.strategyId) || 0); return Number.isInteger(currentId) && currentId === strategyId; }) || null; if (!strategyRow) { const strategyModel = this.getWaveStrategyModel(); if (strategyModel && typeof strategyModel.findOne === 'function') { const strategyEntity = await strategyModel.findOne({ where: { id: strategyId, warehouse_id: warehouseId, status: 1, }, raw: true, }); if (strategyEntity && typeof strategyEntity.get === 'function') { strategyRow = strategyEntity.get({ plain: true }); } else { strategyRow = strategyEntity || null; } } } if (!strategyRow) { plan.validation_errors.push(`策略不存在或已停用: ${strategyId}`); return plan; } plan.strategy_type = Number(strategyRow.strategy_type || 0); plan.strategy_row = strategyRow; const selectedWaveIds = this.normalizeIdsInput( requestData.selected_wave_ids !== undefined ? requestData.selected_wave_ids : requestData.selectedWaveIds !== undefined ? requestData.selectedWaveIds : requestData.wave_ids !== undefined ? requestData.wave_ids : requestData.waveIds !== undefined ? requestData.waveIds : requestData.wave_id !== undefined ? requestData.wave_id : requestData.waveId ); plan.selected_wave_ids = selectedWaveIds; const pickMode = this.resolveWaveStrategyFetchPickMode({ requestData, strategyRow, }); plan.pick_mode = pickMode; if (![ 1, 2, 3, 4, 5 ].includes(pickMode)) { plan.validation_errors.push('无法从策略推导有效 pick_mode,请显式传入 pick_mode(1-5)'); } const rawBoxLimit = requestData.box_limit ?? requestData.boxLimit ?? strategyRow.group_batch_max_orders; const normalizedBoxLimit = Number(rawBoxLimit); plan.box_limit = Number.isInteger(normalizedBoxLimit) && normalizedBoxLimit > 0 ? normalizedBoxLimit : 1; const rawOrderLimit = requestData.order_limit ?? requestData.orderLimit ?? strategyRow.batch_max_orders; const normalizedOrderLimit = Number(rawOrderLimit); plan.order_limit = Number.isInteger(normalizedOrderLimit) && normalizedOrderLimit > 0 ? normalizedOrderLimit : 0; const rawSkuLimit = requestData.sku_limit ?? requestData.skuLimit ?? strategyRow.batch_max_skus; const normalizedSkuLimit = Number(rawSkuLimit); plan.sku_limit = Number.isInteger(normalizedSkuLimit) && normalizedSkuLimit > 0 ? normalizedSkuLimit : 0; const rawWaveLimit = requestData.wave_limit ?? requestData.waveLimit; const normalizedWaveLimit = Number(rawWaveLimit); if (Number.isInteger(normalizedWaveLimit) && normalizedWaveLimit > 0) { plan.wave_limit = normalizedWaveLimit; } else { plan.wave_limit = pickMode === 1 ? plan.box_limit : 1; } if (pickMode === 1) { if (plan.box_limit <= 0) { plan.validation_errors.push('小团购模式 box_limit 必须大于 0'); } if (selectedWaveIds.length > plan.box_limit) { plan.validation_errors.push(`小团购模式预抓波次数(${selectedWaveIds.length})超过 box_limit(${plan.box_limit})`); } } if ([ 1, 5 ].includes(pickMode) && hasExplicitWaveSelectionInput && selectedWaveIds.length === 0) { plan.validation_errors.push('当前模式依赖波次,selected_wave_ids 不能为空'); } if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 1) { plan.validation_errors.push('单品单件/先拣后分/边拣边分模式一次仅支持一个波次'); } if (pickMode === 2 && plan.order_limit <= 0) { plan.validation_errors.push('单品单件模式 order_limit 必须大于 0'); } if (pickMode === 3 && plan.sku_limit <= 0) { plan.validation_errors.push('先拣后分模式 sku_limit 必须大于 0'); } if (pickMode === 5) { plan.dynamic_append = true; if (selectedWaveIds.length > 1) { plan.validation_errors.push('大团购模式一次仅支持一个波次(后续追加采用动态扫描)'); } } plan.box_assignments = this.buildWaveStrategyFetchBoxAssignments({ pickMode, selectedWaveIds, boxLimit: plan.box_limit, }); return plan; } /** * 校验当前操作用户是否存在未完成任务。 * * 活跃状态定义:status in (0,1),不包含已完成(status=2)的任务。 * * @param {Object} params 校验参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {number|string} params.operatorId 操作用户ID。 * @param {Object} params.transaction 事务对象。 * @return {Promise} 无返回值。 */ async ensureNoActiveWavePickTaskForOperator(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const operatorId = Number(params.operatorId || 0); const transaction = params.transaction; if (!Number.isInteger(operatorId) || operatorId <= 0) { return; } const rows = await this.ctx.model.query(` SELECT id, task_no FROM wms_wave_pick_task WHERE warehouse_id = :warehouseId AND pick_user_id = :operatorId AND status IN (0, 1) ORDER BY id DESC LIMIT 1 FOR UPDATE `, { replacements: { warehouseId, operatorId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const activeTask = Array.isArray(rows) ? rows[0] : null; if (activeTask) { const taskNo = String(activeTask.task_no || '').trim(); const taskId = Number(activeTask.id || 0); throw new Error(`当前用户存在未完成任务,请先完成后再创建(task_id=${taskId}${taskNo ? `,task_no=${taskNo}` : ''})`); } } /** * 归一化候选订单查询的创建时间上限(不含)。 * * @param {Date|string|null} [createdBefore=null] 创建时间上限。 * @return {Date|null} 归一化后的 Date;非法输入返回 null(表示不限制)。 */ normalizeWaveStrategyFetchCreatedBefore(createdBefore = null) { if (createdBefore instanceof Date && !Number.isNaN(createdBefore.getTime())) { return createdBefore; } if (typeof createdBefore === 'string' && createdBefore.trim()) { const parsed = new Date(createdBefore.trim()); if (!Number.isNaN(parsed.getTime())) { return parsed; } } return null; } /** * 计算今日 0 点(本地时区),作为订单池分割的时间边界。 * * 第一订单池 = 创建时间早于今日 0 点的订单(前一天及更早订单); * 第二订单池 = 其余订单(今日订单)。 * * @return {Date} 今日 0 点时间。 */ buildWaveStrategyFetchTodayStart() { const now = new Date(); return new Date(now.getFullYear(), now.getMonth(), now.getDate()); } /** * 查询策略自动分流候选订单(命中策略且未分配波次)。 * * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding, * 并按同结构数量命中 min_same_structure/max_same_structure。 * * @param {Object} params 查询参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {number|string} params.strategyId 策略ID。 * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量。 * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量。 * @param {Date|string|null} [params.createdBefore=null] 创建时间上限(不含), * 仅命中创建时间早于该值的订单,用于分割第一/第二订单池;为 null 时不限制。 * @return {Promise>} 候选订单数组(按 order_id 升序)。 */ async getWaveStrategyFetchCandidateOrders(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const strategyId = this.normalizeRequiredPositiveInteger(params.strategyId, 'strategy_id'); const minSameStructureRaw = Number(params.minSameStructure ?? 0); const maxSameStructureRaw = Number(params.maxSameStructure); const minSameStructure = Number.isFinite(minSameStructureRaw) && minSameStructureRaw > 0 ? Math.floor(minSameStructureRaw) : 0; const maxSameStructure = Number.isFinite(maxSameStructureRaw) && maxSameStructureRaw > 0 ? Math.floor(maxSameStructureRaw) : null; const requireSameExpress = Number(params.requireSameExpress ?? 0) === 1; const createdBefore = this.normalizeWaveStrategyFetchCreatedBefore(params.createdBefore); const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const structureExpr = alias => `${alias}.items_hash`; const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const groupKeyExtra = requireSameExpress ? `, ${expressExpr('src')}` : ''; const joinKeyExtra = requireSameExpress ? ` AND same_structure.express_key = ${expressExpr('o')}` : ''; const rows = await this.ctx.model.query(` SELECT o.id, o.items_hash, o.items, o.logistics_name, o.sys_logistics_code, o.logistics_code, o.items_count, o.items_total FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id AND o.warehouse_id = :warehouseId AND o.wave_id = 0 AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' AND o.intercept_status = 'none' AND o.lock_status = 'none' AND (:createdBefore IS NULL OR o.create_at < :createdBefore) INNER JOIN ( SELECT ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, COUNT(1) AS same_structure_count FROM ${orderTableName} src WHERE src.warehouse_id = :warehouseId AND src.wave_id = 0 AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' AND src.intercept_status = 'none' AND src.lock_status = 'none' GROUP BY ${structureExpr('src')}${groupKeyExtra} ) same_structure ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} WHERE m.warehouse_id = :warehouseId AND m.strategy_id = :strategyId AND same_structure.same_structure_count >= :minSameStructure AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure) ORDER BY o.id ASC `, { replacements: { warehouseId, strategyId, minSameStructure, maxSameStructure, createdBefore, }, type: this.ctx.model.QueryTypes.SELECT, }); return (Array.isArray(rows) ? rows : []) .map(row => ({ id: Number(row && row.id || 0), items_hash: String(row && row.items_hash || '').trim(), items: String(row && row.items || '').trim(), logistics_name: String(row && row.logistics_name || '').trim(), sys_logistics_code: String(row && row.sys_logistics_code || '').trim(), logistics_code: String(row && row.logistics_code || '').trim(), items_count: Number(row && row.items_count || 0), items_total: Number(row && row.items_total || 0), })) .filter(row => Number.isInteger(row.id) && row.id > 0) .sort((a, b) => a.id - b.id); } /** * 按订单结构对候选订单分组。 * * @param {Array} candidateRows 候选订单数组。 * @return {Array} 分组结果(含 group_min_order_id)。 */ groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows = []) { const groupedMap = new Map(); const rows = Array.isArray(candidateRows) ? candidateRows : []; for (const row of rows) { const structureKey = this.getWaveStrategyQuickScanStructureKey(row); if (!structureKey) { continue; } if (!groupedMap.has(structureKey)) { groupedMap.set(structureKey, []); } groupedMap.get(structureKey).push(row); } return Array.from(groupedMap.entries()) .map(([ structureKey, orders ]) => { const sortedOrders = orders .map(item => ({ ...item })) .sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); const minOrderId = sortedOrders.length > 0 ? Number(sortedOrders[0].id || 0) : 0; return { structure_key: structureKey, group_min_order_id: minOrderId, orders: sortedOrders, order_ids: sortedOrders.map(item => Number(item.id || 0)).filter(id => Number.isInteger(id) && id > 0), }; }) .filter(group => group.order_ids.length > 0) .sort((a, b) => a.group_min_order_id - b.group_min_order_id); } /** * 读取订单商品明细并构建每单 SKU 集合。 * * @param {Object} params 构建参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Array} params.orderIds 订单ID数组。 * @return {Promise>>} order_id 到 SKU 集合映射。 */ async buildWaveStrategyFetchOrderSkuMap(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const orderIds = this.normalizeIdsInput(params.orderIds || []); if (orderIds.length === 0) { return new Map(); } const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { throw new Error('订单明细模型不可用'); } const itemRows = await orderItemsModel.findAll({ where: { order_id: { [Op.in]: orderIds }, }, attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], raw: true, }); const rowMap = new Map(); for (const row of (Array.isArray(itemRows) ? itemRows : [])) { const orderId = Number(row && row.order_id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { continue; } if (!rowMap.has(orderId)) { rowMap.set(orderId, []); } rowMap.get(orderId).push(row); } const skuMap = new Map(); for (const orderId of orderIds) { const detailRows = rowMap.get(orderId) || []; const detailList = this.mergeOrderItemDetails(detailRows); const skuSet = new Set(); detailList.forEach(item => { const itemCode = String(item && item.item_code || '').trim(); const stockId = Number(item && item.stock_id || 0); if (itemCode) { skuSet.add(itemCode); return; } if (Number.isInteger(stockId) && stockId > 0) { skuSet.add(`stock_${stockId}`); } }); skuMap.set(orderId, skuSet); } return skuMap; } /** * 先拣后分模式按 SKU 上限筛选订单。 * * 当 SKU 种类超限时,循环剔除“出现频率最低”的 SKU, * 每次剔除该 SKU 对应的全部订单,直到 SKU 种类满足上限。 * * @param {Object} params 筛选参数。 * @param {Array} params.orderIds 候选订单ID(升序)。 * @param {Map>} params.orderSkuMap 订单 SKU 映射。 * @param {number|string} params.skuLimit SKU 上限。 * @return {{ selectedOrderIds: Array, removedOrderIds: Array }} 筛选结果。 */ selectWaveStrategyFetchOrdersBySkuLimit(params = {}) { const orderIds = this.normalizeIdsInput(params.orderIds || []); const orderSkuMap = params.orderSkuMap instanceof Map ? params.orderSkuMap : new Map(); const skuLimitRaw = Number(params.skuLimit || 0); const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; if (orderIds.length === 0) { return { selectedOrderIds: [], removedOrderIds: [], }; } if (skuLimit <= 0) { return { selectedOrderIds: [], removedOrderIds: [ ...orderIds ], }; } const activeOrderSet = new Set(orderIds); const removedOrderSet = new Set(); const buildSkuOrderMap = () => { const skuOrderMap = new Map(); for (const orderId of activeOrderSet) { const skuSet = orderSkuMap.get(orderId) instanceof Set ? orderSkuMap.get(orderId) : new Set(); for (const sku of skuSet) { const skuKey = String(sku || '').trim(); if (!skuKey) { continue; } if (!skuOrderMap.has(skuKey)) { skuOrderMap.set(skuKey, new Set()); } skuOrderMap.get(skuKey).add(orderId); } } return skuOrderMap; }; for (;;) { const skuOrderMap = buildSkuOrderMap(); if (skuOrderMap.size <= skuLimit) { break; } let targetSku = ''; let minFrequency = Number.MAX_SAFE_INTEGER; for (const [ sku, orderSet ] of skuOrderMap.entries()) { const frequency = orderSet.size; if (frequency < minFrequency) { minFrequency = frequency; targetSku = sku; continue; } if (frequency === minFrequency && targetSku && String(sku).localeCompare(String(targetSku)) < 0) { targetSku = sku; } } if (!targetSku) { break; } const targetOrderSet = skuOrderMap.get(targetSku) || new Set(); for (const orderId of targetOrderSet) { if (activeOrderSet.has(orderId)) { activeOrderSet.delete(orderId); removedOrderSet.add(orderId); } } if (activeOrderSet.size === 0) { break; } } return { selectedOrderIds: [ ...activeOrderSet ].sort((a, b) => a - b), removedOrderIds: [ ...removedOrderSet ].sort((a, b) => a - b), }; } /** * 在事务内按指定订单创建波次并更新订单波次字段。 * * @param {Object} params 创建参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Array} params.orderIds 订单ID数组。 * @param {number|string} params.waveType 波次类型(1-团购,2-散单)。 * @param {string} params.wavePrefix 波次前缀。 * @param {number|string} [params.source=0] 波次来源。 * @param {number|string} [params.pickMode] 拣货模式(1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购), * 用于散单波次区分单品单件(pickMode=2 时订单 wave_scope 写入 4)。 * @param {string} [params.claimOperator] 抓取人姓名:抓取波次(source=1/2)无需领料, * 将该值冗余写入波次表领料人字段(claim_operator)。 * @param {Object} params.transaction 事务对象。 * @return {Promise<{ waveId: number, waveNo: string, selectedOrderIds: Array }>} 创建结果。 */ async createWaveBatchByOrderIdsInTransaction(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const waveType = Number(params.waveType || 0) === 2 ? 2 : 1; const wavePrefix = String(params.wavePrefix || '').trim() || (waveType === 2 ? 'A' : 'B'); const sourceInput = Number(params.source); const source = [ 0, 1, 2 ].includes(sourceInput) ? sourceInput : 0; const pickModeInput = Number(params.pickMode); const pickMode = [ 1, 2, 3, 4, 5 ].includes(pickModeInput) ? pickModeInput : 0; const claimOperator = String(params.claimOperator || '').trim() || null; const claimOperatorId = Number(params.claimOperatorId || 0) > 0 ? Number(params.claimOperatorId) : null; const transaction = params.transaction; const orderIds = this.normalizeIdsInput(params.orderIds || []); if (orderIds.length === 0) { throw new Error('创建波次失败:订单集合不能为空'); } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const lockRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'items_hash', 'items' ], where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId, wave_id: 0, step: { [Op.ne]: 0 }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, }, raw: true, transaction, lock: transaction.LOCK.UPDATE, }); const fetchableOrderIds = [ ...new Set((Array.isArray(lockRows) ? lockRows : []) .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); if (fetchableOrderIds.length === 0) { throw new Error('创建波次失败:候选订单已被占用或状态变化'); } const firstRow = Array.isArray(lockRows) ? lockRows[0] : null; const itemPart = this.getOrderItemPart(firstRow || {}); const itemSnapshotKey = `${itemPart.item_part_type}:${itemPart.item_part}`; const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPart.item_part_type, item_part: itemPart.item_part, distinguish_express: false, logistics_name: '', item_snapshot_key: itemSnapshotKey, }); const { waveId, waveNo } = await this.createWaveBatchReady({ warehouseId, totalOrders: fetchableOrderIds.length, itemDetailMachine, itemPartType: itemPart.item_part_type, itemPart: itemPart.item_part, distinguishExpress: false, logisticsName: '', itemSnapshotKey, wavePrefix, waveType, source, transaction, }); await orderModel.update({ wave_id: waveId, wave_no: waveNo, wave_scope: this.resolveWaveScopeByWaveMeta(waveType, source, pickMode), grab_operator_id: claimOperatorId, grab_operator: claimOperator, }, { where: { id: { [Op.in]: fetchableOrderIds }, warehouse_id: warehouseId, wave_id: 0, }, transaction, }); const grabbedRows = await orderModel.findAll({ where: { id: { [Op.in]: fetchableOrderIds }, warehouse_id: warehouseId, wave_id: waveId, }, attributes: [ 'id' ], raw: true, transaction, }); const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); if (grabbedOrderIds.length <= 0) { await this.ctx.model.query(` DELETE FROM wms_wave_batch WHERE wave_id = :waveId `, { replacements: { waveId, }, transaction, }); throw new Error('创建波次失败:未抓取到有效订单'); } if (grabbedOrderIds.length !== fetchableOrderIds.length) { await this.ctx.model.query(` UPDATE wms_wave_batch SET total_orders = :totalOrders, update_time = NOW() WHERE wave_id = :waveId `, { replacements: { waveId, totalOrders: grabbedOrderIds.length, }, transaction, }); } // 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯 if ([ 1, 2 ].includes(source) && claimOperator) { await this.ctx.model.WaveBatch.update( { claim_operator: claimOperator, claim_time: new Date(), }, { where: { wave_id: waveId, warehouse_id: warehouseId, }, transaction, } ); // 领料时间写入会改变确认打印未领单统计,递增版本号驱动长轮询 await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId); } await this.rebuildOrderWaveIndex({ warehouseId, waveId, orderIds: grabbedOrderIds, orderModel, transaction, }); return { waveId, waveNo, selectedOrderIds: grabbedOrderIds, }; } /** * 小团购第一池抓取时合并同结构全池订单(修复「1 单 1 波次」问题)。 * * 背景:波次抓取链路将订单池按「今日前 / 今日」分割,第一池非空时只抓第一池; * 但候选 SQL 的同结构计数子查询为「全池统计」(不限策略、不含池边界), * 导致某结构第一池仅剩 1 条时仍能通过 min_same_structure 门槛而单独成波。 * * 合并口径:针对第一池候选分组中出现过的结构 key(require_same_express=1 时为 * 「结构+快递」组合,快递口径复用候选 SQL 中 expressExpr 的 COALESCE 优先级), * 按候选 SQL 中同结构计数子查询的过筛口径(不限策略匹配、不含池边界 create_at 条件) * 查询同结构全池订单,将两池同结构订单全部并入候选,后续复用既有分组与建波流程。 * * 门控条件(任一不满足则返回 null 跳过合并、维持现状): * - 仅小团购(pickMode === 1)生效,大团购(pickMode === 5)不覆盖; * - 仅第一池非空(candidatePoolStage === 'first')时生效; * - 仅 max_same_structure 已设置且有效(正整数且非 999)时生效, * 未设置(null/999)的团购策略跳过合并; * - 同结构全池查询无新增订单(如该结构订单全部在第一池)时不合并。 * * @param {Object} params 合并参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Object} params.strategyRow 策略行。 * @param {Array} params.candidateRows 当前候选订单(第一池)。 * @param {Array} params.effectiveGroupedRows 第一池候选分组结果。 * @param {string} params.candidatePoolStage 候选池阶段(first-第一池/second-第二池)。 * @param {number|string} params.pickMode 拣货模式。 * @param {boolean} params.requireSameExpress 是否要求同快递。 * @param {Object} params.transaction 事务对象(合并查询与后续建波共用同一事务)。 * @return {Promise|null>} 合并后的候选订单数组;跳过合并时返回 null。 */ async mergeWaveStrategyFirstPoolSameStructureOrders(params = {}) { const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; const candidateRows = Array.isArray(params.candidateRows) ? params.candidateRows : []; const effectiveGroupedRows = Array.isArray(params.effectiveGroupedRows) ? params.effectiveGroupedRows : []; const candidatePoolStage = String(params.candidatePoolStage || '').trim(); const pickMode = Number(params.pickMode || 0); const requireSameExpress = Boolean(params.requireSameExpress); const transaction = params.transaction; // 门控一:仅小团购(pickMode=1)且第一池非空时执行合并 if (pickMode !== 1 || candidatePoolStage !== 'first') { return null; } // 门控二:max_same_structure 未设置(null/999)时跳过合并,维持现状; // 已设置有效的策略保存期已被钳制到 min-1,合并后天然受限,无需额外截断。 const maxSameStructureRaw = Number(strategyRow.max_same_structure); const maxSameStructureConfigured = Number.isInteger(maxSameStructureRaw) && maxSameStructureRaw > 0 && maxSameStructureRaw !== 999; if (!maxSameStructureConfigured) { return null; } // 收集第一池候选分组中出现过的结构 key; // require_same_express=1 时同时收集快递 key(分组均来自最大快递组,快递 key 唯一)。 const structureKeySet = new Set(); const expressKeySet = new Set(); for (const group of effectiveGroupedRows) { const structureKey = String(group && group.structure_key || '').trim(); if (!structureKey) { continue; } structureKeySet.add(structureKey); if (requireSameExpress) { const groupOrders = Array.isArray(group && group.orders) ? group.orders : []; const expressKey = groupOrders.length > 0 ? this.getWaveStrategyQuickScanExpressKey(groupOrders[0]) : ''; if (expressKey) { expressKeySet.add(expressKey); } } } const structureKeys = [ ...structureKeySet ].sort(); const expressKeys = [ ...expressKeySet ].sort(); if (structureKeys.length === 0 || (requireSameExpress && expressKeys.length === 0)) { return null; } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderTableName = this.getModelTableSqlName(orderModel); const structureExpr = alias => `${alias}.items_hash`; const expressExpr = alias => `COALESCE(NULLIF(TRIM(COALESCE(${alias}.sys_logistics_code, '')), ''), NULLIF(TRIM(COALESCE(${alias}.logistics_code, '')), ''), TRIM(COALESCE(${alias}.logistics_name, '')))`; const expressCondition = requireSameExpress ? ` AND ${expressExpr('o')} IN (:expressKeys)` : ''; const replacements = { warehouseId, structureKeys, }; if (requireSameExpress) { replacements.expressKeys = expressKeys; } // 复用候选 SQL 同结构计数子查询的过筛口径:不限策略匹配、不含池边界 create_at 条件, // 将两池同结构订单全部取出;查询与建波共用同一事务,行锁与 wave_id=0 复筛由建波流程负责。 const rows = await this.ctx.model.query(` SELECT o.id, o.items_hash, o.items, o.logistics_name, o.sys_logistics_code, o.logistics_code, o.items_count, o.items_total FROM ${orderTableName} o WHERE o.warehouse_id = :warehouseId AND o.wave_id = 0 AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' AND o.intercept_status = 'none' AND o.lock_status = 'none' AND ${structureExpr('o')} IN (:structureKeys)${expressCondition} ORDER BY o.id ASC `, { replacements, type: this.ctx.model.QueryTypes.SELECT, transaction, }); // 行归一化口径与 getWaveStrategyFetchCandidateOrders 保持一致 const mergedRows = (Array.isArray(rows) ? rows : []) .map(row => ({ id: Number(row && row.id || 0), items_hash: String(row && row.items_hash || '').trim(), items: String(row && row.items || '').trim(), logistics_name: String(row && row.logistics_name || '').trim(), sys_logistics_code: String(row && row.sys_logistics_code || '').trim(), logistics_code: String(row && row.logistics_code || '').trim(), items_count: Number(row && row.items_count || 0), items_total: Number(row && row.items_total || 0), })) .filter(row => Number.isInteger(row.id) && row.id > 0) .sort((a, b) => a.id - b.id); if (mergedRows.length === 0) { return null; } // 合并订单并入候选(按 id 去重,第一池候选与全池查询结果存在重叠) const candidateIdSet = new Set(candidateRows.map(row => Number(row && row.id || 0))); const mergedCandidateRows = [ ...candidateRows, ...mergedRows.filter(row => !candidateIdSet.has(row.id)), ].sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); // 无新增订单时视为无需合并,返回 null 维持现状 if (mergedCandidateRows.length <= candidateRows.length) { return null; } return mergedCandidateRows; } /** * 自动补齐按策略抓取的 selected_wave_ids / selected_order_ids。 * * 仅用于 PDA 按策略抓取场景,内部按 strategy_type + pick_mode 执行分流。 * * 候选订单按创建时间分割为两个订单池: * - 第一订单池:创建时间早于今日 0 点(前一天及更早订单); * - 第二订单池:其余订单(今日订单)。 * 只有第一订单池抓取完毕(候选为空)才会抓取第二订单池,确保前一天的订单优先出库。 * * 小团购(pickMode=1)第一池抓取时,会将第一池候选分组中同结构的全池订单并入候选 * (见 mergeWaveStrategyFirstPoolSameStructureOrders),避免同结构订单被两池分割后单独成波。 * * @param {Object} params 自动分流参数。 * @param {Object} params.plan 抓取计划。 * @param {Object} params.strategyRow 策略行。 * @param {number|string} [params.waveBatchSource=0] 波次来源。 * @param {Object} params.transaction 事务对象。 * @return {Promise} 自动补齐结果。 */ async autoPopulateWaveStrategyFetchSelections(params = {}) { const plan = this.isPlainObject(params.plan) ? params.plan : {}; const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; const transaction = params.transaction; const waveBatchSourceInput = Number(params.waveBatchSource); const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; const operatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0); const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null; const claimOperatorId = operatorId > 0 ? operatorId : null; await this.ensureNoActiveWavePickTaskForOperator({ warehouseId, operatorId, transaction, }); const candidateQueryParams = { warehouseId, strategyId, minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), }; // 订单池分割:第一订单池 = 创建时间早于今日 0 点(前一天及更早订单), // 只有第一订单池抓取完毕(候选为空)才允许抓取第二订单池, // 确保前一天的订单可以优先出库。 const todayStart = this.buildWaveStrategyFetchTodayStart(); const firstPoolRows = await this.getWaveStrategyFetchCandidateOrders({ ...candidateQueryParams, createdBefore: todayStart, }); let candidateRows; let candidatePoolStage = 'second'; if (firstPoolRows.length > 0) { candidateRows = firstPoolRows; candidatePoolStage = 'first'; } else { candidateRows = await this.getWaveStrategyFetchCandidateOrders(candidateQueryParams); } const candidateCount = candidateRows.length; if (candidateCount <= 0) { throw new Error('未找到符合策略且未分配波次的候选订单'); } const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); if (groupedRows.length <= 0) { throw new Error('候选订单缺少有效商品结构,无法创建波次'); } const result = { selected_wave_ids: [], selected_order_ids: [], removed_order_ids: [], candidate_count: candidateCount, candidate_pool_stage: candidatePoolStage, first_pool_candidate_count: firstPoolRows.length, grouped_count: groupedRows.length, merged_order_count: 0, wave_prefix: '', wave_prefix_source: '', }; const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ warehouseId, strategyType, strategyRow, }); result.wave_prefix = wavePrefixResolution.wavePrefix; result.wave_prefix_source = wavePrefixResolution.source; if (strategyType === 2) { const requireSameExpress = Number(strategyRow.require_same_express || 0) === 1; let effectiveGroupedRows = requireSameExpress ? this.groupWaveStrategyFetchCandidateOrdersByStructure( this.filterCandidateOrdersByRequireSameExpress(candidateRows) ) : groupedRows; // 小团购(pickMode=1)第一池抓取:将同结构全池订单并入候选,修复「1 单 1 波次」问题。 // 合并受 pickMode=1 + 第一池阶段 + max_same_structure 有效三重门控; // pickMode=5(大团购)不生效,admin 抓取入口(executeWaveStrategyDirectFetch)不经过本方法。 const mergedCandidateRows = await this.mergeWaveStrategyFirstPoolSameStructureOrders({ warehouseId, strategyRow, candidateRows, effectiveGroupedRows, candidatePoolStage, pickMode, requireSameExpress, transaction, }); if (mergedCandidateRows !== null) { result.merged_order_count = mergedCandidateRows.length - candidateRows.length; effectiveGroupedRows = requireSameExpress ? this.groupWaveStrategyFetchCandidateOrdersByStructure( this.filterCandidateOrdersByRequireSameExpress(mergedCandidateRows) ) : this.groupWaveStrategyFetchCandidateOrdersByStructure(mergedCandidateRows); } const groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; const selectedGroups = effectiveGroupedRows .slice(0, groupLimit); if (selectedGroups.length === 0) { throw new Error('团购策略未找到可创建波次的同结构分组'); } for (const group of selectedGroups) { const created = await this.createWaveBatchByOrderIdsInTransaction({ warehouseId, orderIds: group.order_ids, waveType: 1, wavePrefix: wavePrefixResolution.wavePrefix, source: waveBatchSource, claimOperator, claimOperatorId, transaction, }); result.selected_wave_ids.push(created.waveId); result.selected_order_ids.push(...created.selectedOrderIds); } if (result.selected_wave_ids.length <= 0) { throw new Error('团购策略创建波次失败:无有效波次生成'); } } else if (strategyType === 1) { const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) : candidateRows; const effectiveGroupedRows = effectiveCandidateRows === candidateRows ? groupedRows : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); const mergedOrderIds = [ ...new Set(effectiveGroupedRows .flatMap(group => group.order_ids) .map(id => Number(id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (mergedOrderIds.length === 0) { throw new Error('散单策略无可用候选订单'); } const orderLimitRaw = Number(plan.order_limit || strategyRow.batch_max_orders || 0); const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; let selectedOrderIds = []; if (pickMode === 3) { const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ warehouseId, orderIds: mergedOrderIds, }); const skuLimitRaw = Number(plan.sku_limit || strategyRow.batch_max_skus || 0); const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ orderIds: mergedOrderIds, orderSkuMap: skuMap, skuLimit, }); result.removed_order_ids = skuResult.removedOrderIds; selectedOrderIds = skuResult.selectedOrderIds; } else if (pickMode === 4 || pickMode === 2) { selectedOrderIds = mergedOrderIds; } else { throw new Error(`散单策略不支持的 pick_mode: ${pickMode}`); } if (selectedOrderIds.length <= 0) { throw new Error('散单策略筛选后无可用订单(候选可能已被剔除)'); } const limitedOrderIds = orderLimit > 0 ? selectedOrderIds.slice(0, orderLimit) : selectedOrderIds; if (limitedOrderIds.length <= 0) { throw new Error('散单策略筛选后无可用订单(batch_max_orders 限制导致为空)'); } const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ warehouseId, orderIds: limitedOrderIds, waveType: 2, wavePrefix: wavePrefixResolution.wavePrefix, source: waveBatchSource, pickMode, claimOperator, claimOperatorId, transaction, }); result.selected_wave_ids.push(createdWave.waveId); result.selected_order_ids.push(...createdWave.selectedOrderIds); if (result.selected_wave_ids.length <= 0) { throw new Error('散单策略创建波次失败:无有效波次生成'); } } else { throw new Error(`不支持的策略类型: ${strategyType}`); } result.selected_wave_ids = [ ...new Set(result.selected_wave_ids) ].sort((a, b) => a - b); result.selected_order_ids = [ ...new Set(result.selected_order_ids) ].sort((a, b) => a - b); this.ctx.logger.info('[wave.autoPopulateWaveStrategyFetchSelections] 自动分流完成', { strategy_id: strategyId, warehouse_id: warehouseId, pick_mode: pickMode, strategy_type: strategyType, wave_prefix: result.wave_prefix, wave_prefix_source: result.wave_prefix_source, candidate_count: result.candidate_count, candidate_pool_stage: result.candidate_pool_stage, first_pool_candidate_count: result.first_pool_candidate_count, merged_order_count: result.merged_order_count, today_start: todayStart, removed_count: result.removed_order_ids.length, selected_count: result.selected_order_ids.length, selected_wave_count: result.selected_wave_ids.length, }); return result; } /** * 按策略直接抓取候选订单并创建波次(不创建拣货任务)。 * * 在一个事务内完成候选查询、分组与建波: * - 团购策略(strategy_type=2):每个结构分组创建一个波次; * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次。 * * @param {Object} params 执行参数。 * @param {Object} params.plan 预处理计划。 * @param {Object} [params.strategyRow={}] 策略行(可选,默认取 plan.strategy_row)。 * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略抓取 2-PDA策略抓取。 * @return {Promise} 建波结果汇总。 */ async executeWaveStrategyDirectFetch(params = {}) { const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; const strategyRow = this.isPlainObject(params && params.strategyRow) ? params.strategyRow : (this.isPlainObject(plan.strategy_row) ? plan.strategy_row : {}); const waveBatchSourceInput = Number(params && params.waveBatchSource); const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); const pickModeInput = Number(plan.pick_mode || 0); const pickMode = [ 1, 2, 3, 4, 5 ].includes(pickModeInput) ? pickModeInput : 0; const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null; const claimOperatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0) > 0 ? Number((operatorInfo.operator_id ?? operatorInfo.id)) : null; const transaction = await this.ctx.model.transaction(); try { const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ warehouseId, strategyId, minSameStructure: strategyRow.min_same_structure, maxSameStructure: strategyRow.max_same_structure, requireSameExpress: Number(strategyRow.require_same_express || 0), }); const candidateCount = candidateRows.length; if (candidateCount <= 0) { throw new Error('未找到符合策略且未分配波次的候选订单'); } const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); if (groupedRows.length <= 0) { throw new Error('候选订单缺少有效商品结构,无法创建波次'); } const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ warehouseId, strategyType, strategyRow, }); const createdWaveIds = []; const createdWaveNos = []; const createdOrderIds = []; if (strategyType === 2) { const effectiveGroupedRows = Number(strategyRow.require_same_express || 0) === 1 ? this.groupWaveStrategyFetchCandidateOrdersByStructure( this.filterCandidateOrdersByRequireSameExpress(candidateRows) ) : groupedRows; for (const group of effectiveGroupedRows) { const created = await this.createWaveBatchByOrderIdsInTransaction({ warehouseId, orderIds: group.order_ids, waveType: 1, wavePrefix: wavePrefixResolution.wavePrefix, source: waveBatchSource, claimOperator, claimOperatorId, transaction, }); createdWaveIds.push(created.waveId); createdWaveNos.push(created.waveNo); createdOrderIds.push(...created.selectedOrderIds); } } else if (strategyType === 1) { const effectiveCandidateRows = Number(strategyRow.require_same_express || 0) === 1 ? this.filterCandidateOrdersByRequireSameExpress(candidateRows) : candidateRows; const effectiveGroupedRows = effectiveCandidateRows === candidateRows ? groupedRows : this.groupWaveStrategyFetchCandidateOrdersByStructure(effectiveCandidateRows); const mergedOrderIds = [ ...new Set(effectiveGroupedRows .flatMap(group => group.order_ids) .map(id => Number(id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); if (mergedOrderIds.length <= 0) { throw new Error('散单策略无可用候选订单'); } const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ warehouseId, orderIds: mergedOrderIds, waveType: 2, wavePrefix: wavePrefixResolution.wavePrefix, source: waveBatchSource, pickMode, claimOperator, claimOperatorId, transaction, }); createdWaveIds.push(createdWave.waveId); createdWaveNos.push(createdWave.waveNo); createdOrderIds.push(...createdWave.selectedOrderIds); } else { throw new Error(`不支持的策略类型: ${strategyType}`); } const normalizedWaveIds = [ ...new Set(createdWaveIds) ].sort((a, b) => a - b); const normalizedWaveNos = [ ...new Set(createdWaveNos.map(item => String(item || '').trim()).filter(Boolean)) ]; const normalizedOrderIds = [ ...new Set(createdOrderIds) ].sort((a, b) => a - b); if (normalizedWaveIds.length <= 0 || normalizedOrderIds.length <= 0) { throw new Error('按策略抓取建波失败:未生成有效波次或订单结果'); } const result = { wave_ids: normalizedWaveIds, wave_nos: normalizedWaveNos, order_ids: normalizedOrderIds, created_wave_count: normalizedWaveIds.length, created_order_count: normalizedOrderIds.length, wave_prefix: wavePrefixResolution.wavePrefix, wave_prefix_source: wavePrefixResolution.source, candidate_count: candidateCount, grouped_count: groupedRows.length, strategy_type: strategyType, }; await transaction.commit(); // 写入订单操作日志:策略抓取分配到波次 const strategyLogItems = normalizedOrderIds.map(orderId => ({ orderId, operationCode: 'ORDER_WAVE_STRATEGY_FETCH', message: `策略(${strategyId})抓取分配到波次 ${normalizedWaveNos.join(',')}`, })); await this.batchCreateOrderOperationLogs(strategyLogItems, { warehouseId, scene: 'executeWaveStrategyDirectFetch', }); this.ctx.logger.info('[wave.executeWaveStrategyDirectFetch] 按策略直接建波完成', { strategy_id: strategyId, warehouse_id: warehouseId, strategy_type: strategyType, wave_prefix: result.wave_prefix, wave_prefix_source: result.wave_prefix_source, candidate_count: result.candidate_count, grouped_count: result.grouped_count, created_wave_count: result.created_wave_count, created_order_count: result.created_order_count, }); return result; } catch (error) { await transaction.rollback(); throw error; } } /** * 执行按策略抓取任务创建主流程。 * * 该方法在一个事务内完成任务主表、明细表、断点与日志的初始化写入。 * * @param {Object} params 创建参数。 * @param {Object} params.plan 预处理后的抓取计划。 * @param {Object} [params.data={}] 原始请求数据。 * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 创建结果。 */ async createWavePickTaskFromPlan(params = {}) { const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; const requestData = this.isPlainObject(params && params.data) ? params.data : {}; const autoPopulateSelections = Boolean(params && params.autoPopulateSelections); const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); const waveBatchSourceInput = Number( params && params.waveBatchSource !== undefined ? params.waveBatchSource : plan.wave_batch_source ); const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; let effectivePlan = { ...plan, }; let effectiveRequestData = { ...requestData, }; const hasExplicitWaveSelectionInput = [ 'selected_wave_ids', 'selectedWaveIds', 'wave_ids', 'waveIds', 'wave_id', 'waveId', ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); const hasExplicitOrderSelectionInput = [ 'selected_order_ids', 'selectedOrderIds', 'order_ids', 'orderIds', ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); const hasManualSelectionInput = this.normalizeIdsInput(plan.selected_wave_ids || []).length > 0 || hasExplicitWaveSelectionInput || hasExplicitOrderSelectionInput; const normalizedCartId = this.normalizePositiveInteger( effectiveRequestData.cart_id ?? effectiveRequestData.cartId, 'cart_id', 0 ); const transaction = await this.ctx.model.transaction(); try { if (autoPopulateSelections && !hasManualSelectionInput) { const autoFilled = await this.autoPopulateWaveStrategyFetchSelections({ plan: effectivePlan, strategyRow: effectivePlan.strategy_row, waveBatchSource, transaction, }); effectivePlan = { ...effectivePlan, selected_wave_ids: autoFilled.selected_wave_ids, box_assignments: this.buildWaveStrategyFetchBoxAssignments({ pickMode, selectedWaveIds: autoFilled.selected_wave_ids, boxLimit: Number(effectivePlan.box_limit || 0), }), }; effectiveRequestData = { ...effectiveRequestData, selected_wave_ids: autoFilled.selected_wave_ids, selected_order_ids: autoFilled.selected_order_ids, }; } const selectedWaveIds = this.normalizeIdsInput(effectivePlan.selected_wave_ids || []); const selectedOrderIds = this.normalizeIdsInput( effectiveRequestData.selected_order_ids !== undefined ? effectiveRequestData.selected_order_ids : effectiveRequestData.selectedOrderIds !== undefined ? effectiveRequestData.selectedOrderIds : effectiveRequestData.order_ids !== undefined ? effectiveRequestData.order_ids : effectiveRequestData.orderIds ); const validationErrors = Array.isArray(effectivePlan.validation_errors) ? [ ...effectivePlan.validation_errors ] : []; if ([ 1, 5 ].includes(pickMode) && selectedWaveIds.length === 0) { validationErrors.push('当前模式依赖波次,selected_wave_ids 不能为空'); } if ([ 2, 3, 4 ].includes(pickMode) && selectedOrderIds.length === 0) { validationErrors.push('当前模式至少需要一个订单,selected_order_ids 不能为空'); } if (validationErrors.length > 0) { throw new Error(`按策略抓取任务创建校验失败: ${validationErrors.join(';')}`); } if (normalizedCartId > 0) { await this.ensurePickCartAvailable({ cartId: normalizedCartId, warehouseId, transaction, }); } // 查询所有选中波次的 wave_no(用于任务主表 batch_no_array 与任务波次关联记录) const waveNoMap = new Map(); if (selectedWaveIds.length > 0) { const waveNoRows = await this.ctx.model.query( `SELECT wave_id, wave_no FROM wms_wave_batch WHERE wave_id IN (:waveIds) AND warehouse_id = :warehouseId`, { replacements: { waveIds: selectedWaveIds, warehouseId }, type: this.ctx.model.QueryTypes.SELECT, transaction, } ); for (const row of Array.isArray(waveNoRows) ? waveNoRows : []) { const wid = Number(row && row.wave_id || 0); const wno = String(row && row.wave_no || '').trim(); if (wid > 0 && wno) { waveNoMap.set(wid, wno); } } } // 散单模式:取第一个选中波次的 wave_no 写入任务 batch_no const resolvedBatchNo = [ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0 ? (waveNoMap.get(selectedWaveIds[0]) || null) : null; const taskPayload = this.buildTaskCreatePayload({ plan: effectivePlan, data: effectiveRequestData, selectedWaveIds, selectedOrderIds, cartId: normalizedCartId, }); if (resolvedBatchNo !== null) { taskPayload.batch_no = resolvedBatchNo; } // 逗号分隔写入任务主表 batch_no_array,便于统计与查询 const batchNoArray = selectedWaveIds .map(waveId => waveNoMap.get(waveId) || '') .filter(Boolean) .join(','); if (batchNoArray) { taskPayload.batch_no_array = batchNoArray; } if (selectedWaveIds.length > 0 && [ 1, 2 ].includes(waveBatchSource)) { await this.ctx.model.query(` UPDATE wms_wave_batch SET source = :source, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) `, { replacements: { source: waveBatchSource, warehouseId, waveIds: selectedWaveIds, }, transaction, }); } const taskCreateResult = await this.createWavePickTaskWithRetry(taskPayload, transaction); const taskId = Number(taskCreateResult.task_id || 0); const taskNo = String(taskCreateResult.task_no || '').trim(); const taskWaveRows = this.buildTaskWaveRows({ taskId, plan: effectivePlan, selectedWaveIds, waveNoMap, }); // 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致 const waveIndexMap = new Map(); if (selectedOrderIds.length > 0 && selectedWaveIds.length > 0) { try { const waveIndexRows = await this.ctx.model.query( `SELECT order_id, wave_index FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) AND order_id IN (:orderIds)`, { replacements: { warehouseId, waveIds: selectedWaveIds, orderIds: selectedOrderIds, }, type: this.ctx.model.QueryTypes.SELECT, transaction, } ); for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { const wrOrderId = Number(wr && wr.order_id || 0); if (wrOrderId > 0) { waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); } } } catch (e) { this.ctx.logger.warn('[wave.createTask] 查询波次索引失败,box_no 将退化为任务内序号', { error: e && e.message, warehouseId, waveIds: selectedWaveIds, }); } } const taskOrderRows = this.buildTaskOrderRows({ taskId, plan: effectivePlan, selectedWaveIds, selectedOrderIds, cartId: normalizedCartId, waveIndexMap, }); const taskSkuRows = await this.buildTaskSkuRows({ plan: effectivePlan, selectedOrderIds, }); const taskBoxRows = this.buildTaskBoxRows({ taskId, taskNo, plan: effectivePlan, taskWaveRows, taskOrderRows, taskSkuRows, }); if (taskWaveRows.length > 0) { await this.bulkInsertRows('wms_wave_pick_task_wave', taskWaveRows, transaction); } if (taskOrderRows.length > 0) { await this.bulkInsertRows('wms_wave_pick_task_order', taskOrderRows, transaction); } if (taskBoxRows.length > 0) { await this.bulkInsertRows('wms_wave_pick_task_box', taskBoxRows, transaction); } if (normalizedCartId > 0) { await this.bindPickCartForTask({ taskId, cartId: normalizedCartId, warehouseId, operatorId: taskPayload.pick_user_id, transaction, }); } await this.initTaskCheckpointAndLogs({ taskId, taskNo, plan: effectivePlan, data: effectiveRequestData, selectedOrderIds, cartId: normalizedCartId, operatorId: taskPayload.pick_user_id, operatorName: taskPayload.pick_user_name, transaction, }); await transaction.commit(); // 写入订单操作日志:分配到波次 if (selectedOrderIds.length > 0) { const waveNoList = taskWaveRows .map(r => String(r && r.wave_no || '').trim()) .filter(Boolean); const waveNoMessage = waveNoList.length > 0 ? waveNoList.join(',') : ''; await this.batchCreateOrderOperationLogs( selectedOrderIds.map(orderId => ({ orderId, operationCode: 'ORDER_WAVE_ASSIGN', message: `分配到波次 ${waveNoMessage}`, })), { warehouseId, scene: 'createWavePickTaskFromPlan' } ); } return { task_id: taskId, task_no: taskNo, state: 'created', plan_summary: { pick_mode: pickMode, wave_count: taskWaveRows.length, order_count: taskOrderRows.length, box_count: taskBoxRows.length, cart_id: normalizedCartId > 0 ? normalizedCartId : null, }, }; } catch (error) { const errorDetail = { name: String(error && error.name || ''), message: String(error && error.message || ''), stack: String(error && error.stack || '').split('\n').slice(0, 6) .join('\n'), sql: String(error && error.sql || '').slice(0, 500), errorType: Object.prototype.toString.call(error), errors: Array.isArray(error && error.errors) ? error.errors.map(e => ({ message: e.message, type: e.type, path: e.path, value: e.value })) : [], }; this.ctx.logger.error('[wave.createWavePickTaskFromPlan] 任务创建异常详情', errorDetail); await transaction.rollback(); throw error; } } /** * 构建任务主表写入载荷。 * * @param {Object} options 构建参数。 * @param {Object} options.plan 预处理计划。 * @param {Object} options.data 原始请求数据。 * @param {Array} options.selectedWaveIds 已选波次ID。 * @param {Array} options.selectedOrderIds 已选订单ID。 * @param {number} options.cartId 拣货车ID。 * @return {Object} 主表写入载荷。 */ buildTaskCreatePayload(options = {}) { const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; const data = this.isPlainObject(options && options.data) ? options.data : {}; const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) ? options.selectedWaveIds : []; const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) ? options.selectedOrderIds : []; const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const source = String(plan.source || 'unknown').trim(); const sourceCode = source === 'admin' ? 2 : 1; const operator = this.isPlainObject(plan.operator) ? plan.operator : {}; const rawOperatorId = operator.operator_id ?? operator.id; const normalizedOperatorId = Number(rawOperatorId); const pickUserId = Number.isInteger(normalizedOperatorId) && normalizedOperatorId >= 0 ? normalizedOperatorId : 0; const pickUserName = String(operator.operator_name || operator.name || this.getOrderLogOperator().name || 'system').trim() || 'system'; const taskNo = String(data.task_no || '').trim() || this.generateWavePickTaskNo(warehouseId, sourceCode); return { task_no: taskNo, warehouse_id: warehouseId, wave_id: selectedWaveIds.length > 0 ? selectedWaveIds[0] : null, pick_mode: pickMode, status: 0, source: sourceCode, wave_count: selectedWaveIds.length, order_count: selectedOrderIds.length, box_count: pickMode === 5 ? 1 : 0, batch_no: null, batch_no_array: null, pick_user_id: pickUserId, pick_user_name: pickUserName, current_cart_id: Number(options && options.cartId || 0) > 0 ? Number(options.cartId) : null, current_cart_code_snapshot: null, review_status: 0, review_version: 0, device_id: String(data.device_id || data.deviceId || '').trim() || `wave_${source}_${warehouseId}`, ext_json: JSON.stringify({ strategy_id: plan.strategy_id, wave_limit: Number(plan.wave_limit || 0), order_limit: Number(plan.order_limit || 0), sku_limit: Number(plan.sku_limit || 0), box_limit: Number(plan.box_limit || 0), dynamic_append: Boolean(plan.dynamic_append), }), }; } /** * 构建任务波次关联写入行。 * * @param {Object} options 构建参数。 * @param {number} options.taskId 任务ID。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.selectedWaveIds 已选波次ID。 * @param {Map} [options.waveNoMap] wave_id → wave_no 映射。 * @return {Array} 任务波次关联行。 */ buildTaskWaveRows(options = {}) { const taskId = Number(options && options.taskId || 0); const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) ? options.selectedWaveIds : []; const waveNoMap = options && options.waveNoMap instanceof Map ? options.waveNoMap : new Map(); return selectedWaveIds.map((waveId, index) => ({ task_id: taskId, wave_id: waveId, wave_no: waveNoMap.get(waveId) || null, box_no: index + 1, status: 0, bind_time: null, pick_time: null, warehouse_id: warehouseId, })); } /** * 构建任务订单明细写入行。 * * box_no 与 wms_order_wave_index.wave_index 保持一致(波次内全局顺序)。 * 若 waveIndexMap 中无对应记录,则退化为当前订单在 selectedOrderIds 中的 index + 1。 * * @param {Object} options 构建参数。 * @param {number} options.taskId 任务ID。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.selectedWaveIds 已选波次ID。 * @param {Array} options.selectedOrderIds 已选订单ID。 * @param {number} options.cartId 绑定车ID。 * @param {Map} [options.waveIndexMap] orderId → wave_index 映射。 * @return {Array} 任务订单行。 */ buildTaskOrderRows(options = {}) { const taskId = Number(options && options.taskId || 0); const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; const pickMode = Number(plan.pick_mode || 0); const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) ? options.selectedWaveIds : []; const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) ? options.selectedOrderIds : []; const cartId = Number(options && options.cartId || 0); const waveIndexMap = options && options.waveIndexMap instanceof Map ? options.waveIndexMap : new Map(); if (![ 2, 3, 4 ].includes(pickMode)) { return []; } const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; return selectedOrderIds.map((orderId, index) => { const waveIndex = waveIndexMap.has(orderId) ? Number(waveIndexMap.get(orderId) || 0) : 0; return { task_id: taskId, wave_id: defaultWaveId, order_id: orderId, order_no: null, box_no: waveIndex > 0 ? waveIndex : (index + 1), cart_id: cartId > 0 ? cartId : null, cart_code_snapshot: null, warehouse_id: warehouseId, pick_status: 0, review_status: 0, review_user_id: null, review_result: null, review_remark: null, exception_reason: null, picked_time: null, review_time: null, }; }); } /** * 构建任务 SKU 明细写入行(仅先拣后分模式使用)。 * * @param {Object} options 构建参数。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.selectedOrderIds 已选订单ID。 * @return {Promise>} 任务 SKU 行。 */ async buildTaskSkuRows(options = {}) { const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; const pickMode = Number(plan.pick_mode || 0); const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) ? this.normalizeIdsInput(options.selectedOrderIds) : []; if (pickMode !== 3 || selectedOrderIds.length <= 0) { return []; } const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { throw new Error('订单明细模型不可用'); } const itemRows = await orderItemsModel.findAll({ where: { order_id: { [Op.in]: selectedOrderIds }, }, attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], raw: true, }); const skuMap = new Map(); for (const row of (Array.isArray(itemRows) ? itemRows : [])) { const normalized = this.normalizeOrderItemRow(row); if (normalized.quantity <= 0) { continue; } const skuId = Number(normalized.stock_id || 0); const itemCode = String(normalized.item_code || '').trim(); const itemName = String(normalized.item_name || '').trim(); if (!(Number.isInteger(skuId) && skuId > 0) && !itemCode) { continue; } const key = Number.isInteger(skuId) && skuId > 0 ? `stock_${skuId}` : `code_${itemCode}`; if (!skuMap.has(key)) { skuMap.set(key, { sku_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, ref_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, ref_label: itemName || itemCode || null, required_qty: 0, }); } const aggregated = skuMap.get(key); aggregated.required_qty += normalized.quantity; if (!aggregated.ref_label && (itemName || itemCode)) { aggregated.ref_label = itemName || itemCode; } } return Array.from(skuMap.values()) .sort((a, b) => { const leftSkuId = Number(a.sku_id || 0); const rightSkuId = Number(b.sku_id || 0); if (leftSkuId !== rightSkuId) { return leftSkuId - rightSkuId; } return String(a.ref_label || '').localeCompare(String(b.ref_label || '')); }) .map((row, index) => ({ box_no: index + 1, sku_id: row.sku_id, ref_id: row.ref_id, ref_label: row.ref_label, required_qty: Number(row.required_qty || 0), })); } /** * 构建任务框明细写入行。 * * @param {Object} options 构建参数。 * @param {number} options.taskId 任务ID。 * @param {string} options.taskNo 任务编号。 * @param {Object} options.plan 预处理计划。 * @param {Array} options.taskWaveRows 任务波次行。 * @param {Array} options.taskOrderRows 任务订单行。 * @param {Array} options.taskSkuRows 任务 SKU 行。 * @return {Array} 任务框行。 */ buildTaskBoxRows(options = {}) { const taskId = Number(options && options.taskId || 0); const taskNo = String(options && options.taskNo || '').trim(); const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; const pickMode = Number(plan.pick_mode || 0); const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const taskWaveRows = Array.isArray(options && options.taskWaveRows) ? options.taskWaveRows : []; const taskOrderRows = Array.isArray(options && options.taskOrderRows) ? options.taskOrderRows : []; const taskSkuRows = Array.isArray(options && options.taskSkuRows) ? options.taskSkuRows : []; if ([ 1, 5 ].includes(pickMode)) { return taskWaveRows.map(row => ({ task_id: taskId, order_id: null, box_code: `${taskNo || taskId}-W${row.box_no}`, box_no: row.box_no, box_type: 3, ref_id: row.wave_id, ref_label: row.wave_no, required_qty: 0, picked_qty: 0, box_status: 0, review_result: null, review_user_id: null, review_time: null, warehouse_id: warehouseId, })); } if (pickMode === 3 && taskSkuRows.length > 0) { return taskSkuRows.map(row => ({ task_id: taskId, order_id: null, box_code: `${taskNo || taskId}-S${row.box_no}`, box_no: row.box_no, box_type: 1, ref_id: Number(row.ref_id || row.sku_id || 0) || null, ref_label: String(row.ref_label || '').trim() || null, required_qty: Number(row.required_qty || 0), picked_qty: 0, box_status: 0, review_result: null, review_user_id: null, review_time: null, warehouse_id: warehouseId, })); } return taskOrderRows.map(row => ({ task_id: taskId, order_id: row.order_id, box_code: `${taskNo || taskId}-O${row.box_no}`, box_no: row.box_no, box_type: 2, ref_id: row.order_id, ref_label: null, required_qty: 0, picked_qty: 0, box_status: 0, review_result: null, review_user_id: null, review_time: null, warehouse_id: warehouseId, })); } /** * 领单时绑定拣货车并更新车辆主表。 * * @param {Object} params 绑定参数。 * @param {number} params.taskId 任务ID。 * @param {number} params.cartId 拣货车ID。 * @param {number} params.warehouseId 仓库ID。 * @param {number} params.operatorId 操作人ID。 * @param {Object} params.transaction 事务对象。 * @return {Promise} 无返回值。 */ async bindPickCartForTask(params = {}) { const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const transaction = params.transaction; const operatorId = Number.isInteger(Number(params.operatorId)) ? Number(params.operatorId) : 0; const cartRows = await this.ctx.model.query(` SELECT id, cart_code FROM wms_pick_cart WHERE id = :cartId AND warehouse_id = :warehouseId AND status = 1 FOR UPDATE `, { replacements: { cartId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const cartRow = Array.isArray(cartRows) ? cartRows[0] : null; if (!cartRow) { throw new Error(`拣货车不存在或已停用: ${cartId}`); } // 通过绑定表判断车是否被其他活跃任务占用(不依赖 wms_pick_cart.current_task_id) // 仅以 wms_pick_task_cart_binding.is_active = 1 为准,不关联任务状态做二次过滤 const bindingRows = await this.ctx.model.query(` SELECT b.task_id FROM wms_pick_task_cart_binding b WHERE b.cart_id = :cartId AND b.warehouse_id = :warehouseId AND b.is_active = 1 LIMIT 1 FOR UPDATE `, { replacements: { cartId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const activeBindingTaskId = Number( (Array.isArray(bindingRows) && bindingRows.length > 0 ? bindingRows[0]?.task_id : 0) ); if (activeBindingTaskId > 0 && activeBindingTaskId !== taskId) { throw new Error(`拣货车已被活动任务占用: ${cartId}`); } await this.bulkInsertRows('wms_pick_task_cart_binding', [{ task_id: taskId, cart_id: cartId, cart_code_snapshot: String(cartRow.cart_code || '').trim() || null, warehouse_id: warehouseId, bind_user_id: operatorId, bind_type: 1, unbind_user_id: null, is_active: 1, bind_time: new Date(), unbind_time: null, }], transaction); await this.ctx.model.query(` UPDATE wms_wave_pick_task SET current_cart_id = :cartId, current_cart_code_snapshot = :cartCode WHERE id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, cartId, cartCode: String(cartRow.cart_code || '').trim() || null, warehouseId, }, transaction, }); } /** * 初始化任务断点、动作日志与轨迹。 * * @param {Object} params 初始化参数。 * @param {number} params.taskId 任务ID。 * @param {string} params.taskNo 任务编号。 * @param {Object} params.plan 预处理计划。 * @param {Object} params.data 原始请求数据。 * @param {Array} params.selectedOrderIds 已选订单ID。 * @param {number} params.cartId 绑定车ID。 * @param {number} params.operatorId 操作人ID。 * @param {string} params.operatorName 操作人姓名。 * @param {Object} params.transaction 事务对象。 * @return {Promise} 无返回值。 */ async initTaskCheckpointAndLogs(params = {}) { const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); const taskNo = String(params.taskNo || '').trim(); const plan = this.isPlainObject(params.plan) ? params.plan : {}; const data = this.isPlainObject(params.data) ? params.data : {}; const transaction = params.transaction; const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); const operatorId = Number.isInteger(Number(params.operatorId)) ? Number(params.operatorId) : 0; const operatorName = String(params.operatorName || 'system').trim() || 'system'; const cartId = Number(params.cartId || 0) > 0 ? Number(params.cartId) : null; const selectedOrderIds = Array.isArray(params.selectedOrderIds) && params.selectedOrderIds.length > 0 ? params.selectedOrderIds : [ 0 ]; const deviceId = String(data.device_id || data.deviceId || '').trim() || `device_${warehouseId}`; const requestId = String(data.request_id || data.requestId || `${taskNo || taskId}_init`).trim(); await this.bulkInsertRows('wms_wave_pick_checkpoint', [{ task_id: taskId, warehouse_id: warehouseId, pick_user_id: operatorId, device_id: deviceId, current_location_id: null, current_sku_id: null, current_box_no: null, picked_count: 0, remaining_count: Math.max(selectedOrderIds.length, 0), last_event_id: null, last_seq_no: null, checkpoint_json: JSON.stringify({ state: 'created', task_no: taskNo, }), version: 0, }], transaction); await this.bulkInsertRows('wms_wave_pick_action_log', [{ task_id: taskId, warehouse_id: warehouseId, wave_id: Array.isArray(plan.selected_wave_ids) && plan.selected_wave_ids.length > 0 ? Number(plan.selected_wave_ids[0]) : null, order_id: selectedOrderIds[0], sku_id: null, location_id: null, box_no: null, cart_id: cartId, qty_delta: 0, action_type: 'init', request_id: `${requestId}_${taskId}`, operator_id: operatorId, device_id: deviceId, seq_no: 1, snapshot: JSON.stringify({ task_no: taskNo, state: 'created', }), }], transaction); const traceRows = selectedOrderIds.map(orderId => ({ warehouse_id: warehouseId, order_id: Number(orderId), task_id: taskId, cart_id: cartId, cart_code_snapshot: null, pick_user_id: operatorId, pick_time: null, review_user_id: null, review_time: null, review_result: null, event_type: 'task_created', event_desc: `任务创建: ${taskNo || taskId}`, operator_id: operatorId, operator_name: operatorName, snapshot: JSON.stringify({ task_no: taskNo, pick_mode: Number(plan.pick_mode || 0), }), })); await this.bulkInsertRows('wms_order_pick_trace', traceRows, transaction); } /** * 校验拣货车是否可占用。 * * @param {Object} params 校验参数。 * @param {number} params.cartId 拣货车ID。 * @param {number} params.warehouseId 仓库ID。 * @param {Object} params.transaction 事务对象。 * @return {Promise} 无返回值。 */ async ensurePickCartAvailable(params = {}) { const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); const transaction = params.transaction; const rows = await this.ctx.model.query(` SELECT b.task_id FROM wms_pick_task_cart_binding b INNER JOIN wms_wave_pick_task t ON t.id = b.task_id WHERE b.cart_id = :cartId AND b.warehouse_id = :warehouseId AND b.is_active = 1 AND t.status IN (0, 1) LIMIT 1 FOR UPDATE `, { replacements: { cartId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); if (Array.isArray(rows) && rows.length > 0) { throw new Error(`拣货车已绑定活动任务: ${cartId}`); } } /** * 生成任务编号。 * * @param {number} warehouseId 仓库ID。 * @param {number} sourceCode 来源编码。 * @return {string} 任务编号。 */ generateWavePickTaskNo(warehouseId, sourceCode) { const now = Date.now(); const rand = Math.random().toString(36).slice(2, 8) .toUpperCase(); return `WPT${warehouseId}${sourceCode}${now}${rand}`; } /** * 写入任务主表并在任务编号冲突时重试。 * * @param {Object} payload 主表载荷。 * @param {Object} transaction 事务对象。 * @return {Promise<{ task_id: number, task_no: string }>} 主表写入结果。 */ async createWavePickTaskWithRetry(payload = {}, transaction) { const maxRetry = 5; const warehouseId = this.normalizeRequiredPositiveInteger(payload.warehouse_id, 'warehouse_id'); for (let attempt = 1; attempt <= maxRetry; attempt += 1) { const candidateTaskNo = attempt === 1 && String(payload.task_no || '').trim() ? String(payload.task_no || '').trim() : this.generateWavePickTaskNo(warehouseId, Number(payload.source || 1)); const insertPayload = { ...payload, task_no: candidateTaskNo, batch_no_array: String(payload.batch_no_array || '').trim() || null, }; try { const createResult = await this.ctx.model.query(` INSERT INTO wms_wave_pick_task ( task_no, warehouse_id, wave_id, pick_mode, status, source, wave_count, order_count, box_count, batch_no, batch_no_array, pick_user_id, pick_user_name, current_cart_id, current_cart_code_snapshot, review_status, review_version, device_id, ext_json, create_time, update_time ) VALUES ( :task_no, :warehouse_id, :wave_id, :pick_mode, :status, :source, :wave_count, :order_count, :box_count, :batch_no, :batch_no_array, :pick_user_id, :pick_user_name, :current_cart_id, :current_cart_code_snapshot, :review_status, :review_version, :device_id, :ext_json, NOW(), NOW() ) `, { replacements: insertPayload, transaction, }); let insertedTaskId = this.extractInsertId(createResult); if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { transaction, }); insertedTaskId = this.extractLastInsertId(fallbackResult); } if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { throw new Error('创建任务失败,未获取到任务主键'); } return { task_id: insertedTaskId, task_no: candidateTaskNo, }; } catch (error) { const isDuplicateTaskNo = this.isTaskNoDuplicateError(error); if (isDuplicateTaskNo && attempt < maxRetry) { continue; } throw error; } } throw new Error('创建任务失败,任务编号重试次数已达上限'); } /** * 判断是否为 task_no 唯一键冲突。 * * @param {Error} error 数据库错误。 * @return {boolean} 是否冲突。 */ isTaskNoDuplicateError(error) { const message = String(error && error.message || '').toLowerCase(); const parentErrno = Number(error && error.parent && error.parent.errno || 0); return parentErrno === 1062 || message.includes('duplicate entry') || message.includes('uk_task_no'); } /** * 批量插入行数据。 * * @param {string} tableName 表名。 * @param {Array} rows 行数据。 * @param {Object} transaction 事务对象。 * @return {Promise} 实际写入行数。 */ async bulkInsertRows(tableName, rows = [], transaction) { if (!Array.isArray(rows) || rows.length === 0) { return 0; } const columns = Object.keys(rows[0]); if (columns.length === 0) { return 0; } const replacements = {}; const valueSqlList = rows.map((row, rowIndex) => { const placeholders = columns.map(column => { const key = `${column}_${rowIndex}`; replacements[key] = Object.prototype.hasOwnProperty.call(row, column) ? row[column] : null; return `:${key}`; }); return `(${placeholders.join(', ')})`; }); const columnSql = columns.map(column => `\`${column}\``).join(', '); const sql = `INSERT INTO ${tableName} (${columnSql}) VALUES ${valueSqlList.join(', ')}`; await this.ctx.model.query(sql, { replacements, transaction, }); return rows.length; } /** * 解析“存在未完成任务”异常信息中的任务标识。 * * @param {string} message 异常消息文本。 * @return {{ task_id: number|null, task_no: string|null }} 解析结果。 */ parseWaveStrategyExistingTaskInfo(message = '') { const normalizedMessage = String(message || ''); const match = normalizedMessage.match(/task_id=(\d+)(?:,task_no=([^\)\)\s]+))?/); if (!match) { return { task_id: null, task_no: null, }; } const parsedTaskId = Number(match[1] || 0); const parsedTaskNo = String(match[2] || '').trim(); return { task_id: Number.isInteger(parsedTaskId) && parsedTaskId > 0 ? parsedTaskId : null, task_no: parsedTaskNo || null, }; } /** * 按策略抓取任务壳子方法(仅 PDA 使用),仅受理请求并返回任务信息。 * * @param {Object} [data={}] 请求参数。 * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 * @return {Promise} 受理结果。 */ async waveStrategyFetchPda(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const strategyId = this.normalizeRequiredPositiveInteger( normalizedData.strategy_id ?? normalizedData.strategyId, 'strategy_id' ); let warehouseId; try { warehouseId = Number(this.getWarehouseId()); } catch (error) { throw new Error('未识别到当前仓库上下文'); } if (!Number.isInteger(warehouseId) || warehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const operatorInfo = this.getOrderLogOperator(); const plan = await this.prepareWaveStrategyFetchPlan({ strategyId, warehouseId, operator: { operator_id: operatorInfo.id, operator_name: operatorInfo.name, }, source: 'pda', data: normalizedData, }); if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { return this.fail('按策略抓取预处理校验失败', { data: { status: 'failed', fetch_state: 2, tip: '创建失败,请重试', task_id: null, can_enter_pick_flow: false, warehouse_id: warehouseId, strategy_id: strategyId, source: 'pda', plan, }, }, 400); } try { const createdTask = await this.createWavePickTaskFromPlan({ plan, data: normalizedData, waveBatchSource: 2, autoPopulateSelections: true, }); this.ctx.logger.info('[wave.waveStrategyFetchPda] 任务创建成功', { taskId: createdTask.task_id, taskNo: createdTask.task_no, warehouseId, strategyId, }); return this.success('ok', { status: 'success', fetch_state: 1, tip: '任务创建成功', task_id: createdTask.task_id, task_no: createdTask.task_no, can_enter_pick_flow: false, warehouse_id: warehouseId, strategy_id: strategyId, source: 'pda', state: createdTask.state, plan, plan_summary: createdTask.plan_summary, accepted_at: new Date().toISOString(), }); } catch (error) { const errorMessage = String(error && error.message || ''); if (errorMessage.includes('当前用户存在未完成任务')) { const existingTaskInfo = this.parseWaveStrategyExistingTaskInfo(errorMessage); return this.success('存在未完成任务', { status: 'failed', fetch_state: 3, tip: '存在未完成任务,已返回任务ID,可继续拣货', task_id: existingTaskInfo.task_id, task_no: existingTaskInfo.task_no, can_enter_pick_flow: true, warehouse_id: warehouseId, strategy_id: strategyId, source: 'pda', plan, }); } return this.fail(`按策略抓取任务创建失败: ${error.message}`, { data: { status: 'failed', fetch_state: 2, tip: '创建失败,请重试', task_id: null, can_enter_pick_flow: false, warehouse_id: warehouseId, strategy_id: strategyId, source: 'pda', plan, }, }, 500); } } /** * 公共拣货任务取消流程。 * * 仅允许取消状态为 0/1 的任务。取消后会回收拣货车绑定,并物理删除该任务 * 的任务-订单关联记录(wms_wave_pick_task_order),避免订单回池后残留脏数据。 * * 按任务来源区分行为: * - source=0/1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), * 使订单可重新参与后续策略抓取。 * - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。 * * 所有来源均会清理任务-波次关联(wms_wave_pick_task_wave)与任务-订单关联记录 * (wms_wave_pick_task_order)。 * * @param {Object} [params={}] 取消参数。 * @param {Array} params.taskIds 任务ID列表。 * @param {number} params.warehouseId 仓库ID。 * @param {number} params.operatorId 操作人ID。 * @param {string} params.operatorName 操作人名称。 * @param {number|null} [params.restrictCreatorId=null] 限制创建人ID。 * @return {Promise} 取消结果。 */ async cancelWavePickTasksInternal(params = {}) { const normalizedParams = this.isPlainObject(params) ? params : {}; const sourceTaskIds = Array.isArray(normalizedParams.taskIds) ? normalizedParams.taskIds : []; const normalizedTaskIds = [ ...new Set(sourceTaskIds .map(item => Number(item)) .filter(taskId => Number.isInteger(taskId) && taskId > 0)) ]; const warehouseId = Number(normalizedParams.warehouseId || 0); const operatorId = Number(normalizedParams.operatorId || 0); const operatorName = String(normalizedParams.operatorName || 'system').trim() || 'system'; const rawRestrictCreatorId = normalizedParams.restrictCreatorId; const restrictCreatorId = rawRestrictCreatorId === null || rawRestrictCreatorId === undefined ? null : Number(rawRestrictCreatorId); if (normalizedTaskIds.length === 0) { const error = new Error('task_ids 必须为非空数组'); error.statusCode = 400; error.data = {}; throw error; } if (!Number.isInteger(warehouseId) || warehouseId <= 0) { const error = new Error('未获取到仓库上下文'); error.statusCode = 400; error.data = {}; throw error; } if (!Number.isInteger(operatorId) || operatorId <= 0) { const error = new Error('未获取到操作人上下文'); error.statusCode = 400; error.data = {}; throw error; } if (restrictCreatorId !== null && (!Number.isInteger(restrictCreatorId) || restrictCreatorId <= 0)) { const error = new Error('取消任务创建人限制参数不合法'); error.statusCode = 400; error.data = {}; throw error; } const transaction = await this.ctx.model.transaction(); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const canceledAtColumnRows = await this.ctx.model.query(` SHOW COLUMNS FROM wms_wave_pick_task LIKE 'cancelled_at' `, { type: this.ctx.model.QueryTypes.SELECT, transaction, }); const hasCancelledAtColumn = Array.isArray(canceledAtColumnRows) && canceledAtColumnRows.length > 0; const cancelledTaskNos = []; const cancelOrderLogItems = []; let hasReleasedWaves = false; for (const taskId of normalizedTaskIds) { const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; const taskRows = await this.ctx.model.query(` SELECT id, task_no, warehouse_id, status, current_cart_id, source FROM wms_wave_pick_task WHERE id = :taskId AND warehouse_id = :warehouseId ${restrictCreatorId !== null ? 'AND pick_user_id = :restrictCreatorId' : ''} LIMIT 1 FOR UPDATE `, { replacements: { taskId, warehouseId, ...(restrictCreatorId !== null ? { restrictCreatorId } : {}), }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const taskRow = Array.isArray(taskRows) ? taskRows[0] : null; if (!taskRow) { if (restrictCreatorId !== null) { const taskRowsWithoutCreator = await this.ctx.model.query(` SELECT id FROM wms_wave_pick_task WHERE id = :taskId AND warehouse_id = :warehouseId LIMIT 1 `, { replacements: { taskId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); if (Array.isArray(taskRowsWithoutCreator) && taskRowsWithoutCreator.length > 0) { const error = new Error('仅允许取消本人创建的任务'); error.statusCode = 403; error.data = { task_id: taskId, warehouse_id: warehouseId, operator_id: restrictCreatorId, }; throw error; } } const error = new Error('任务不存在'); error.statusCode = 404; error.data = { task_id: taskId, warehouse_id: warehouseId, }; throw error; } const taskStatus = Number(taskRow.status || 0); // status 2(待复核)、3(已完成)不允许取消,此时库存已扣减且订单已标记拣货完成 if (![ 0, 1 ].includes(taskStatus)) { const statusMessages = { 2: '待复核', 3: '已完成', 9: '已取消' }; const statusText = statusMessages[taskStatus] || `状态${taskStatus}`; const error = new Error(`当前任务已${statusText},不允许取消`); error.statusCode = 400; error.data = { task_id: taskId, task_no: String(taskRow.task_no || '').trim(), warehouse_id: warehouseId, status: taskStatus, }; throw error; } const taskSource = Number(taskRow.source || 0); const taskNo = String(taskRow.task_no || '').trim(); const taskWaveRows = await this.ctx.model.query(` SELECT wave_id FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const waveIds = [ ...new Set((Array.isArray(taskWaveRows) ? taskWaveRows : []) .map(row => Number(row && row.wave_id || 0)) .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; const taskOrderRows = await this.ctx.model.query(` SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, warehouseId, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const taskOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) .map(row => Number(row && row.order_id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; // 收集订单操作日志(提交后统一写入) for (const orderId of taskOrderIds) { cancelOrderLogItems.push({ orderId, operationCode: 'ORDER_WAVE_CANCEL', message: `取消拣货任务 ${taskNo},从波次释放`, }); } // source=2(后台/扫描创建)不释放波次,仅清理任务-波次关联 const isScanCreated = taskSource === 2; let releasedWaveRows = []; if (waveIds.length > 0) { if (!isScanCreated) { // PDA 抓取:释放波次 releasedWaveRows = await this.ctx.model.query(` SELECT wave_id, wave_no FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) FOR UPDATE `, { replacements: { warehouseId, waveIds, }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); await orderModel.update({ wave_id: 0, wave_no: '', wave_scope: 0, wave_strategy_version: 0, wave_scan_result: 0, }, { where: { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds }, }, transaction, }); await this.ctx.model.query(` DELETE FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) `, { replacements: { warehouseId, waveIds, }, transaction, }); // 清理波次订单索引 await this.deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction, }); if (Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0) { hasReleasedWaves = true; } } // 清理任务-波次关联(所有来源都需要) await this.ctx.model.query(` DELETE FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, warehouseId, }, transaction, }); } // 清理任务-订单关联记录(所有来源都需要): // 任务取消后订单回池,wms_wave_pick_task_order 的关联记录属于脏数据,必须物理删除, // 否则会污染后续任务进度统计、复核状态批量更新及车标快照兜底查询 await this.ctx.model.query(` DELETE FROM wms_wave_pick_task_order WHERE task_id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, warehouseId, }, transaction, }); // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取) if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) { await this.ctx.model.query(` UPDATE wms_wave_pick_task_order SET pick_status = 0, picked_time = NULL, update_time = NOW() WHERE task_id = :taskId AND warehouse_id = :warehouseId AND pick_status = 1 `, { replacements: { taskId, warehouseId, }, transaction, }); const pickedOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) .map(row => Number(row && row.order_id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; if (pickedOrderIds.length > 0) { await orderModel.update({ pick_status: 'padding', }, { where: { warehouse_id: warehouseId, id: { [Op.in]: pickedOrderIds, }, pick_status: 'fin', }, transaction, validate: false, hooks: false, }); } } await this.ctx.model.query(` UPDATE wms_wave_pick_task SET status = 9, wave_count = 0, ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} update_time = NOW() WHERE id = :taskId AND warehouse_id = :warehouseId `, { replacements: { taskId, warehouseId, }, transaction, }); await this.ctx.model.query(` UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :operatorId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND warehouse_id = :warehouseId AND is_active = 1 `, { replacements: { taskId, warehouseId, operatorId, }, transaction, }); await this.bulkInsertRows('wms_wave_pick_action_log', [{ task_id: taskId, warehouse_id: warehouseId, wave_id: Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0 ? Number(releasedWaveRows[0].wave_id || 0) : 0, order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : null, sku_id: null, location_id: null, box_no: null, cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, qty_delta: 0, action_type: 'cancel', request_id: requestId, operator_id: Number.isInteger(operatorId) ? operatorId : 0, device_id: null, seq_no: 1, snapshot: JSON.stringify({ task_no: taskNo, source: taskSource, released_wave_ids: isScanCreated ? [] : waveIds, released_order_count: isScanCreated ? 0 : taskOrderIds.length, }), }], transaction); await this.bulkInsertRows('wms_order_pick_trace', [{ warehouse_id: warehouseId, order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : 0, task_id: taskId, cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, cart_code_snapshot: null, pick_user_id: null, pick_time: null, review_user_id: null, review_time: null, review_result: null, event_type: 'task_cancelled', event_desc: isScanCreated ? `任务取消(未释放波次): ${taskNo || taskId}` : `任务取消并释放波次: ${taskNo || taskId}`, operator_id: Number.isInteger(operatorId) ? operatorId : 0, operator_name: operatorName, snapshot: JSON.stringify({ task_no: taskNo, source: taskSource, released_wave_ids: isScanCreated ? [] : waveIds, released_order_count: isScanCreated ? 0 : taskOrderIds.length, released_wave_nos: isScanCreated ? [] : (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) .map(row => String(row && row.wave_no || '').trim()) .filter(Boolean), }), }], transaction); cancelledTaskNos.push(taskNo); } await transaction.commit(); if (cancelOrderLogItems.length > 0) { await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { warehouseId, scene: 'cancelWavePickTasksInternal', }); } if (hasReleasedWaves) { setImmediate(() => { this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { this.ctx.logger.warn('[wave.wavePickTaskCancel] 触发回池后重扫失败', { warehouseId, error: err && err.message ? err.message : String(err), }); }); }); } return { cancelled_count: normalizedTaskIds.length, task_ids: normalizedTaskIds, task_nos: cancelledTaskNos, }; } catch (error) { await transaction.rollback(); throw error; } } /** * 取消拣货任务并释放关联波次。 * * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定、 * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 * 当任务状态为 2(待复核)或 3(已完成)时,还会回退已拣货订单的拣货状态。 * * @param {Object} [data={}] 请求参数。 * @param {Array} data.task_ids 任务ID数组。 * @return {Promise} 取消结果。 */ async wavePickTaskCancel(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const sourceTaskIds = Array.isArray(normalizedData.task_ids) ? normalizedData.task_ids : []; if (sourceTaskIds.length === 0) { return this.fail('task_ids 必须为非空数组', {}, 400); } const normalizedTaskIds = []; for (const item of sourceTaskIds) { const taskId = Number(item); if (!Number.isInteger(taskId) || taskId <= 0) { return this.fail('task_ids 必须为正整数数组', { data: { task_ids: sourceTaskIds, }, }, 400); } normalizedTaskIds.push(taskId); } const taskIds = [ ...new Set(normalizedTaskIds) ]; if (taskIds.length === 0) { return this.fail('task_ids 必须为非空数组', {}, 400); } const resolvedWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { return this.fail('未获取到仓库上下文', {}, 400); } const operatorInfo = this.getOrderLogOperator(); const operatorId = Number(operatorInfo.id || 0); if (!Number.isInteger(operatorId) || operatorId <= 0) { return this.fail('未获取到操作人上下文', {}, 400); } const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; try { const result = await this.cancelWavePickTasksInternal({ taskIds, warehouseId: resolvedWarehouseId, operatorId, operatorName, restrictCreatorId: null, }); return this.success('ok', result); } catch (error) { if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { return this.fail(error.message, { data: this.isPlainObject(error.data) ? error.data : {}, }, error.statusCode); } return this.fail(`取消拣货任务失败: ${error.message}`, { data: { task_ids: taskIds, warehouse_id: resolvedWarehouseId, }, }, 500); } } /** * 取消本人创建的单个拣货任务并释放关联波次。 * * @param {Object} [data={}] 请求参数。 * @param {number|string} data.task_id 任务ID。 * @return {Promise} 取消结果。 */ async wavePickTaskCancelSelf(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; if (Object.prototype.hasOwnProperty.call(normalizedData, 'task_ids')) { return this.fail('当前接口仅支持单个 task_id,请勿传 task_ids', { data: { task_ids: normalizedData.task_ids, }, }, 400); } const taskId = Number(normalizedData.task_id); if (!Number.isInteger(taskId) || taskId <= 0) { return this.fail('task_id 必须为正整数', { data: { task_id: normalizedData.task_id, }, }, 400); } const resolvedWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { return this.fail('未获取到仓库上下文', {}, 400); } const operatorInfo = this.getOrderLogOperator(); const operatorId = Number(operatorInfo.id || 0); if (!Number.isInteger(operatorId) || operatorId <= 0) { return this.fail('未获取到操作人上下文', {}, 400); } const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; try { const result = await this.cancelWavePickTasksInternal({ taskIds: [ taskId ], warehouseId: resolvedWarehouseId, operatorId, operatorName, restrictCreatorId: operatorId, }); return this.success('ok', result); } catch (error) { if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { return this.fail(error.message, { data: this.isPlainObject(error.data) ? error.data : {}, }, error.statusCode); } return this.fail(`取消本人拣货任务失败: ${error.message}`, { data: { task_id: taskId, warehouse_id: resolvedWarehouseId, }, }, 500); } } /** * 后台按策略直接抓取并创建波次。 * * @param {Object} [data={}] 请求参数。 * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 * @return {Promise} 建波结果。 */ async waveStrategyFetchAdmin(data = {}) { const normalizedData = this.isPlainObject(data) ? data : {}; const strategyId = this.normalizeRequiredPositiveInteger( normalizedData.strategy_id ?? normalizedData.strategyId, 'strategy_id' ); let warehouseId; try { warehouseId = Number(this.getWarehouseId()); } catch (error) { throw new Error('未识别到当前仓库上下文'); } if (!Number.isInteger(warehouseId) || warehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const operatorInfo = this.getOrderLogOperator(); const plan = await this.prepareWaveStrategyFetchPlan({ strategyId, warehouseId, operator: { operator_id: operatorInfo.id, operator_name: operatorInfo.name, }, source: 'admin', data: normalizedData, }); if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { return this.fail('按策略抓取预处理校验失败', { data: { status: 'failed', fetch_state: 2, tip: '建波失败,请重试', warehouse_id: warehouseId, strategy_id: strategyId, source: 'admin', plan, }, }, 400); } try { const directFetchResult = await this.executeWaveStrategyDirectFetch({ plan, waveBatchSource: 0, }); this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { warehouseId, strategyId, strategyType: directFetchResult.strategy_type, createdWaveCount: directFetchResult.created_wave_count, createdOrderCount: directFetchResult.created_order_count, }); return this.success('ok', { status: 'success', fetch_state: 1, tip: '建波成功', warehouse_id: warehouseId, strategy_id: strategyId, source: 'admin', plan, wave_ids: directFetchResult.wave_ids, wave_nos: directFetchResult.wave_nos, order_ids: directFetchResult.order_ids, created_wave_count: directFetchResult.created_wave_count, created_order_count: directFetchResult.created_order_count, wave_prefix: directFetchResult.wave_prefix, wave_prefix_source: directFetchResult.wave_prefix_source, candidate_count: directFetchResult.candidate_count, grouped_count: directFetchResult.grouped_count, strategy_type: directFetchResult.strategy_type, accepted_at: new Date().toISOString(), }); } catch (error) { return this.fail(`按策略抓取建波失败: ${error.message}`, { data: { status: 'failed', fetch_state: 2, tip: '建波失败,请重试', warehouse_id: warehouseId, strategy_id: strategyId, source: 'admin', plan, }, }, 500); } } /** * 删除指定订单的波次索引记录。 * * @param {Object} [params={}] 参数对象。 * @param {number|string} [params.warehouseId] 仓库ID。 * @param {Array} [params.orderIds] 订单ID列表。 * @param {Object} [params.transaction] 事务对象。 * @return {Promise} */ async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedOrderIds = this.normalizeIdsInput(orderIds); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) { return; } const deleteSql = ` DELETE FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND order_id IN (:orderIds) `; await this.ctx.model.query(deleteSql, { replacements: { warehouseId: normalizedWarehouseId, orderIds: normalizedOrderIds, }, transaction, }); } /** * 删除指定波次的波次索引记录。 * * @param {Object} [params={}] 参数对象。 * @param {number|string} [params.warehouseId] 仓库ID。 * @param {Array} [params.waveIds] 波次ID列表。 * @param {Object} [params.transaction] 事务对象。 * @return {Promise} */ async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedWaveIds = this.normalizeIdsInput(waveIds); if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { return; } const deleteSql = ` DELETE FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND wave_id IN (:waveIds) `; await this.ctx.model.query(deleteSql, { replacements: { warehouseId: normalizedWarehouseId, waveIds: normalizedWaveIds, }, transaction, }); } /** * 重建指定波次的订单波次索引。 * * @param {Object} [params={}] 参数对象。 * @param {number|string} [params.warehouseId] 仓库ID。 * @param {number|string} [params.waveId] 波次ID。 * @param {Array} [params.orderIds] 订单ID列表。 * @param {Object} [params.orderModel] 订单模型实例。 * @param {Object} [params.transaction] 事务对象。 * @return {Promise} */ async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedWaveId = Number(waveId || 0); const normalizedOrderIds = this.normalizeIdsInput(orderIds); if ( !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || !Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0 || normalizedOrderIds.length === 0 ) { return; } await this.replaceOrderWaveIndexByWaveIds({ warehouseId: normalizedWarehouseId, waveIds: [ normalizedWaveId ], orderModel, transaction, }); } /** * 按波次ID批量替换订单波次索引记录。 * * @param {Object} [params={}] 参数对象。 * @param {number|string} [params.warehouseId] 仓库ID。 * @param {Array} [params.waveIds] 波次ID列表。 * @param {Object} [params.orderModel] 订单模型实例。 * @param {Object} [params.transaction] 事务对象。 * @return {Promise>} 各波次对应的订单总数映射。 */ async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); const normalizedWaveIds = this.normalizeIdsInput(waveIds); const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); if ( !Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0 || !currentOrderModel || typeof currentOrderModel.findAll !== 'function' ) { return new Map(); } const orderRows = await currentOrderModel.findAll({ attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code', 'sys_logistics_code' ], where: { wave_id: { [Op.in]: normalizedWaveIds, [Op.gt]: 0, }, }, order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, transaction, }); const orderRowsList = Array.isArray(orderRows) ? orderRows : []; const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []])); for (const row of orderRowsList) { const waveId = Number(row && row.wave_id || 0); const orderId = Number(row && row.id || 0); if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) { continue; } if (!Number.isInteger(orderId) || orderId <= 0) { continue; } waveOrderRowsMap.get(waveId).push({ id: orderId, sys_platform_code: String(row && row.sys_platform_code || ''), source_platform_code: String(row && row.source_platform_code || ''), sys_logistics_code: String(row && row.sys_logistics_code || ''), }); } await this.deleteOrderWaveIndexByWaveIds({ warehouseId: normalizedWarehouseId, waveIds: normalizedWaveIds, transaction, }); const allOrderIds = [ ...new Set(orderRowsList .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ]; if (allOrderIds.length > 0) { await this.deleteOrderWaveIndexByOrderIds({ warehouseId: normalizedWarehouseId, orderIds: allOrderIds, transaction, }); } const valueSqlList = []; const replacements = { warehouseId: normalizedWarehouseId, }; let rowIndex = 0; for (const waveId of normalizedWaveIds) { const rawOrderRows = waveOrderRowsMap.get(waveId) || []; // 按平台+快递排序:同平台、同快递订单聚合在一起,确保 wave_index 连续分配 const orderRowsByWave = [ ...rawOrderRows ].sort((a, b) => { const platformA = String( (a && a.sys_platform_code) || (a && a.source_platform_code) || '' ).trim().toLowerCase(); const platformB = String( (b && b.sys_platform_code) || (b && b.source_platform_code) || '' ).trim().toLowerCase(); if (platformA !== platformB) return platformA.localeCompare(platformB); const logisticsA = String((a && a.sys_logistics_code) || '').trim().toLowerCase(); const logisticsB = String((b && b.sys_logistics_code) || '').trim().toLowerCase(); if (logisticsA !== logisticsB) return logisticsA.localeCompare(logisticsB); return (Number(a && a.id) || 0) - (Number(b && b.id) || 0); }); const platformsIndexMap = new Map(); const platformSequenceMap = new Map(); for (const orderRow of orderRowsByWave) { const currentOrderId = Number(orderRow && orderRow.id || 0); if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) { continue; } const platformKey = String( (orderRow && orderRow.sys_platform_code) || (orderRow && orderRow.source_platform_code) || '' ).trim().toLowerCase(); const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1; platformSequenceMap.set(platformKey, nextPlatformSequence); platformsIndexMap.set(currentOrderId, nextPlatformSequence); } for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) { const orderId = Number(orderRow && orderRow.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { continue; } const waveSequence = orderIndex + 1; const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence); valueSqlList.push( `(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())` ); replacements[`orderId_${rowIndex}`] = orderId; replacements[`waveId_${rowIndex}`] = waveId; replacements[`waveIndex_${rowIndex}`] = waveSequence; replacements[`platformsIndex_${rowIndex}`] = platformsSequence; rowIndex += 1; } } if (valueSqlList.length > 0) { const insertSql = ` INSERT INTO wms_order_wave_index ( warehouse_id, order_id, wave_id, wave_index, platforms_index, create_at ) VALUES ${valueSqlList.join(',\n ')} `; await this.ctx.model.query(insertSql, { replacements, transaction, }); } const totalOrdersMap = new Map(); for (const waveId of normalizedWaveIds) { const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; totalOrdersMap.set(waveId, orderRowsByWave.length); } return totalOrdersMap; } /** * 兼容旧方法名 fetch,内部转调 groupFetch。 * * @param {Object} data 请求参数。 * @return {Promise} 任务提交结果。 */ async fetch(data = {}) { return this.groupFetch(data); } } module.exports = WaveService;