'use strict'; const { Op } = require('sequelize'); const OrderBaseService = require('./base'); 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 WAVE_MANUAL_FETCH_FLAG = 'wave_manual_fetch'; 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 * 60 * 24; 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 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', }); class WaveService extends OrderBaseService { /** * 初始化波次方法权限配置。 * * @param {Egg.Context} ctx 请求上下文。 */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; const _noNeedLog = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; const _noNeedAuth = 'wavePickTaskList,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; 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}`; } /** * 查询当天前缀下的下一个波次序号。 * * @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 sql = ` SELECT wave_no FROM wms_wave_batch WHERE wave_no LIKE :pattern ORDER BY wave_no DESC LIMIT 1 `; const rows = await this.ctx.model.query(sql, { replacements: { pattern }, type: this.ctx.model.QueryTypes.SELECT, transaction, }); const latestWaveNo = String(rows && rows[0] && rows[0].wave_no || '').trim(); if (!latestWaveNo) { return 1; } const match = latestWaveNo.match(/(\d{5})$/); const lastSequence = match ? Number(match[1]) : 0; if (!Number.isInteger(lastSequence) || lastSequence <= 0) { return 1; } return lastSequence + 1; } /** * 构建波次编号。 * * @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; } /** * 新增一条“已就绪”波次批次记录,并返回自增 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 {Object} params.transaction Sequelize 事务。 * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 */ async createWaveBatchReady({ warehouseId, totalOrders, itemDetailMachine, itemPartType, itemPart, distinguishExpress, logisticsName, itemSnapshotKey, wavePrefix, waveNo, waveType, 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; let normalizedWaveNo = normalizedWaveNoInput; if (!normalizedWaveNo) { const datePart = this.getCurrentDatePart(); const sequence = await this.getNextWaveNoSequence(normalizedWavePrefix, datePart, transaction); normalizedWaveNo = this.buildWaveNo(normalizedWavePrefix, datePart, sequence); } 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, create_time, update_time ) VALUES ( :waveNo, :waveType, 1, :totalOrders, 0, :itemDetailMachine, :itemPartType, :itemPart, :distinguishExpress, :logisticsName, :itemSnapshotKey, :warehouseId, :creator, NOW(), NOW() ) `; const 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, }, transaction, }); 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, }; } /** * 按订单ID清理波次索引记录。 * * @param {Object} params 清理参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Array|number|string} params.orderIds 订单ID集合。 * @param {Object} params.transaction Sequelize 事务。 * @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, }); } /** * 按波次ID清理波次索引记录(用于兜底)。 * * @param {Object} params 清理参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Array|number|string} params.waveIds 波次ID集合。 * @param {Object} params.transaction Sequelize 事务。 * @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|number|string} params.orderIds 订单ID集合。 * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 * @param {Object} params.transaction Sequelize 事务。 * @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, }); } /** * 按波次整批覆盖订单索引并返回各波次当前订单数。 * * 处理流程: * 1. 查询目标波次下当前订单(按 wave_id ASC, id ASC)。 * 2. 先按波次批量删除 wms_order_wave_index。 * 3. 按每个波次内订单顺序重建 wave_index;platforms_index 按平台内顺序重建(同平台按 id ASC,从 1 开始)。 * * @param {Object} params 覆盖参数。 * @param {number|string} params.warehouseId 仓库ID。 * @param {Array|number|string} params.waveIds 波次ID集合。 * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 * @param {Object} params.transaction Sequelize 事务。 * @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' ], 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 || ''), }); } await this.deleteOrderWaveIndexByWaveIds({ warehouseId: normalizedWarehouseId, waveIds: normalizedWaveIds, transaction, }); const valueSqlList = []; const replacements = { warehouseId: normalizedWarehouseId, }; let rowIndex = 0; for (const waveId of normalizedWaveIds) { const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; 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; } /** * 构建抓取候选订单筛选条件。 * * @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' }, 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) { where.logistics_name = String(structure.logistics_name || '').trim(); } 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 表示不限制。 * @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 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, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') END`); await model.update({ wave_id: waveId, wave_no: waveNo, order_flag: orderFlagExpression, }, { where: { id: { [Op.in]: candidateOrderIds }, wave_id: 0, }, 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, }); } await this.rebuildOrderWaveIndex({ warehouseId, waveId, orderIds: grabbedOrderIds, orderModel: model, 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; } } } await transaction.commit(); await this.batchCreateOrderOperationLogs(fetchedOrderLogItems, { warehouseId, scene: 'fetchSingleStructure', }); const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); 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, auto_fetch_disabled: true, auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, ...(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) { if (value === undefined || value === null || value === '') { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue) { return ''; } const allowedValues = [ '未分配', '部分分配', '已分配' ]; if (!allowedValues.includes(normalizedValue)) { throw new Error(`storage_assignment_status 参数不合法,仅支持: ${allowedValues.join('、')}`); } return normalizedValue; } /** * 规范化波次列表快递分配状态筛选值。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListExpressAssignmentStatusFilter(value) { if (value === undefined || value === null || value === '') { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue) { return ''; } const allowedValueMap = { unassigned: '未分配', partially_assigned: '部分分配', assigned: '已分配', }; if (allowedValueMap[normalizedValue]) { return allowedValueMap[normalizedValue]; } const allowedValues = [ '未分配', '部分分配', '已分配' ]; if (!allowedValues.includes(normalizedValue)) { throw new Error('express_assignment_status 参数不合法,仅支持: unassigned、partially_assigned、assigned'); } return normalizedValue; } /** * 规范化波次列表打印状态筛选值。 * * @param {string} value 入参筛选值。 * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListPrintAssignmentStatusFilter(value) { if (value === undefined || value === null || value === '') { return ''; } const normalizedValue = String(value).trim(); if (!normalizedValue) { return ''; } const allowedValueMap = { unprinted: '未打印', partially_printed: '部分打印', printed: '已打印', }; if (allowedValueMap[normalizedValue]) { return allowedValueMap[normalizedValue]; } const allowedValues = [ '未打印', '部分打印', '已打印' ]; if (!allowedValues.includes(normalizedValue)) { throw new Error('print_assignment_status 参数不合法,仅支持: unprinted、partially_printed、printed'); } return normalizedValue; } /** * 解析模型对应的 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 = '') { const normalizedStatusFilter = this.normalizeBatchListStorageAssignmentStatusFilter(statusFilter); if (!normalizedStatusFilter) { return { sql: '', replacements: {}, }; } const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; const storageNoneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; const storageFinExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; const storageErrorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; let whereClause = ''; if (normalizedStatusFilter === '已分配') { whereClause = ` ${storageFinExpr} = ${totalExpr} AND ${totalExpr} > 0 `; } else if (normalizedStatusFilter === '部分分配') { whereClause = ` ${storageErrorExpr} = 0 AND ${storageNoneExpr} <> ${totalExpr} AND ${storageFinExpr} <> ${totalExpr} `; } else if (normalizedStatusFilter === '未分配') { return { sql: ` AND ( ${totalExpr} = 0 OR ${storageErrorExpr} > 0 OR ${storageNoneExpr} = ${totalExpr} )`, replacements: {}, }; } return { sql: ` AND ${whereClause}`, replacements: {}, }; } /** * 构建波次列表快递分配状态筛选 SQL 条件。 * * @param {string} statusFilter 快递分配状态筛选值。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListExpressAssignmentFilterClause(statusFilter = '') { const normalizedStatusFilter = this.normalizeBatchListExpressAssignmentStatusFilter(statusFilter); if (!normalizedStatusFilter) { return { sql: '', replacements: {}, }; } const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; const expressNoneExpr = 'COALESCE(wave_order_stats.post_none_count, 0)'; const expressFinExpr = 'COALESCE(wave_order_stats.post_fin_count, 0)'; const expressErrorExpr = 'COALESCE(wave_order_stats.post_error_count, 0)'; let whereClause = ''; if (normalizedStatusFilter === '已分配') { whereClause = ` ${expressFinExpr} = ${totalExpr} AND ${totalExpr} > 0 `; } else if (normalizedStatusFilter === '部分分配') { whereClause = ` ${expressErrorExpr} = 0 AND ${expressNoneExpr} <> ${totalExpr} AND ${expressFinExpr} <> ${totalExpr} `; } else if (normalizedStatusFilter === '未分配') { return { sql: ` AND ( ${totalExpr} = 0 OR ${expressErrorExpr} > 0 OR ${expressNoneExpr} = ${totalExpr} )`, replacements: {}, }; } return { sql: ` AND ${whereClause}`, replacements: {}, }; } /** * 构建波次列表打印状态筛选 SQL 条件。 * * @param {string} statusFilter 打印状态筛选值。 * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListPrintAssignmentFilterClause(statusFilter = '') { const normalizedStatusFilter = this.normalizeBatchListPrintAssignmentStatusFilter(statusFilter); if (!normalizedStatusFilter) { return { sql: '', replacements: {}, }; } const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; const printNoneExpr = 'COALESCE(wave_order_stats.print_none_count, 0)'; const printFinExpr = 'COALESCE(wave_order_stats.print_fin_count, 0)'; let whereClause = ''; if (normalizedStatusFilter === '已打印') { whereClause = ` ${printFinExpr} = ${totalExpr} AND ${totalExpr} > 0 `; } else if (normalizedStatusFilter === '部分打印') { whereClause = ` ${printNoneExpr} <> ${totalExpr} AND ${printFinExpr} <> ${totalExpr} `; } else if (normalizedStatusFilter === '未打印') { return { sql: ` AND ( ${totalExpr} = 0 OR ${printNoneExpr} = ${totalExpr} )`, replacements: {}, }; } return { sql: ` AND ${whereClause}`, replacements: {}, }; } /** * 构建波次列表 where 条件(白名单字段)。 * * @param {Object} whereData 查询 where 入参。 * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} 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', 'source', 'creator', 'logistics_name', 'item_part_type', 'item_part', 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', 'total_orders_min', 'total_orders_max', 'processed_orders_min', 'processed_orders_max', 'storage_assignment_status', 'express_assignment_status', 'print_assignment_status', ]; 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 appendLikeCondition = (fieldKey, columnName, replacementKey) => { const value = normalizedWhere[fieldKey]; if (value === undefined || value === null || value === '') { return; } const normalizedValue = String(value).trim(); if (!normalizedValue) { return; } conditions.push(`${columnName} LIKE :${replacementKey}`); replacements[replacementKey] = `%${normalizedValue}%`; }; const appendMinCondition = (fieldKey, columnName, replacementKey) => { const value = normalizedWhere[fieldKey]; if (value === undefined || value === null || value === '') { return; } const numberValue = Number(value); if (!Number.isFinite(numberValue)) { throw new Error(`${fieldKey} 参数不合法`); } conditions.push(`${columnName} >= :${replacementKey}`); replacements[replacementKey] = numberValue; }; const appendMaxCondition = (fieldKey, columnName, replacementKey) => { const value = normalizedWhere[fieldKey]; if (value === undefined || value === null || value === '') { return; } const numberValue = Number(value); if (!Number.isFinite(numberValue)) { throw new Error(`${fieldKey} 参数不合法`); } conditions.push(`${columnName} <= :${replacementKey}`); replacements[replacementKey] = numberValue; }; appendIntegerEqualCondition('wave_id', 'wave_id', 'whereWaveId', false); appendLikeCondition('wave_no', 'wave_no', 'whereWaveNo'); appendIntegerEqualCondition('wave_type', 'wave_type', 'whereWaveType'); appendIntegerEqualCondition('wave_status', 'wave_status', 'whereWaveStatus'); const source = normalizedWhere.source; if (source !== undefined && source !== null && source !== '') { const normalizedSource = Number(source); if (!Number.isInteger(normalizedSource) || ![ 0, 1, 2 ].includes(normalizedSource)) { throw new Error('source 参数不合法'); } conditions.push('source = :whereSource'); replacements.whereSource = normalizedSource; } appendLikeCondition('creator', 'creator', 'whereCreator'); appendLikeCondition('logistics_name', 'logistics_name', 'whereLogisticsName'); appendLikeCondition('item_part', 'item_part', 'whereItemPart'); appendLikeCondition('item_snapshot_key', 'item_snapshot_key', 'whereItemSnapshotKey'); appendLikeCondition('item_detail_machine', 'item_detail_machine', 'whereItemDetailMachine'); const itemPartType = normalizedWhere.item_part_type; if (itemPartType !== undefined && itemPartType !== null && itemPartType !== '') { const normalizedItemPartType = String(itemPartType).trim(); if (!normalizedItemPartType) { throw new Error('item_part_type 参数不合法'); } conditions.push('item_part_type = :whereItemPartType'); replacements.whereItemPartType = normalizedItemPartType; } const distinguishExpress = normalizedWhere.distinguish_express; if (distinguishExpress !== undefined && distinguishExpress !== null && distinguishExpress !== '') { let normalizedDistinguishExpress; if (typeof distinguishExpress === 'boolean') { normalizedDistinguishExpress = distinguishExpress ? 1 : 0; } else if (typeof distinguishExpress === 'number') { if (distinguishExpress !== 0 && distinguishExpress !== 1) { throw new Error('distinguish_express 参数不合法'); } normalizedDistinguishExpress = distinguishExpress; } else { const boolText = String(distinguishExpress).trim().toLowerCase(); if ([ '1', 'true', 'yes', 'y', 'on' ].includes(boolText)) { normalizedDistinguishExpress = 1; } else if ([ '0', 'false', 'no', 'n', 'off' ].includes(boolText)) { normalizedDistinguishExpress = 0; } else { throw new Error('distinguish_express 参数不合法'); } } conditions.push('distinguish_express = :whereDistinguishExpress'); replacements.whereDistinguishExpress = normalizedDistinguishExpress; } appendMinCondition('total_orders_min', 'total_orders', 'whereTotalOrdersMin'); appendMaxCondition('total_orders_max', 'total_orders', 'whereTotalOrdersMax'); appendMinCondition('processed_orders_min', 'processed_orders', 'whereProcessedOrdersMin'); appendMaxCondition('processed_orders_max', 'processed_orders', 'whereProcessedOrdersMax'); const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter( normalizedWhere.storage_assignment_status ); const expressAssignmentStatus = this.normalizeBatchListExpressAssignmentStatusFilter( normalizedWhere.express_assignment_status ); const printAssignmentStatus = this.normalizeBatchListPrintAssignmentStatusFilter( normalizedWhere.print_assignment_status ); return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', replacements, storageAssignmentStatus, expressAssignmentStatus, printAssignmentStatus, }; } /** * 解析分配状态。 * * @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, }; } /** * 拣货任务列表查询。 * * 基于 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} 列表与分页结果。 */ 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.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, t.batch_no, 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 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); 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(), batch_no: String(item && item.batch_no || '').trim(), 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, })); 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); } } /** * 解析拣货任务列表分页参数。 * * 兼容 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, }); } mergeOrderItemDetails(itemRows = []) { const merged = new Map(); for (const row of itemRows) { const normalized = this.normalizeOrderItemRow(row); if (!normalized.item_code || 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('|'); } /** * 归一化拣货任务列表请求参数。 * * 兼容顶层筛选参数与 where 结构并保持旧调用可用: * - 顶层支持 warehouse_id/status/source/keyword/task_no * - 同名字段优先使用顶层值覆盖 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', 'pick_mode', 'review_status', 'pick_user_id', 'review_user_id', 'cart_id', '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', 'task_no', 'cart_id', '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 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 )`); 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, }; } 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.logistics_name || '').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.logistics_name || '').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 { page, pageSize } = this.normalizePagination(requestData); const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, wave_id: 0, }; if (storeId > 0) { where.store_id = storeId; } if (shopName) { where.shop_nick = { [Op.like]: `%${shopName}%` }; } // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, attributes: [ 'id', 'store_id', 'logistics_name', 'items_hash', 'items', 'items_total', '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 itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); const logisticsName = String(g.orders[0].logistics_name || '').trim(); const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, logistics_name: logisticsName, 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, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, 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 { page, pageSize } = this.normalizePagination(requestData); const where = { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, wave_id: 0, }; if (storeId > 0) { where.store_id = storeId; } if (shopName) { where.shop_nick = { [Op.like]: `%${shopName}%` }; } // Phase 1: 主表全量查询,用 items_hash 做分组基准 const rawOrders = await model.findAll({ where, attributes: [ 'id', 'store_id', 'logistics_name', 'items_hash', 'items', 'items_total', '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 itemPartInfo = this.getOrderItemPart(g.orders[0] || {}); const logisticsName = String(g.orders[0].logistics_name || '').trim(); const itemDetailMachine = this.buildMachineStructureToken({ item_part_type: itemPartInfo.item_part_type, item_part: itemPartInfo.item_part, distinguish_express: distinguishExpress, logistics_name: logisticsName, 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, store_id: store_ids.length === 1 ? store_ids[0] : 0, store_ids, logistics_name: logisticsName, 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, }, }); } /** * 查询当前仓库波次策略列表。 * * 仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 * * @param {Object} [data={}] 请求参数。 * @param {Object} [data.pagination] 分页参数。 * @return {Promise} 波次策略列表及分页信息。 */ async waveStrategyList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; 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 queryResult = await strategyModel.findAndCountAll({ where: { warehouse_id: contextWarehouseId, }, order: [ [ 'status', 'DESC' ], [ 'id', 'DESC' ], ], offset, limit: pageSize, raw: true, }); const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; const total = Number(queryResult && queryResult.count || 0); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 新增波次策略。 * * 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); } } }; 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; payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, '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, 'strategy_type')) { payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); } if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); } } 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'); this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_orders'); this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_skus'); this.patchWaveStrategyIntegerField(payload, requestData, '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')) { payload.allowed_provinces = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_platforms')) { payload.allowed_platforms = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms); } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_owners')) { const allowedOwners = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); await this.validateWaveStrategyAllowedOwners(allowedOwners, warehouseId); payload.allowed_owners = allowedOwners; } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_expresses')) { const allowedExpresses = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses); await this.validateWaveStrategyAllowedExpresses(allowedExpresses); payload.allowed_expresses = allowedExpresses; } await this.applyWaveStrategyMaxSameStructureConstraint(payload, warehouseId); delete payload.warehouse_id; delete payload.creator; delete payload.creator_name; return payload; } /** * 按字段补丁方式归一化波次策略正整数参数。 * * @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().toLowerCase()).filter(Boolean) : []; if (normalizedExpresses.length === 0) { return; } const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); const illegalExpresses = normalizedExpresses.filter(item => !availableExpressSet.has(item)); 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, 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 : {}; 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, 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 || ''), }; } /** * 查询兜底不符合波次策略的订单列表。 * * 直接复用订单通用列表能力,返回标准 list/pagination 结构。 * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 * * @param {Object} data 请求参数。 * @param {Object} data.pagination 分页参数。 * @param {Object} data.where 查询条件。 * @param {Object} data.sort 排序参数。 * @return {Promise} 列表查询结果。 */ async waveStrategyFallbackOrderList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { pagination, where, sort } = requestData; const normalizedPagination = this.normalizePagination(pagination || {}); const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); const listResult = await this.listByModule('waveStrategyFallbackOrder', { ...requestData, pagination: normalizedPagination, where: normalizedWhere, sort, }); const normalizedResult = this.isPlainObject(listResult) ? listResult : {}; const sourceList = Array.isArray(normalizedResult.list) ? normalizedResult.list : []; const orderIds = sourceList .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 list = sourceList.map(item => { const orderId = Number(item && item.id || 0); return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); }); return this.success('ok', { ...normalizedResult, list, }); } /** * 波次列表查询。 * * 默认查询状态为 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 baseBatchWhereSql = ` warehouse_id = :warehouseId AND wave_status IN (:waveStatusList) ${whereClause.sql} `; const batchListFromSql = ` FROM ( SELECT wave_id, wave_no, wave_type, wave_status, total_orders, processed_orders, distinguish_express, logistics_name, item_snapshot_key, warehouse_id, creator, 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 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 WHERE 1 = 1 AND COALESCE(wave_order_stats.order_total, 0) > 0 ${storageAssignmentFilterClause.sql} ${expressAssignmentFilterClause.sql} ${printAssignmentFilterClause.sql} `; 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.logistics_name, wb.item_snapshot_key, wb.warehouse_id, wb.creator, wb.create_time, wb.update_time ${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, limit: pageSize, offset, }, }), this.ctx.model.query(countSql, { replacements: { warehouseId, waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.replacements, ...expressAssignmentFilterClause.replacements, ...printAssignmentFilterClause.replacements, }, }), ]); 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 waveIds = rawList .map(item => Number(item && item.wave_id || 0)) .filter(id => Number.isInteger(id) && id > 0); const orderRows = waveIds.length > 0 ? await orderModel.findAll({ where: { wave_id: { [Op.in]: waveIds }, }, attributes: [ 'wave_id', 'storage_status', 'post_status', 'print_status' ], raw: true, }) : []; const waveOrderStatsMap = new Map(); for (const row of orderRows) { const waveId = Number(row && row.wave_id || 0); if (!Number.isInteger(waveId) || waveId <= 0) { continue; } if (!waveOrderStatsMap.has(waveId)) { waveOrderStatsMap.set(waveId, { orderCount: 0, storageNoneCount: 0, storageFinCount: 0, storageErrorCount: 0, expressNoneCount: 0, expressFinCount: 0, expressErrorCount: 0, printNoneCount: 0, printFinCount: 0, }); } const stats = waveOrderStatsMap.get(waveId); const storageStatus = String(row && row.storage_status || '').trim(); const expressStatus = String(row && row.post_status || '').trim(); const printStatus = String(row && row.print_status || '').trim(); stats.orderCount += 1; if (storageStatus === 'none') { stats.storageNoneCount += 1; } else if (storageStatus === 'fin') { stats.storageFinCount += 1; } else if (storageStatus === 'error') { stats.storageErrorCount += 1; } if (expressStatus === 'none') { stats.expressNoneCount += 1; } else if (expressStatus === 'fin') { stats.expressFinCount += 1; } else if (expressStatus === 'error') { stats.expressErrorCount += 1; } if (printStatus === 'none') { stats.printNoneCount += 1; } else if (printStatus === 'fin') { stats.printFinCount += 1; } } const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); const stats = waveOrderStatsMap.get(waveId) || {}; const orderCount = Number(stats.orderCount || 0); const storageNoneCount = Number(stats.storageNoneCount || 0); const storageFinCount = Number(stats.storageFinCount || 0); const storageErrorCount = Number(stats.storageErrorCount || 0); const expressNoneCount = Number(stats.expressNoneCount || 0); const expressFinCount = Number(stats.expressFinCount || 0); const expressErrorCount = Number(stats.expressErrorCount || 0); const printNoneCount = Number(stats.printNoneCount || 0); const printFinCount = Number(stats.printFinCount || 0); 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), 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: '已打印', }), }; }); return this.success('ok', { list, pagination: { page, pageSize, total, totalPages, hasPrevious: page > 1, hasNext: page < totalPages, }, }); } /** * 批量解除波次任务提交接口。 * * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 * * @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 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: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', 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: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', 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: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', 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: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', 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: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', 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: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', 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); } /** * 提交波次策略快速扫描异步任务。 * * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接返回已有 task_id。 * * @return {Promise} 任务受理结果。 */ async waveStrategyQuickScan() { const contextWarehouseId = Number(this.getWarehouseId() || 0); if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { throw new Error('未识别到当前仓库上下文'); } const warehouseId = contextWarehouseId; const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(warehouseId); 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 this.success('ok', { status: 'success', task_id: existingTaskId, warehouse_id: warehouseId, state: existingState, message: 'Quick scan task is already running. Check progress with order.wave.waveStrategyQuickScanTaskProgress', accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), }); } await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, existingTaskId); } const taskId = this.generateWaveStrategyQuickScanTaskId(warehouseId); const acceptedAt = new Date().toISOString(); await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { warehouse_id: warehouseId, 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, error: '', error_code: '', result: null, }); await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, { state: 'submitted', accepted_at: acceptedAt, }); setImmediate(() => { this.runWaveStrategyQuickScanTask({ taskId, warehouseId, }).catch(error => { this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { taskId, warehouseId, 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, state: 'submitted', message: 'Quick scan task submitted. Check progress with order.wave.waveStrategyQuickScanTaskProgress', accepted_at: acceptedAt, }); } /** * 查询波次策略快速扫描任务进度。 * * @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), }); } /** * 执行波次策略快速扫描后台任务。 * * 扫描范围:当前仓库 + step != 0 + wave_id = 0 + wave_strategy_version != 当前策略版本。 * * @param {Object} [params={}] 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库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 subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') ); 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 strategyRows = await strategyModel.findAll({ where: { warehouse_id: warehouseId, status: 1, }, order: [[ 'id', 'ASC' ]], raw: true, }); 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: { warehouse_id: warehouseId, step: { [Op.ne]: 0 }, wave_id: 0, [Op.or]: [ { wave_strategy_version: { [Op.ne]: strategyVersion } }, { wave_strategy_version: { [Op.is]: null } }, ], }, raw: true, }); const normalizedOrders = Array.isArray(orderRows) ? orderRows : []; const totalOrderCount = normalizedOrders.length; if (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 structureStoreSetMap = new Map(); for (const order of normalizedOrders) { const structureKey = this.getWaveStrategyQuickScanStructureKey(order); if (!structureKey) { continue; } const storeId = String(order && order.store_id || '').trim(); if (!structureStoreSetMap.has(structureKey)) { structureStoreSetMap.set(structureKey, new Set()); } if (storeId) { structureStoreSetMap.get(structureKey).add(storeId); } } const matchedOrderIds = []; const unmatchedOrderIds = []; let processedOrderCount = 0; for (const order of normalizedOrders) { const matched = this.isWaveStrategyQuickScanOrderMatched(order, strategyList, { structureStoreSetMap, }); const orderId = Number(order && order.id || 0); if (Number.isInteger(orderId) && orderId > 0) { if (matched) { matchedOrderIds.push(orderId); } else { unmatchedOrderIds.push(orderId); } } processedOrderCount += 1; if (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount) { await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, total_order_count: totalOrderCount, processed_order_count: processedOrderCount, matched_order_count: matchedOrderIds.length, unmatched_order_count: unmatchedOrderIds.length, progress_percent: Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)), }); } } 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, }); const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, total_order_count: totalOrderCount, processed_order_count: totalOrderCount, matched_order_count: matchedOrderIds.length, unmatched_order_count: unmatchedOrderIds.length, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { strategy_version: strategyVersion, matched_order_count: matchedOrderIds.length, unmatched_order_count: unmatchedOrderIds.length, 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); } } /** * 批量更新快速扫描结果。 * * @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 : {}; return { 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), allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms), 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 原始值。 * @return {Array} 归一化字符串数组(小写去重)。 */ normalizeWaveStrategyQuickScanStringList(value) { 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 => String(item || '').trim().toLowerCase()) .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。 * * @param {Object} order 订单记录。 * @return {string} 快递 key。 */ getWaveStrategyQuickScanExpressKey(order = {}) { const sysLogisticsCode = String(order && order.sys_logistics_code || '').trim(); if (sysLogisticsCode) { return sysLogisticsCode; } const logisticsCode = String(order && order.logistics_code || '').trim(); if (logisticsCode) { return logisticsCode; } return String(order && order.logistics_name || '').trim(); } /** * 判断订单是否命中任一快速扫描策略。 * * @param {Object} order 订单记录。 * @param {Array} strategyList 策略列表。 * @param {Object} context 统计上下文。 * @return {boolean} 是否命中。 */ isWaveStrategyQuickScanOrderMatched(order = {}, strategyList = [], context = {}) { const list = Array.isArray(strategyList) ? strategyList : []; if (list.length === 0) { return false; } for (const strategy of list) { if (this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { return true; } } return false; } /** * 判断订单是否命中单条快速扫描策略。 * * @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 structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); if (!structureKey) { return false; } if (normalizedStrategy.allow_cross_owner === false) { 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; } const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); 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 hitExpress = expressCandidates.some(code => normalizedStrategy.allowed_expresses.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 hitPlatform = platformCandidates.some(code => normalizedStrategy.allowed_platforms.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 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' ], 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 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; } 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, 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: '混合订单', wavePrefix: singleFetchByIdsWavePrefix, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') END`); await orderModel.update({ wave_id: waveId, wave_no: waveNo, order_flag: orderFlagExpression, }, { 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', }); 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, 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 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: '', }, { where: { id: { [Op.in]: removablePendingIds }, }, transaction, }); const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); 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', }); 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; } } /** * 批量移除异常订单任务提交接口。 * * 仅处理当前登录仓库下命中波次中的异常订单,提交后异步执行。 * 异常判定与订单模块待处理异常定义保持一致:仅 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: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', 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: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', 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; } } /** * 执行批量解除波次后台任务。 * * @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 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(), })) .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, duration_ms: Date.now() - startTime, }, }); return; } let processedWaveCount = 0; let affectedOrderCount = 0; let canceledWaveCount = 0; const affectedWaveIds = []; for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); const waveNo = String(wave.wave_no || '').trim() || '未知波次'; const transaction = await this.ctx.model.transaction(); try { 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 affectedOrderIds = [ ...new Set((Array.isArray(affectedOrderRows) ? affectedOrderRows : []) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; const orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', }, { where: { wave_id: waveId, }, transaction, }); if (affectedOrderIds.length > 0) { await this.deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds: affectedOrderIds, transaction, }); } else { await this.deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds: [ waveId ], transaction, }); } const currentAffectedOrderCount = Number( Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 ); const cancelSql = ` UPDATE wms_wave_batch SET wave_status = -1, update_time = NOW() WHERE warehouse_id = :warehouseId AND wave_id = :waveId `; 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 transaction.commit(); await this.batchCreateOrderOperationLogs(cancelOrderLogItems, { warehouseId, scene: 'batchCancel', }); 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, duration_ms: Date.now() - startTime, }, }); return; } } 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, 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; }); } /** * 执行批次分配快递号后台任务。 * * 任务仅负责提交分配请求到快递分配流水线,实际分配过程由快递服务异步处理。 * * @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(); let matchedOrderIds = []; let matchedOrderCount = 0; let orderModel = null; let useBusinessKeyColumn = true; let normalizedOrders = []; 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 { orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }; let orderRows = []; try { orderRows = await orderModel.findAll({ attributes: [ 'id', 'business_key' ], 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' ], where: baseOrderWhere, raw: true, }); } this.ctx.logger.info('[wave.batchAllocateExpress] 订单筛选完成', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, useBusinessKeyColumn, matchedOrderCount: Array.isArray(orderRows) ? orderRows.length : 0, }); normalizedOrders = (Array.isArray(orderRows) ? orderRows : []) .map(row => { const orderId = Number(row && row.id || 0); if (!Number.isInteger(orderId) || orderId <= 0) { return null; } const businessKey = Number(useBusinessKeyColumn ? row && row.business_key : 0); return { order_id: orderId, business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 0, }; }) .filter(Boolean); matchedOrderIds = normalizedOrders.map(item => Number(item && item.order_id || 0)).filter(orderId => Number.isInteger(orderId) && orderId > 0); matchedOrderCount = matchedOrderIds.length; if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, }); 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, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: 0, duration_ms: durationMs, message: '未找到可分配快递号的订单', }, 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), }); const pipelineResult = await this.service.systems.express.createWaybillCodePipeline(normalizedOrders); 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, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { wave_ids: waveIds, allocated_order_count: normalizedOrders.length, duration_ms: durationMs, message: String(pipelineResult && pipelineResult.message || '分配快递任务已提交').trim(), }, trace_id: traceId, }); } catch (error) { const durationMs = Date.now() - startTime; const canIdentifyBusinessKey = useBusinessKeyColumn; const rollbackOrderIds = canIdentifyBusinessKey ? normalizedOrders .filter(item => Number(item && item.business_key) === 1) .map(item => Number(item && item.order_id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0) : []; if (!canIdentifyBusinessKey) { this.ctx.logger.warn('[wave.batchAllocateExpress] business_key 列不可用,按强约束跳过 post_status 失败回写', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, matchedOrderCount, }); } else if (rollbackOrderIds.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未命中 business_id=1 订单,跳过 post_status 失败回写', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, matchedOrderCount, }); } if (rollbackOrderIds.length > 0 && orderModel && typeof orderModel.update === 'function') { try { await this.service.systems.express.markWaybillAsyncOrdersAsError( orderModel, rollbackOrderIds, error && error.message ? `${error.message}` : `${error}`, { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, } ); } catch (updateError) { this.ctx.logger.warn('[wave.batchAllocateExpress] 通过统一 helper 回写订单失败状态失败', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, matchedOrderCount: rollbackOrderIds.length, error: updateError && updateError.message ? updateError.message : `${updateError}`, }); } } 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, total_wave_count: waveIds.length, total_order_count: matchedOrderCount, processed_order_count: matchedOrderCount, success_order_count: 0, failed_order_count: matchedOrderCount, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, 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' ], where: { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }, raw: true, }); const normalizedOrders = [ ...new Set((Array.isArray(orderRows) ? orderRows : []) .map(row => Number(row && row.id || 0)) .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ] .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 orderModel = await this.getOrderModel('pendingOrder', warehouseId); await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: updatableWaveIds, orderModel, 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, }); } 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 orderModel = await this.getOrderModel('pendingOrder', warehouseId); await this.replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds: updatedWaveIds, orderModel, 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, autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, }); 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 } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, 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 } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, 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: '达到最大抓取上限' } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, 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, autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, 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 } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, 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 } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, submitted_at: Date.now(), }); this.ctx.logger.info('[wave.fetch] 任务提交成功', { taskId, warehouseId: Number(warehouseId || 0), structureCount: structures.length, defaultQuantity, fetchMode: normalizedFetchMode, maxFetchQuantity: normalizedMaxFetchQuantity, autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, }); 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, autoFetchDisabledMarker: WAVE_MANUAL_FETCH_FLAG, 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 } : {}), auto_fetch_disabled_marker: WAVE_MANUAL_FETCH_FLAG, 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); } /** * 兼容旧方法名 fetch,内部转调 groupFetch。 * * @param {Object} data 请求参数。 * @return {Promise} 任务提交结果。 */ async fetch(data = {}) { return this.groupFetch(data); } } module.exports = WaveService;