'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 SINGLE_FETCH_BY_IDS_WAVE_PREFIX = 'S'; 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 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(); class WaveService extends OrderBaseService { /** * 初始化波次方法权限配置。 * * @param {Egg.Context} ctx 请求上下文。 */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; 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 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 {Object} params.transaction Sequelize 事务。 * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 */ async createWaveBatchReady({ warehouseId, totalOrders, itemDetailMachine, itemPartType, itemPart, distinguishExpress, logisticsName, itemSnapshotKey, wavePrefix, waveNo, 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(); 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, 1, 1, :totalOrders, 0, :itemDetailMachine, :itemPartType, :itemPart, :distinguishExpress, :logisticsName, :itemSnapshotKey, :warehouseId, :creator, NOW(), NOW() ) `; const createResult = await this.ctx.model.query(sql, { replacements: { waveNo: normalizedWaveNo, 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, }; } /** * 构建抓取候选订单筛选条件。 * * @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, }); } 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 请求参数。 * @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 {Object} options 规范化选项。 * @param {number|string} options.maxPageSize 每页数量上限。 * @return {{ page: number, pageSize: number }} 规范化后的分页信息。 */ normalizePagination(data = {}, options = {}) { const pagination = this.isPlainObject(data && data.pagination) ? data.pagination : {}; 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; } /** * 解析模型对应的 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: {}, }; } /** * 构建波次列表 where 条件(白名单字段)。 * * @param {Object} whereData 查询 where 入参。 * @return {{ sql: string, replacements: Object, storageAssignmentStatus: 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', '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', ]; 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'); 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 ); return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', replacements, storageAssignmentStatus, }; } /** * 解析分配状态。 * * @param {number} total 总数量。 * @param {number} noneCount 未分配数量。 * @param {number} finCount 已分配数量。 * @param {number} errorCount 分配异常数量。 * @param {{ none?: string, partial?: string, finished?: string, error?: string }} [labels] 状态文案映射。 * @return {string} 分配状态。 */ resolveAssignmentStatus(total, noneCount, finCount, errorCount = 0, labels = {}) { const normalizedTotal = Number(total || 0); const normalizedNoneCount = Number(noneCount || 0); const normalizedFinCount = Number(finCount || 0); const normalizedErrorCount = Number(errorCount || 0); const normalizedLabels = labels && typeof labels === 'object' ? labels : {}; const noneLabel = String(normalizedLabels.none || '未分配'); const partialLabel = String(normalizedLabels.partial || '部分分配'); const finishedLabel = String(normalizedLabels.finished || '已分配'); const errorLabel = String(normalizedLabels.error || '分配异常'); if (normalizedErrorCount > 0) { return errorLabel; } if (normalizedTotal <= 0 || normalizedNoneCount === normalizedTotal) { return noneLabel; } if (normalizedFinCount === normalizedTotal) { return finishedLabel; } return partialLabel; } normalizeSkuText(value) { if (value === undefined || value === null) { return ''; } return String(value).trim(); } normalizeShopName(value) { if (value === undefined || value === null) { return ''; } return String(value).trim(); } parseItemSnapshot(rawSnapshot) { if (!rawSnapshot) { return {}; } if (typeof rawSnapshot === 'string') { try { const parsed = JSON.parse(rawSnapshot); return parsed && typeof parsed === 'object' ? parsed : {}; } catch { return {}; } } return typeof rawSnapshot === 'object' ? rawSnapshot : {}; } normalizeOrderItemRow(row = {}) { const snapshot = this.parseItemSnapshot(row.item_snapshot); const stockIdRaw = snapshot.stock_id ?? row.stock_id; const quantityRaw = row.plan_qty; const stockId = Number(stockIdRaw || 0); const quantity = Number(quantityRaw || 0); return { stock_id: Number.isInteger(stockId) && stockId > 0 ? stockId : 0, item_code: String(snapshot.item_code ?? row.item_code ?? '').trim(), item_name: String(snapshot.item_name ?? row.item_name ?? '').trim(), barcode: String(snapshot.barcode ?? '').trim(), quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 0, }; } mergeOrderItemDetails(itemRows = []) { const merged = new Map(); for (const row of itemRows) { const normalized = this.normalizeOrderItemRow(row); 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(' | '); } 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, }, }); } /** * 波次列表查询。 * * 默认查询状态为 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 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 ${storageAssignmentFilterClause.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, limit: pageSize, offset, }, }), this.ctx.model.query(countSql, { replacements: { warehouseId, waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.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); } /** * 过滤 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. 仅抓取待处理订单(step in [1,2,3])且未取消、未进入出库中的订单; * 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); const step = Number(row && row.step || 0); const status = String(row && row.status || '').trim(); const outboundStatus = String(row && row.outbound_status || '').trim(); if (!Number.isInteger(orderId) || orderId <= 0) { return false; } if (waveId > 0) { return false; } if (![ 1, 2, 3 ].includes(step)) { return false; } if (status === 'cancel') { return false; } if (outboundStatus === 'padding') { return false; } return true; }); const groupCandidateOrderIds = await this.resolveGroupCandidateOrderIdsForSingleFetch( orderModel, warehouseId, fetchableRows ); const fetchableRowsAfterGroupFilter = fetchableRows.filter(row => { const orderId = Number(row && row.id || 0); return !groupCandidateOrderIds.includes(orderId); }); const fetchableOrderIds = [ ...new Set(fetchableRowsAfterGroupFilter .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); const notFoundOrderIds = normalizedIds.filter(id => !foundOrderIds.includes(id)); const skippedOrderIds = normalizedIds.filter(id => !fetchableOrderIds.includes(id)); if (fetchableOrderIds.length === 0) { await transaction.commit(); return this.success('ok', { ids: normalizedIds, wave_id: 0, wave_no: '', fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, excluded_group_order_ids: groupCandidateOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); } const { waveId, waveNo } = await this.createWaveBatchReady({ warehouseId, totalOrders: fetchableOrderIds.length, itemDetailMachine: `manual_single_ids_${Date.now()}`, itemPartType: 'manual_ids', itemPart: `ids_${fetchableOrderIds.length}`, distinguishExpress: false, logisticsName: '', itemSnapshotKey: 'manual_single_ids', wavePrefix: SINGLE_FETCH_BY_IDS_WAVE_PREFIX, 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, excluded_group_order_ids: groupCandidateOrderIds, 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 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, excluded_group_order_ids: groupCandidateOrderIds, 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 remainingRows = await orderModel.findAll({ attributes: [ 'wave_id', [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], ], where: { wave_id: { [Op.in]: affectedWaveIds, [Op.gt]: 0, }, }, group: [ 'wave_id' ], raw: true, transaction, }); const remainingCountMap = new Map(); for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { const waveId = Number(row && row.wave_id || 0); const remainingCount = Number(row && row.remaining_count || 0); if (!Number.isInteger(waveId) || waveId <= 0) { continue; } remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); } 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 orderUpdateResult = await orderModel.update({ wave_id: 0, wave_no: '', }, { where: { wave_id: 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(); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, total_wave_count: waveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', trace_id: traceId, }); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const baseOrderWhere = { warehouse_id: warehouseId, wave_id: { [Op.in]: waveIds, }, step: { [Op.in]: [ 1, 2, 3 ], }, }; let orderRows = []; let useBusinessKeyColumn = true; try { orderRows = await orderModel.findAll({ attributes: [ 'id', 'business_key' ], 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, }); const 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 : 1); return { order_id: orderId, business_key: Number.isInteger(businessKey) && businessKey > 0 ? businessKey : 1, }; }) .filter(Boolean); if (normalizedOrders.length === 0) { this.ctx.logger.info('[wave.batchAllocateExpress] 未筛选到可分配快递号订单', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, }); 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) { this.ctx.logger.error('[wave.batchAllocateExpress] 后台任务执行失败', { traceId, taskId: normalizedTaskId, warehouseId, waveIds, error: error && error.message ? error.message : `${error}`, stack: error && error.stack ? error.stack : '', }); await this.setBatchAllocateExpressTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: error && error.message ? error.message : `${error}`, error_code: 'WAVE_BATCH_ALLOCATE_EXPRESS_FAILED', trace_id: traceId, }); } } /** * 执行批次分配储位后台任务。 * * 任务仅负责按波次拉取订单并提交储位分配流水线,实际分配过程复用储位分配服务。 * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 * @param {Array|number|string} [params.waveIds] 波次ID集合(兜底)。 * @return {Promise} 无返回值。 */ async runBatchAllocateStorageTask(params = {}) { const normalizedTaskId = String(params && params.taskId || '').trim(); if (!normalizedTaskId) { throw new Error('taskId 不能为空'); } const cachedTask = await this.getBatchAllocateStorageTaskProgress(normalizedTaskId); const warehouseId = Number( cachedTask && cachedTask.warehouse_id !== undefined ? cachedTask.warehouse_id : params && params.warehouseId ); const waveIds = this.normalizeIdsInput( cachedTask && cachedTask.wave_ids !== undefined ? cachedTask.wave_ids : params && params.waveIds ); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { end_time: Date.now(), error: 'warehouse_id 参数不合法', error_code: 'INVALID_WAREHOUSE_ID', }); return; } if (waveIds.length === 0) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, end_time: Date.now(), error: 'wave_ids 参数不能为空或格式错误', error_code: 'INVALID_WAVE_IDS', }); return; } const startTime = Date.now(); const lockResult = this.tryAcquireBatchAllocateStorageWarehouseLock(warehouseId, normalizedTaskId); if (!lockResult.acquired) { await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'failed', { warehouse_id: warehouseId, progress_percent: 0, end_time: Date.now(), duration_ms: Date.now() - startTime, error: lockResult.ownerTaskId ? `同仓库存在执行中的批量储位分配任务,请稍后重试(running_task_id=${lockResult.ownerTaskId})` : '同仓库存在执行中的批量储位分配任务,请稍后重试', error_code: 'WAVE_BATCH_ALLOCATE_STORAGE_WAREHOUSE_CONFLICT', }); return; } await this.setBatchAllocateStorageTaskProgress(normalizedTaskId, 'running', { warehouse_id: warehouseId, wave_ids: waveIds.join(','), wave_id_list: waveIds, business_id: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID, business_ids: BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS, total_wave_count: waveIds.length, total_order_count: 0, processed_order_count: 0, success_order_count: 0, failed_order_count: 0, progress_percent: 0, start_time: startTime, end_time: null, result: null, error: '', error_code: '', }); try { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const orderRows = await orderModel.findAll({ attributes: [ 'id' ], 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 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 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;