diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 43fa09c..4925f6d 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -66,6 +66,10 @@ module.exports = { ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败', ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交', ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败', + ORDER_INTERCEPT_REQUEST: '请求订单拦截', + ORDER_INTERCEPT_CANCEL: '解除订单拦截', + ORDER_LOCK: '订单锁定', + ORDER_UNLOCK: '订单解锁', // 库存管理 STOCK_IN: '商品入库', diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index 3fb0320..c64c861 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -6,7 +6,7 @@ module.exports = app => { // 状态机枚举定义 const StatusEnum = { - STATUS: [ 'pedding', 'created', 'cancel', 'error' ], + STATUS: [ 'pedding', 'created', 'cancel', 'error', 'finished' ], SYNC_STATUS: [ 'padding', 'fin', 'error' ], POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ], STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ], diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index b05162f..7b6ef22 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -107,10 +107,6 @@ const MODULE_CONFIGS = Object.freeze({ operator: 'eq', value: 0, }, - wave_scan_result: { - operator: 'eq', - value: 2, - }, }, }, outboundOrder: { diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index ea89c51..9fd63ae 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -19,6 +19,18 @@ const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({ unknown: 0, }); +const BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-intercept:'; +const BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_LOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-lock:'; +const BATCH_LOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX = 'order:batch-unlock:'; +const BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + +const BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX = 'order:batch-unintercept:'; +const BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; + class PendingOrderService extends OrderBaseService { /** * 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。 @@ -28,9 +40,9 @@ class PendingOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; - const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress'; - const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress'; + const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; + const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; + const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -2333,6 +2345,2078 @@ class PendingOrderService extends OrderBaseService { }); } + /** + * 归一化 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) ]; + } + + /** + * 批量拦截订单。 + * + * 提交后台异步任务,将给定订单的 intercept_status 更新为 'requested'。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchIntercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchInterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchInterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchInterceptTaskId(warehouseId); + const existingTask = await this.getBatchInterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchInterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchIntercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchInterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchIntercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchInterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchInterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchInterceptTaskProgress(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_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.intercepted_order_count = Number(result.intercepted_order_count || 0); + payload.intercepted_order_ids = this.normalizeIdsInput(result.intercepted_order_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_order_count = Number(cachedProgress.total_order_count || 0); + payload.intercepted_order_count = Number(cachedProgress.intercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_INTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量拦截任务ID。 + * + * 格式:order_intercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchInterceptTaskId(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 `order_intercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchInterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchInterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchInterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_INTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchInterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchInterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchInterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_INTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchInterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchInterceptTaskCacheKey(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( + `[order.pendingOrder.batchIntercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'requested',并写入操作日志。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchInterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchInterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + intercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const interceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: [], + intercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可拦截的当前仓库订单', + }, + }); + return; + } + + // 分批更新拦截状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + intercept_status: 'requested', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_REQUEST', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'requested', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchIntercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + interceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((interceptedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchInterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + intercepted_order_count: interceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + intercepted_order_ids: interceptedOrderIds, + intercepted_order_count: interceptedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已拦截 ${interceptedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchInterceptTaskProgress(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: 'BATCH_INTERCEPT_FAILED', + }); + } + } + + /** + * 批量锁定订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 仅操作当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchLock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchLockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchLockTaskId(data); + const taskId = requestedTaskId || this.generateBatchLockTaskId(warehouseId); + const existingTask = await this.getBatchLockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量锁定任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchLockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchLock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchLockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchLock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量锁定任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量锁定任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchLockTaskProgress(data = {}) { + const taskId = this.normalizeBatchLockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchLockTaskProgress(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_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.locked_order_count = Number(result.locked_order_count || 0); + payload.locked_order_ids = this.normalizeIdsInput(result.locked_order_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_order_count = Number(cachedProgress.total_order_count || 0); + payload.locked_order_count = Number(cachedProgress.locked_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_LOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量锁定任务ID。 + * + * 格式:order_lock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchLockTaskId(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 `order_lock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量锁定任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchLockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量锁定的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchLockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量锁定任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchLockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_LOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchLockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchLockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchLockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_LOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchLock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量锁定任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchLockTaskProgress(taskId = '') { + const cacheKey = this.getBatchLockTaskCacheKey(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( + `[order.pendingOrder.batchLock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量锁定后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'warehouse',并写入操作日志 ORDER_LOCK。 + * 仅处理当前仓库上下文内的订单,每批最多 500 条。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchLockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchLockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchLockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + locked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const lockedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: [], + locked_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可锁定的当前仓库订单', + }, + }); + return; + } + + // 分批更新锁定状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'warehouse', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_LOCK + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_LOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'warehouse', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchLock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + lockedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((lockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchLockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchLockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + locked_order_count: lockedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + locked_order_ids: lockedOrderIds, + locked_order_count: lockedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已锁定 ${lockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchLockTaskProgress(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: 'BATCH_LOCK_FAILED', + }); + } + } + + /** + * 批量解锁订单(异步任务模式)。 + * + * 将给定订单的 lock_status 批量更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} data.order_ids 订单ID数组。 + * @param {string} [data.task_id] 可选的任务ID(用于幂等续查)。 + * @return {Promise} 提交响应,含 task_id。 + */ + async batchUnlock(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUnlockOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUnlockTaskId(data); + const taskId = requestedTaskId || this.generateBatchUnlockTaskId(warehouseId); + const existingTask = await this.getBatchUnlockTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解锁任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUnlockTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnlock] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUnlockTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnlock] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解锁任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解锁任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUnlockTaskProgress(data = {}) { + const taskId = this.normalizeBatchUnlockTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUnlockTaskProgress(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_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unlocked_order_count = Number(result.unlocked_order_count || 0); + payload.unlocked_order_ids = this.normalizeIdsInput(result.unlocked_order_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_order_count = Number(cachedProgress.total_order_count || 0); + payload.unlocked_order_count = Number(cachedProgress.unlocked_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNLOCK_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解锁任务ID。 + * + * 格式:order_unlock_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUnlockTaskId(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 `order_unlock_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解锁任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUnlockTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解锁的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUnlockOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解锁任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUnlockTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNLOCK_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUnlockTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUnlockTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUnlockTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNLOCK_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解锁任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUnlockTaskProgress(taskId = '') { + const cacheKey = this.getBatchUnlockTaskCacheKey(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( + `[order.pendingOrder.batchUnlock] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解锁后台任务。 + * + * 直接对给定订单ID数组,将 lock_status 更新为 'none',并写入操作日志 ORDER_UNLOCK。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUnlockTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUnlockTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unlocked_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const unlockedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: [], + unlocked_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解锁的当前仓库订单', + }, + }); + return; + } + + // 分批更新解锁状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + lock_status: 'none', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_UNLOCK + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_UNLOCK', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newLockStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnlock] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + unlockedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((unlockedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUnlockTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unlocked_order_count: unlockedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unlocked_order_ids: unlockedOrderIds, + unlocked_order_count: unlockedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解锁 ${unlockedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUnlockTaskProgress(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: 'BATCH_UNLOCK_FAILED', + }); + } + } + + /** + * 批量解除拦截订单(异步任务模式)。 + * + * 将给定订单的 intercept_status 批量更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 仅操作当前仓库上下文内的订单。 + * + * @param {Object} data 请求参数。 + * @param {Array} [data.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [data.orderIds] 订单ID数组(驼峰别名)。 + * @param {Array} [data.ids] 订单ID数组(简写别名)。 + * @param {string} [data.task_id] 任务ID(用于查询进度)。 + * @param {string} [data.taskId] 任务ID(驼峰别名)。 + * @return {Promise} 提交结果,包含 task_id、状态与 accepted_at。 + */ + async batchUnintercept(data = {}) { + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOrderIds = this.normalizeBatchUninterceptOrderIds(data); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 参数不能为空或格式错误'); + } + + const requestedTaskId = this.normalizeBatchUninterceptTaskId(data); + const taskId = requestedTaskId || this.generateBatchUninterceptTaskId(warehouseId); + const existingTask = await this.getBatchUninterceptTaskProgress(taskId); + + if (existingTask) { + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: Number(existingTask.warehouse_id || warehouseId), + state: String(existingTask.state || 'submitted').trim() || 'submitted', + message: '批量解除拦截任务已存在,请勿重复提交。', + accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), + }); + } + + const acceptedAt = new Date().toISOString(); + await this.setBatchUninterceptTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + order_ids: normalizedOrderIds.join(','), + order_id_list: normalizedOrderIds, + total_order_count: normalizedOrderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + result: null, + error: '', + error_code: '', + }); + + this.ctx.logger.info('[order.pendingOrder.batchUnintercept] 任务提交成功', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + }); + + setImmediate(() => { + this.runBatchUninterceptTask({ + taskId, + warehouseId, + orderIds: normalizedOrderIds, + }).catch(error => { + this.ctx.logger.error('[order.pendingOrder.batchUnintercept] 后台任务异常', { + taskId, + warehouseId, + orderCount: normalizedOrderIds.length, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return this.success('ok', { + status: 'success', + task_id: taskId, + warehouse_id: warehouseId, + message: '批量解除拦截任务已提交。', + accepted_at: acceptedAt, + }); + } + + /** + * 查询批量解除拦截任务进度。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度响应。 + */ + async batchUninterceptTaskProgress(data = {}) { + const taskId = this.normalizeBatchUninterceptTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getBatchUninterceptTaskProgress(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_order_count = Number(cachedProgress.total_order_count || 0); + payload.processed_order_count = Number(cachedProgress.processed_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + } + + if (state === 'success') { + const result = this.isPlainObject(cachedProgress.result) ? cachedProgress.result : {}; + payload.progress_percent = Number(cachedProgress.progress_percent || 100); + payload.total_order_count = Number(result.total_order_count || 0); + payload.unintercepted_order_count = Number(result.unintercepted_order_count || 0); + payload.unintercepted_order_ids = this.normalizeIdsInput(result.unintercepted_order_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_order_count = Number(cachedProgress.total_order_count || 0); + payload.unintercepted_order_count = Number(cachedProgress.unintercepted_order_count || 0); + payload.error_message = String(cachedProgress.error || '').trim(); + payload.error_code = String(cachedProgress.error_code || '').trim() || 'BATCH_UNINTERCEPT_FAILED'; + payload.duration_ms = Number(cachedProgress.duration_ms || 0); + } + + return this.success('ok', payload); + } + + /** + * 生成可追踪的批量解除拦截任务ID。 + * + * 格式:order_unintercept_{warehouseId}_{timestamp}_{rand}。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateBatchUninterceptTaskId(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 `order_unintercept_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化批量解除拦截任务ID。 + * + * @param {Object} data 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeBatchUninterceptTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 归一化批量解除拦截的订单ID参数。 + * 兼容 order_ids / orderIds / ids 三种入参别名。 + * + * @param {Object} data 请求参数。 + * @return {Array} 归一化后的订单ID数组。 + */ + normalizeBatchUninterceptOrderIds(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const rawOrderIds = normalizedData.order_ids !== undefined + ? normalizedData.order_ids + : normalizedData.orderIds !== undefined + ? normalizedData.orderIds + : normalizedData.ids !== undefined + ? normalizedData.ids + : []; + + return this.normalizeIdsInput(rawOrderIds); + } + + /** + * 获取批量解除拦截任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getBatchUninterceptTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${BATCH_UNINTERCEPT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态(submitted|running|success|failed)。 + * @param {Object} data 进度或结果数据。 + * @return {Promise} 无返回值。 + */ + async setBatchUninterceptTaskProgress(taskId = '', state = 'submitted', data = {}) { + const cacheKey = this.getBatchUninterceptTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safeData = this.isPlainObject(data) ? data : {}; + const mergedPayload = { + ...(await this.getBatchUninterceptTaskProgress(taskId) || {}), + ...safeData, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, BATCH_UNINTERCEPT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 写入任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + } + } + + /** + * 读取批量解除拦截任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getBatchUninterceptTaskProgress(taskId = '') { + const cacheKey = this.getBatchUninterceptTaskCacheKey(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( + `[order.pendingOrder.batchUnintercept] 读取任务进度缓存失败: ${error && error.message ? error.message : error}` + ); + return null; + } + } + + /** + * 执行批量解除拦截后台任务。 + * + * 直接对给定订单ID数组,将 intercept_status 更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。 + * 仅处理当前仓库上下文内的订单。 + * + * @param {Object} params 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 + * @param {Array|number|string} [params.orderIds] 订单ID集合(兜底)。 + * @return {Promise} 无返回值。 + */ + async runBatchUninterceptTask(params = {}) { + const { ctx } = this; + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getBatchUninterceptTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + const orderIds = this.normalizeIdsInput( + cachedTask && cachedTask.order_ids !== undefined + ? cachedTask.order_ids + : params && params.orderIds + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + if (orderIds.length === 0) { + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + end_time: Date.now(), + error: 'order_ids 参数不能为空或格式错误', + error_code: 'INVALID_ORDER_IDS', + }); + return; + } + + const startTime = Date.now(); + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + order_ids: orderIds.join(','), + order_id_list: orderIds, + total_order_count: orderIds.length, + processed_order_count: 0, + unintercepted_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + result: null, + error: '', + error_code: '', + failed_order_id: 0, + }); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const { Op } = this.app.Sequelize; + + // 分批查询订单是否存在且属于当前仓库 + const BATCH_SIZE = 500; + const validOrderRows = []; + + for (let i = 0; i < orderIds.length; i += BATCH_SIZE) { + const chunkOrderIds = orderIds.slice(i, i + BATCH_SIZE); + if (chunkOrderIds.length === 0) { + continue; + } + + const orderRows = await orderModel.findAll({ + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ], + where: { + warehouse_id: warehouseId, + id: { + [Op.in]: chunkOrderIds, + }, + }, + raw: true, + }); + + for (const row of (Array.isArray(orderRows) ? orderRows : [])) { + validOrderRows.push(row); + } + } + + const uninterceptedOrderIds = []; + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + + const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : []; + const totalOrderCount = orderIds.length; + const validOrderCount = normalizedOrderRows.length; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + valid_order_count: validOrderCount, + }); + + if (validOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: [], + unintercepted_order_count: 0, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: '未找到可解除拦截的当前仓库订单', + }, + }); + return; + } + + // 分批更新解除拦截状态,每批最多500条 + const UPDATE_CHUNK_SIZE = 500; + for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) { + const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE); + if (chunkRows.length === 0) { + continue; + } + + const chunkOrderIds = chunkRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0); + if (chunkOrderIds.length === 0) { + continue; + } + + const now = new Date(); + const updateValues = { + intercept_status: 'none', + updated_at: now, + }; + + await orderModel.update(updateValues, { + where: { + id: { + [Op.in]: chunkOrderIds, + }, + }, + }); + + // 写入操作日志 ORDER_INTERCEPT_CANCEL + const logPayloads = chunkRows.map(row => { + const orderId = Number(row.id || 0); + const orderNo = String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(); + if (!Number.isInteger(orderId) || orderId <= 0) { + return null; + } + + return { + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CANCEL', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + newInterceptStatus: 'none', + }, + beforeChanges: null, + }; + }).filter(Boolean); + + if (logPayloads.length > 0) { + try { + const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (operationLogService && typeof operationLogService.createOperationLogs === 'function') { + await operationLogService.createOperationLogs(logPayloads); + } + } catch (logErr) { + ctx.logger.warn( + `[order.pendingOrder.batchUnintercept] 批量写操作日志失败,不影响主流程, count=${logPayloads.length}, error=${logErr.message}` + ); + } + } + + for (const orderId of chunkOrderIds) { + uninterceptedOrderIds.push(orderId); + } + + // 更新进度 + const progressPercent = validOrderCount > 0 + ? Math.min(99, Math.round((uninterceptedOrderIds.length / validOrderCount) * 100)) + : 0; + + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: progressPercent, + }); + } + + const durationMs = Date.now() - startTime; + await this.setBatchUninterceptTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + unintercepted_order_count: uninterceptedOrderIds.length, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + order_ids: orderIds, + unintercepted_order_ids: uninterceptedOrderIds, + unintercepted_order_count: uninterceptedOrderIds.length, + total_order_count: totalOrderCount, + duration_ms: durationMs, + message: `已解除拦截 ${uninterceptedOrderIds.length} 条订单`, + }, + }); + } catch (error) { + await this.setBatchUninterceptTaskProgress(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: 'BATCH_UNINTERCEPT_FAILED', + }); + } + } + } module.exports = PendingOrderService; diff --git a/app/service/systemMethods/order/print.js b/app/service/systemMethods/order/print.js index efd8877..d86af2c 100644 --- a/app/service/systemMethods/order/print.js +++ b/app/service/systemMethods/order/print.js @@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; - const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; - const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup'; + const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; + const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -90,6 +90,36 @@ class OrderPrintService extends OrderBaseService { }); } + /** + * 按订单ID拉取平台打印中间态数据。 + * + * method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。 + * 仓库ID统一从当前上下文获取,无需调用方传入。 + * + * @param {Object} data 请求体。 + * @param {Array} data.order_ids 订单ID数组。 + * @return {Promise} 统一 success 包装的平台打印中间态结果。 + */ + async getOrderPrintData(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { + order_ids: orderIds, + } = requestData; + + if (!Array.isArray(orderIds) || orderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const result = await this.service.systems.orderPrint.getOrderPrintData({ + orderIds, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } + /** * 按分组解锁波次平台打印锁。 * diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index 691d25e..34fbe9e 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -10,62 +10,943 @@ class RecheckOrderService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'scanOrder,scanWaybill,confirmRecheck'; - const _noNeedLog = 'scanOrder,scanWaybill,confirmRecheck'; - const _noNeedAuth = 'scanOrder,scanWaybill,confirmRecheck'; + const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; + const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; + const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } /** - * 扫描关键词并返回订单头与商品明细。 + * 扫描关键词并返回以波次为单位的复核视图。 + * 支持运单号、波次号、车号三种匹配模式。 + * - 运单号/波次号匹配(散单):返回匹配订单所在波次的所有订单,list_type='single', + * 顶层携带波次/拣货人/策略/任务ID等汇总信息,list 为扁平订单数组 + * - 车号匹配(团单):返回拣货任务下所有团购波次及订单,list_type='group',保持嵌套结构, + * 顶层携带 task_id * @param {Object} data 请求体。 * @param {string} [data.keyword] 通用扫描关键词。 * @param {string} [data.value] 通用扫描关键词别名。 * @param {string} [data.waybill_no] 运单号。 * @param {string} [data.waybillCode] 运单号别名。 * @param {string} [data.waybill_code] 运单号别名。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 * @param {string} [data.cart_code] 车号。 * @param {string} [data.cartCode] 车号别名。 - * @return {Promise} 扫描结果。 + * @return {Promise} 扫描结果,包含 match_type、list_type、task_id(散单/团单均有)与 list 数组。 */ async scanOrder(data = {}) { const warehouseId = this.getWarehouseId(); const keyword = this.resolveScanKeyword(data); const matchedResult = await this.pickOrderMatchByKeyword(keyword); - const { orderId, matchType, cartMatchContext } = matchedResult; + const { orderId, matchType, cartMatchContext, waveMatchContext } = matchedResult; + + // 散单处理:运单号匹配 → 查找订单所在波次 → 拉取波次全量订单 + if (matchType === 'waybill') { + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const order = await orderModel.findOne({ + where: this.buildOrderWhere([ orderId ], warehouseId), + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status', 'delivery_order_code' ], + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + const orderWaveId = Number(order.wave_id || 0); + const orderWaveNo = String(order.wave_no || '').trim(); + + if (orderWaveId > 0 && orderWaveNo) { + const scanView = await this.buildSingleWaveScanView(orderWaveId, orderWaveNo, warehouseId); + if (scanView) { + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [], + }; + } + + // 无波次信息时退回单订单模式 + this.assertOrderCanRecheck(order); + const detailResult = await this.detail({ id: orderId }); + return { + match_type: matchType, + list_type: 'single', + waybill_no: keyword, + list: [{ + ...(detailResult.detail || {}), + items: Array.isArray(detailResult.items) ? detailResult.items : [], + expresses: Array.isArray(detailResult.expresses) ? detailResult.expresses : [], + logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + }], + }; + } + + // 散单处理:波次号匹配 → 直接按波次号查找波次及订单 + if (matchType === 'wave') { + const waveId = Number(waveMatchContext?.wave?.wave_id || 0); + const waveNo = String(waveMatchContext?.wave?.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + if (scanView) { + return { + match_type: matchType, + list_type: 'single', + ...scanView, + }; + } + return { + match_type: matchType, + list_type: 'single', + list: [], + }; + } + + throw new Error('波次信息不完整,无法加载复核视图'); + } + + // 团单处理:车号匹配 → 查找拣货任务 → 拉取任务下所有团购波次 + if (matchType === 'cart' && cartMatchContext) { + const taskId = Number(cartMatchContext?.task?.task_id || 0); + + if (taskId > 0) { + const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + return { + match_type: 'cart', + list_type: 'group', + task_id: taskId, + list: groupWaveList, + }; + } + + throw new Error('拣货任务信息不完整,无法加载团购复核视图'); + } + + throw new Error('未找到对应订单'); + } + + /** + * 通过拣货任务ID刷新复核扫描视图。 + * 根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。 + * - 散单模式(pick_mode 2/3/4):扁平化任务下所有波次的订单列表,顶层携带拣货人/任务等汇总信息 + * - 团购模式(pick_mode 1/5):返回任务下所有团购波次及订单的分组列表 + * @param {Object} data 请求体。 + * @param {number} data.task_id 拣货任务ID。 + * @return {Promise} 扫描视图,包含 match_type、list_type、task_id、list 等字段, + * 散单模式额外包含 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count。 + */ + async scanTask(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const taskId = Number(requestData.task_id || 0); + + if (!Number.isFinite(taskId) || taskId <= 0) { + throw new Error('task_id 无效'); + } + + const warehouseId = this.getWarehouseId(); + const { ctx } = this; + + // 查询拣货任务信息 + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, pick_user_id, pick_user_name + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + throw new Error('未找到对应拣货任务'); + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY wave_id ASC + `, + { + replacements: { taskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 团购模式(pick_mode 1 或 5):复用 buildGroupWaveList + if (pickMode === 1 || pickMode === 5) { + const groupWaveList = await this.buildGroupWaveList(taskId, warehouseId); + + return { + match_type: 'task', + list_type: 'group', + task_id: taskId, + list: groupWaveList, + }; + } + + // 散单模式(pick_mode 2、3、4):逐波次构建扫描视图并合并 + const scanViews = []; + + for (const tw of taskWaves) { + const waveId = Number(tw.wave_id || 0); + const waveNo = String(tw.wave_no || '').trim(); + + if (waveId > 0 && waveNo) { + const scanView = await this.buildSingleWaveScanView(waveId, waveNo, warehouseId); + + if (scanView) { + scanViews.push(scanView); + } + } + } + + if (scanViews.length === 0) { + return { + match_type: 'task', + list_type: 'single', + task_id: taskId, + pick_mode: pickMode, + list: [], + }; + } + + // 合并所有波次的订单列表(按 order_id 去重) + const allOrders = scanViews.flatMap(v => (Array.isArray(v.list) ? v.list : [])); + const seenOrderIds = new Set(); + const mergedList = []; + + for (const order of allOrders) { + const oid = Number(order.order_id || 0); + + if (oid > 0 && !seenOrderIds.has(oid)) { + seenOrderIds.add(oid); + mergedList.push(order); + } + } + + // 排序:未复核的排前面,其次按 wave_index 从小到大 + mergedList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + + return (Number(a.wave_index || 0)) - (Number(b.wave_index || 0)); + }); + + const totalOrders = mergedList.length; + const reviewedCount = mergedList.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = totalOrders - reviewedCount; + const waveType = scanViews.find(v => Number(v.wave_type || 0) > 0)?.wave_type || 0; + + return { + match_type: 'task', + list_type: 'single', + picker_id: taskRow.pick_user_id != null ? Number(taskRow.pick_user_id) : null, + picker_name: String(taskRow.pick_user_name || '').trim(), + task_id: taskId, + wave_id: 0, + wave_no: '', + wave_type: Number(waveType || 0), + pick_mode: pickMode, + strategy_id: null, + strategy_name: '', + total_orders: totalOrders, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: mergedList, + }; + } + + /** + * 构建散单模式的扁平化扫描复核视图。 + * 将波次信息、拣货人、策略、任务ID等提升到顶层,订单列表扁平化。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 扁平化扫描视图,包含 picker_id、picker_name、task_id、wave_id、wave_no、 + * wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count、list。 + */ + async buildSingleWaveScanView(waveId, waveNo, warehouseId) { + const baseWaveView = await this.buildSingleWaveView(waveId, waveNo, warehouseId); + + if (!baseWaveView) { + return null; + } + + const normalizedWaveId = Number(waveId || 0); + const orders = Array.isArray(baseWaveView.orders) ? baseWaveView.orders : []; + + // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 + for (const order of orders) { + this.assertOrderCanRecheck(order); + } + + // 并行查询拣货人信息和策略信息 + const [ pickerInfo, strategyInfo ] = await Promise.all([ + this.getPickerInfoByWaveId(normalizedWaveId, warehouseId), + this.getWaveStrategyInfo(normalizedWaveId, warehouseId), + ]); + + // 计算复核汇总 + const reviewedCount = orders.filter(o => o.recheck_status === 'fin').length; + const unreviewedCount = orders.length - reviewedCount; + + return { + picker_id: pickerInfo.picker_id, + picker_name: pickerInfo.picker_name, + task_id: pickerInfo.task_id, + wave_id: baseWaveView.wave_id, + wave_no: baseWaveView.wave_no, + wave_type: baseWaveView.wave_type, + pick_mode: baseWaveView.pick_mode, + strategy_id: strategyInfo.strategy_id, + strategy_name: strategyInfo.strategy_name, + total_orders: orders.length, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + list: orders, + }; + } + + /** + * 构建单个波次的复核视图(散单/团单内部共用)。 + * 查询波次信息、拣货模式、以及波次下全部订单列表。 + * @param {number} waveId 波次ID。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 波次视图对象,包含 wave_id、wave_no、wave_type、pick_mode、order_count、orders。 + */ + async buildSingleWaveView(waveId, waveNo, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + const normalizedWaveNo = String(waveNo || '').trim(); + + if (normalizedWaveId <= 0 || !normalizedWaveNo) { + return null; + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_id = :waveId + AND wave_no = :waveNo + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return null; + } + + // 查询波次关联的拣货任务,获取 pick_mode + const pickMode = await this.getPickModeByWaveId(normalizedWaveId, warehouseId); + + // 查询波次下所有订单 + const orders = await this.getWaveOrdersBasic(normalizedWaveNo, warehouseId); + const orderCount = orders.length; + + return { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + pick_mode: pickMode, + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + order_count: orderCount, + orders, + }; + } + + /** + * 构建团购波次列表视图(团单模式)。 + * 根据拣货任务ID查找关联的所有波次,每个波次展开为一项。 + * @param {number} taskId 拣货任务ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 波次视图列表。 + */ + async buildGroupWaveList(taskId, warehouseId) { + const { ctx } = this; + const normalizedTaskId = Number(taskId || 0); + + if (normalizedTaskId <= 0) { + return []; + } + + // 查询拣货任务信息,获取 pick_mode + const taskRows = await ctx.model.query( + ` + SELECT id AS task_id, pick_mode, current_cart_code_snapshot + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + + if (!taskRow) { + return []; + } + + const pickMode = Number(taskRow.pick_mode || 0); + + // 查询任务关联的所有波次 + const taskWaveRows = await ctx.model.query( + ` + SELECT wave_id, wave_no, box_no + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + ORDER BY box_no ASC, wave_id ASC + `, + { + replacements: { taskId: normalizedTaskId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const taskWaves = Array.isArray(taskWaveRows) ? taskWaveRows : []; + + // 并行查询每个波次的详细信息和订单 + const waveViewPromises = taskWaves.map(async tw => { + const twWaveId = Number(tw.wave_id || 0); + const twWaveNo = String(tw.wave_no || '').trim(); + + if (twWaveId <= 0 || !twWaveNo) { + return null; + } + + const waveView = await this.buildSingleWaveView(twWaveId, twWaveNo, warehouseId); + + if (!waveView) { + return null; + } + + // 校验波次内所有订单是否都已拣货,未拣货订单不允许复核 + const orders = Array.isArray(waveView.orders) ? waveView.orders : []; + for (const order of orders) { + this.assertOrderCanRecheck(order); + } + + // 使用任务级别的 pick_mode 覆盖(团单模式下以任务为准) + return { + ...waveView, + pick_mode: pickMode, + box_no: Number(tw.box_no || 0), + }; + }); + + const waveViews = await Promise.all(waveViewPromises); + + return waveViews.filter(view => view !== null); + } + + /** + * 通过波次ID查询关联的拣货模式。 + * 优先查询 wms_wave_pick_task.wave_id,其次查 wms_wave_pick_task_wave 关联。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 拣货模式编码,未找到返回 0。 + */ + async getPickModeByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return 0; + } + + // 先按 wave_id 直接查拣货任务 + const taskRows = await ctx.model.query( + ` + SELECT pick_mode + FROM wms_wave_pick_task + WHERE wave_id = :waveId + AND warehouse_id = :warehouseId + ORDER BY create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(taskRows) && taskRows.length > 0) { + return Number(taskRows[0].pick_mode || 0); + } + + // 通过 wms_wave_pick_task_wave 关联查询 + const twRows = await ctx.model.query( + ` + SELECT t.pick_mode + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + if (Array.isArray(twRows) && twRows.length > 0) { + return Number(twRows[0].pick_mode || 0); + } + + return 0; + } + + /** + * 查询波次下所有订单的基本信息列表。 + * 包含运单号、打印状态、复核状态、波次内序号(优先从 wms_order_wave_index 读取真实 wave_index, + * 若表无记录则降级使用 Array.map 临时序号),按未复核优先 + 波次内序号升序排序。 + * @param {string} waveNo 波次号。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单基本信息列表,每项含 order_id、delivery_order_code、 + * waybill_no、pick_status、is_printed、is_reviewed、shop_nick、items_count、 + * wave_index、recheck_status、wave_id、wave_no、order_type、status、 + * logistics_name、store_remark、intercept_status、stock 等字段。 + */ + async getWaveOrdersBasic(waveNo, warehouseId) { + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return []; + } + const orderModel = await this.getOrderModelByTableType('current', warehouseId); - const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); - const order = await orderModel.findOne({ - where: orderWhere, + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + 'items_count', + 'shop_nick', + 'logistics_name', + 'print_status', + 'store_id', + 'intercept_status', + ], + order: [[ 'id', 'ASC' ]], raw: true, }); - if (!order) { - throw new Error('未找到对应订单'); + const { ctx } = this; + const orderRowsArray = Array.isArray(orderRows) ? orderRows : []; + const orderIds = orderRowsArray.map(row => Number(row.id || 0)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } } - this.assertOrderCanRecheck(order); + // 批量查询运单信息 + const waybillMap = new Map(); + if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) { + const expressRows = await ctx.model.OrderExpress.findAll({ + where: { order_id: orderIds }, + attributes: [ 'order_id', 'waybill_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + for (const er of (Array.isArray(expressRows) ? expressRows : [])) { + const oid = Number(er.order_id || 0); + if (oid > 0 && !waybillMap.has(oid)) { + waybillMap.set(oid, String(er.waybill_code || '').trim()); + } + } + } - const detailResult = await this.detail({ - id: orderId, + // 批量查询波次顺序索引(wms_order_wave_index) + const waveIndexMap = new Map(); + if (orderIds.length > 0 && ctx.model && typeof ctx.model.query === 'function') { + const waveIds = [ + ...new Set( + orderRowsArray + .map(row => Number(row.wave_id || 0)) + .filter(id => id > 0) + ), + ]; + if (waveIds.length > 0) { + try { + const waveIndexRows = await ctx.model.query( + ` + SELECT order_id, wave_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND order_id IN (:orderIds) + `, + { + replacements: { warehouseId, waveIds, orderIds }, + type: ctx.model.QueryTypes && ctx.model.QueryTypes.SELECT, + } + ); + for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) { + const wrOrderId = Number(wr && wr.order_id || 0); + if (wrOrderId > 0) { + waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0)); + } + } + } catch (e) { + ctx.logger.warn(`[recheckOrder.getWaveOrdersBasic] 查询波次索引失败, waveNo=${normalizedWaveNo}, error=${e.message}`); + } + } + } + + // 构建订单列表 + const orderList = orderRowsArray.map((row, index) => { + const orderId = Number(row.id || 0); + const recheckStatus = String(row.recheck_status || '').trim(); + const printStatus = String(row.print_status || '').trim(); + + // 运单号:从 wms_order_express 关联表查询 + const waybillNo = waybillMap.has(orderId) ? (waybillMap.get(orderId) || '') : ''; + + return { + order_id: orderId, + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + waybill_no: waybillNo, + pick_status: String(row.pick_status || '').trim(), + is_printed: printStatus === 'fin', + is_reviewed: recheckStatus === 'fin', + shop_nick: String(row.shop_nick || '').trim(), + items_count: Number(row.items_count || 0), + wave_index: waveIndexMap.has(orderId) ? waveIndexMap.get(orderId) : index, + recheck_status: recheckStatus, + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + logistics_name: String(row.logistics_name || '').trim(), + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + intercept_status: String(row.intercept_status || '').trim(), + }; }); - const expresses = Array.isArray(detailResult.expresses) ? detailResult.expresses : []; - const resolvedWaybillNo = matchType === 'waybill' - ? keyword - : String(expresses?.[0]?.waybill_code || '').trim(); - const cartMatchView = matchType === 'cart' - ? await this.buildCartMatchView(cartMatchContext) - : null; + + // 排序:未复核的排前面,其次按波次内序号从小到大 + orderList.sort((a, b) => { + const aReviewed = a.is_reviewed ? 1 : 0; + const bReviewed = b.is_reviewed ? 1 : 0; + if (aReviewed !== bReviewed) { + return aReviewed - bReviewed; + } + return a.wave_index - b.wave_index; + }); + + // 补充库存信息 + const enrichedList = await this.enrichOrdersWithStock(orderList, warehouseId); + return enrichedList; + } + + /** + * 为订单列表批量补充库存信息。 + * 查询每个订单的明细商品、库存数量、条码列表和图片,构建 stock 数组。 + * @param {Object[]} orderList 订单基本信息列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 补充了 stock 字段的订单列表。 + */ + async enrichOrdersWithStock(orderList, warehouseId) { + if (!Array.isArray(orderList) || orderList.length === 0) { + return orderList; + } + + const orderIds = orderList.map(o => Number(o.order_id || 0)).filter(Boolean); + if (orderIds.length === 0) { + return orderList; + } + + // 1. 批量查询所有订单的商品明细 + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const allOrderItems = await orderItemsModel.findAll({ + where: { + order_id: { [this.app.Sequelize.Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const itemsArray = Array.isArray(allOrderItems) ? allOrderItems : []; + + // 2. 收集所有唯一的 stock_id + const stockIds = [ ...new Set( + itemsArray + .map(item => Number(item.stock_id)) + .filter(Boolean) + ) ]; + + // 3. 批量查询库存信息 + const stockMap = new Map(); + if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockWarehouse) { + const stockRows = await this.ctx.model.StockWarehouse.findAll({ + where: { + id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'packing_requirements' ], + raw: true, + }); + for (const row of (Array.isArray(stockRows) ? stockRows : [])) { + stockMap.set(Number(row.id), row); + } + } + + // 4. 批量查询条码 + const barcodeMap = new Map(); + if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { + const barcodeRows = await this.ctx.model.StockBarcode.findAll({ + where: { + stock_id: { [this.app.Sequelize.Op.in]: stockIds }, + warehouse_id: warehouseId, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }); + for (const row of (Array.isArray(barcodeRows) ? barcodeRows : [])) { + const sid = Number(row.stock_id); + const barcodeVal = String(row.barcode || '').trim(); + if (!barcodeMap.has(sid)) { + barcodeMap.set(sid, []); + } + if (barcodeVal) { + barcodeMap.get(sid).push(barcodeVal); + } + } + } + + // 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中 + const sharedBarcodeSet = new Set(); + if (barcodeMap.size > 0) { + const allBarcodes = []; + for (const [ , barcodes ] of barcodeMap) { + for (const bc of barcodes) { + allBarcodes.push(bc); + } + } + if (allBarcodes.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) { + const sharedRows = await this.ctx.model.query( + `SELECT barcode, COUNT(DISTINCT stock_id) AS cnt + FROM wms_stock_barcodes + WHERE barcode IN (:barcodes) + AND warehouse_id = :warehouseId + GROUP BY barcode + HAVING cnt > 1`, + { + replacements: { barcodes: allBarcodes, warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + for (const row of (Array.isArray(sharedRows) ? sharedRows : [])) { + sharedBarcodeSet.add(String(row.barcode || '').trim()); + } + } + } + + // 6. 批量查询图片 + const imagesByStockId = await this.getOrderItemImagesByStockIds(itemsArray); + + // 7. 按 order_id 分组商品明细 + const itemsByOrderId = new Map(); + for (const item of itemsArray) { + const oid = Number(item.order_id); + if (!itemsByOrderId.has(oid)) { + itemsByOrderId.set(oid, []); + } + itemsByOrderId.get(oid).push(item); + } + + // 8. 为每个订单构建 stock 数组 + return orderList.map(order => { + const oid = Number(order.order_id || 0); + const items = itemsByOrderId.get(oid) || []; + const stock = items.map(item => { + const sid = Number(item.stock_id || 0); + const stockInfo = stockMap.get(sid) || {}; + const barcodes = (() => { + const arr = barcodeMap.get(sid); + if (Array.isArray(arr) && arr.length > 0) { + return arr; + } + return [ String(item.item_code || '').trim() ]; + })(); + const images = imagesByStockId.get(sid) || []; + + const hasSharedBarcode = (() => { + const arr = barcodeMap.get(sid); + if (Array.isArray(arr) && arr.length > 0) { + return arr.some(bc => sharedBarcodeSet.has(bc)); + } + return false; + })(); + + return { + stock_id: sid, + item_code: String(item.item_code || stockInfo.item_code || '').trim(), + item_name: String(stockInfo.item_name || item.item_name || '').trim(), + sku_property: String(stockInfo.sku_property || '').trim(), + packing_requirements: String(stockInfo.packing_requirements || '').trim(), + barcodes, + images, + has_shared_barcode: hasSharedBarcode, + plan_qty: Number(item.plan_qty || 0), + }; + }); + + return { + ...order, + stock, + }; + }); + } + + /** + * 通过波次ID查询关联的拣货人信息及任务ID。 + * 通过 wms_wave_pick_task_wave 关联 wms_wave_pick_task 获取 pick_user_id / pick_user_name / task_id。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ picker_id: number|null, picker_name: string, task_id: number|null }>} 拣货人信息及任务ID。 + */ + async getPickerInfoByWaveId(waveId, warehouseId) { + const { ctx } = this; + const normalizedWaveId = Number(waveId || 0); + + if (normalizedWaveId <= 0) { + return { picker_id: null, picker_name: '', task_id: null }; + } + + const rows = await ctx.model.query( + ` + SELECT t.pick_user_id, t.pick_user_name, t.id AS task_id + FROM wms_wave_pick_task_wave tw + INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id + WHERE tw.wave_id = :waveId + AND tw.warehouse_id = :warehouseId + AND t.pick_user_id IS NOT NULL + ORDER BY t.create_time DESC + LIMIT 1 + `, + { + replacements: { waveId: normalizedWaveId, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const row = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; return { - match_type: matchType, - cart_match_view: cartMatchView, - order_id: orderId, - waybill_no: resolvedWaybillNo, - order: detailResult.detail || {}, - items: Array.isArray(detailResult.items) ? detailResult.items : [], - expresses, - logs: Array.isArray(detailResult.logs) ? detailResult.logs : [], + picker_id: row && row.pick_user_id != null ? Number(row.pick_user_id) : null, + picker_name: String(row && row.pick_user_name || '').trim(), + task_id: row && row.task_id != null ? Number(row.task_id) : null, + }; + } + + /** + * 查询波次关联的策略信息。 + * 当前 wms_wave_batch 与 wms_wave_pick_task 均未直接存储 strategy_id, + * 因此默认返回 null,后续若补充关联字段可在此扩展查询逻辑。 + * @param {number} waveId 波次ID。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{ strategy_id: number|null, strategy_name: string }>} 策略信息。 + */ + // eslint-disable-next-line no-unused-vars + async getWaveStrategyInfo(waveId, warehouseId) { + return { + strategy_id: null, + strategy_name: '', }; } @@ -375,6 +1256,8 @@ class RecheckOrderService extends OrderBaseService { /** * 从多种兼容字段中解析扫描关键词。 * @param {Object} data 请求体。 + * @param {string} [data.wave_no] 波次号。 + * @param {string} [data.waveNo] 波次号别名。 * @return {string} 规范化后的扫描关键词。 */ resolveScanKeyword(data = {}) { @@ -385,11 +1268,13 @@ class RecheckOrderService extends OrderBaseService { waybill_no: waybillNo, waybillCode, waybill_code: waybillCodeAlias, + wave_no: waveNo, + waveNo: waveNoAlias, cart_code: cartCode, cartCode: cartCodeAlias, } = requestData; const normalizedKeyword = String( - keyword || value || waybillNo || waybillCode || waybillCodeAlias || cartCode || cartCodeAlias || '' + keyword || value || waybillNo || waybillCode || waybillCodeAlias || waveNo || waveNoAlias || cartCode || cartCodeAlias || '' ).trim(); if (!normalizedKeyword) { @@ -401,9 +1286,9 @@ class RecheckOrderService extends OrderBaseService { /** * 根据扫描关键词解析订单ID。 - * 优先按运单号匹配,未命中时回退到车号匹配。 + * 匹配优先级:运单号 → 波次号 → 车号。 * @param {string} keyword 扫描关键词。 - * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object }>} 命中结果。 + * @return {Promise<{ orderId: number, matchType: string, cartMatchContext?: Object, waveMatchContext?: Object }>} 命中结果。 */ async pickOrderMatchByKeyword(keyword) { const waybillOrderId = await this.pickOrderIdByWaybill(keyword); @@ -415,6 +1300,17 @@ class RecheckOrderService extends OrderBaseService { }; } + const waveMatchContext = await this.pickWaveMatchContextByWaveNo(keyword); + const waveOrderId = Number(waveMatchContext?.order_id || 0); + + if (Number.isFinite(waveOrderId) && waveOrderId > 0) { + return { + orderId: waveOrderId, + matchType: 'wave', + waveMatchContext, + }; + } + const cartMatchContext = await this.pickCartMatchContextByCartCode(keyword); const cartOrderId = Number(cartMatchContext?.order_id || 0); @@ -467,6 +1363,119 @@ class RecheckOrderService extends OrderBaseService { return Number.isFinite(orderId) && orderId > 0 ? orderId : 0; } + /** + * 根据波次号查询波次信息及波次下订单列表。 + * @param {string} waveNo 波次号。 + * @return {Promise<{order_id:number, wave:Object|null, orders:Array, matched_order_ids:Array}>} 命中上下文。 + */ + async pickWaveMatchContextByWaveNo(waveNo) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const normalizedWaveNo = String(waveNo || '').trim(); + + if (!normalizedWaveNo) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + // 查询波次批次信息 + const waveRows = await ctx.model.query( + ` + SELECT + wave_id, + wave_no, + wave_type, + wave_status, + total_orders, + processed_orders, + creator, + create_time, + update_time + FROM wms_wave_batch + WHERE wave_no = :waveNo + AND warehouse_id = :warehouseId + ORDER BY create_time DESC, wave_id DESC + LIMIT 1 + `, + { + replacements: { waveNo: normalizedWaveNo, warehouseId }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const waveRow = Array.isArray(waveRows) && waveRows.length > 0 ? waveRows[0] : null; + + if (!waveRow) { + return { + order_id: 0, + wave: null, + orders: [], + matched_order_ids: [], + }; + } + + const wave = { + wave_id: Number(waveRow.wave_id || 0), + wave_no: String(waveRow.wave_no || '').trim(), + wave_type: Number(waveRow.wave_type || 0), + wave_status: Number(waveRow.wave_status || 0), + total_orders: Number(waveRow.total_orders || 0), + processed_orders: Number(waveRow.processed_orders || 0), + creator: String(waveRow.creator || '').trim(), + create_time: waveRow.create_time || null, + update_time: waveRow.update_time || null, + }; + + // 查询波次下的订单列表 + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderRows = await orderModel.findAll({ + where: { + wave_no: normalizedWaveNo, + warehouse_id: warehouseId, + }, + attributes: [ + 'id', + 'delivery_order_code', + 'pre_delivery_order_code', + 'pick_status', + 'wave_id', + 'wave_no', + 'order_type', + 'status', + 'recheck_status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const orders = (Array.isArray(orderRows) ? orderRows : []).map(row => ({ + order_id: Number(row.id || 0), + delivery_order_code: String(row.delivery_order_code || row.pre_delivery_order_code || '').trim(), + pick_status: String(row.pick_status || '').trim(), + wave_id: Number(row.wave_id || 0), + wave_no: String(row.wave_no || '').trim(), + order_type: String(row.order_type || '').trim(), + status: Number(row.status || 0), + recheck_status: String(row.recheck_status || '').trim(), + })); + + const matchedOrderIds = [ ...new Set(orders + .map(o => Number(o.order_id)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + const primaryOrderId = Number(matchedOrderIds[0] || 0); + + return { + order_id: Number.isFinite(primaryOrderId) && primaryOrderId > 0 ? primaryOrderId : 0, + wave, + orders, + matched_order_ids: matchedOrderIds, + }; + } + /** * 根据车号读取任务上下文及任务订单行。 * @param {string} cartCode 车号。 @@ -633,6 +1642,31 @@ class RecheckOrderService extends OrderBaseService { return pickModeMap[normalizedPickMode] || '未知模式'; } + /** + * 构建波次号命中语义化视图。 + * @param {Object} waveMatchContext 波次号命中上下文。 + * @return {Promise} 语义化视图。 + */ + async buildWaveMatchView(waveMatchContext = {}) { + const context = this.isPlainObject(waveMatchContext) ? waveMatchContext : {}; + const wave = this.isPlainObject(context.wave) ? context.wave : {}; + const orders = Array.isArray(context.orders) ? context.orders : []; + + return { + wave_id: Number(wave.wave_id || 0), + wave_no: String(wave.wave_no || '').trim(), + wave_type: Number(wave.wave_type || 0), + wave_status: Number(wave.wave_status || 0), + total_orders: Number(wave.total_orders || 0), + processed_orders: Number(wave.processed_orders || 0), + creator: String(wave.creator || '').trim(), + create_time: wave.create_time || null, + update_time: wave.update_time || null, + order_count: orders.length, + orders, + }; + } + /** * 构建车号命中语义化视图。 * @param {Object} cartMatchContext 车号命中上下文。 @@ -698,6 +1732,32 @@ class RecheckOrderService extends OrderBaseService { }; } + /** + * 将车号匹配视图中的订单平铺为一维数组。 + * 根据 view_type 从 groups / pick_groups / box_groups / orders 中提取所有订单。 + * @param {Object} cartMatchView 车号匹配视图。 + * @return {Array} 平铺后的订单列表。 + */ + flattenCartMatchOrders(cartMatchView = {}) { + const view = this.isPlainObject(cartMatchView) ? cartMatchView : {}; + const { view_type: viewType } = view; + + if (viewType === 'groups') { + const groups = Array.isArray(view.groups) ? view.groups : []; + return groups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'pick_groups') { + const pickGroups = Array.isArray(view.pick_groups) ? view.pick_groups : []; + return pickGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + if (viewType === 'box_groups') { + const boxGroups = Array.isArray(view.box_groups) ? view.box_groups : []; + return boxGroups.flatMap(g => (Array.isArray(g.orders) ? g.orders : [])); + } + // view_type === 'orders' 或兜底 + return Array.isArray(view.orders) ? view.orders : []; + } + /** * 追加任务订单行的订单维度字段。 * @param {Array} taskOrders 任务订单行。 @@ -827,14 +1887,426 @@ class RecheckOrderService extends OrderBaseService { } /** - * 校验订单是否允许复核,仅未拣货订单可执行复核。 + * 校验订单是否允许复核,未拣货订单不允许复核。 * @param {Object} order 订单信息。 */ assertOrderCanRecheck(order = {}) { - if (String(order.pick_status || '') !== 'none') { + if (String(order.pick_status || '') === 'none') { throw new Error('订单未拣货,不允许复核。'); } } + + /** + * 复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。 + * - 散单模式(single):返回待复核订单列表,每项为一个订单。 + * - 团购模式(group):返回波次维度的复核列表,每项为一个波次及其订单汇总。 + * 统一使用 list 字段名输出。 + * @param {Object} data 请求参数。 + * @param {string} [data.list_type='single'] 列表模式:single(散单模式)/ group(团购模式)。 + * @param {Object} [data.where] 筛选条件。 + * @param {Object} [data.pagination] 分页参数,兼容 page/pageSize。 + * @return {Promise} 列表结果,包含 list 与 pagination。 + */ + async recheckOrderList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { list_type: listType = 'single' } = requestData; + const normalizedListType = String(listType || 'single').trim(); + + if (normalizedListType === 'group') { + return await this.queryRecheckOrderGroupList(requestData); + } + return await this.queryRecheckOrderSingleList(requestData); + } + + /** + * 散单模式复核列表:按订单维度返回待复核订单,支持分页与关键词/波次号/复核状态筛选。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 keyword / wave_no / recheck_status / pick_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderSingleList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('o.warehouse_id = :warehouseId'); + conditions.push('o.pick_status != \'none\''); + conditions.push('o.recheck_status != \'fin\''); + + // 关键词搜索:运单号 / 订单号 + const keyword = String(where.keyword || '').trim(); + if (keyword) { + conditions.push(`( + o.delivery_order_code LIKE :keyword + OR o.pre_delivery_order_code LIKE :keyword + OR EXISTS ( + SELECT 1 FROM order_express oe + WHERE oe.order_id = o.id + AND oe.waybill_code LIKE :keyword + AND oe.delete_at IS NULL + ) + )`); + replacements.keyword = `%${keyword}%`; + } + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('o.wave_no = :waveNo'); + replacements.waveNo = waveNo; + } + + // 复核状态筛选 + const recheckStatus = String(where.recheck_status || '').trim(); + if (recheckStatus) { + conditions.push('o.recheck_status = :recheckStatus'); + replacements.recheckStatus = recheckStatus; + } + + // 拣货状态筛选 + const pickStatus = String(where.pick_status || '').trim(); + if (pickStatus) { + conditions.push('o.pick_status = :pickStatus'); + replacements.pickStatus = pickStatus; + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const listSql = ` + SELECT + o.id AS order_id, + o.delivery_order_code, + o.pre_delivery_order_code, + o.order_type, + o.wave_id, + o.wave_no, + o.pick_status, + o.recheck_status, + o.shop_nick, + o.logistics_name, + o.items_count, + o.items_total, + o.status, + o.create_at, + o.pick_time, + o.recheck_time + FROM ${orderTableName} o + ${whereClause} + ORDER BY o.id ASC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM ${orderTableName} o + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ + order_id: Number(row?.order_id || 0), + delivery_order_code: String(row?.delivery_order_code || row?.pre_delivery_order_code || '').trim(), + order_type: String(row?.order_type || '').trim(), + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + pick_status: String(row?.pick_status || '').trim(), + recheck_status: String(row?.recheck_status || '').trim(), + shop_nick: String(row?.shop_nick || '').trim(), + logistics_name: String(row?.logistics_name || '').trim(), + items_count: Number(row?.items_count || 0), + items_total: Number(row?.items_total || 0), + status: Number(row?.status || 0), + create_at: row?.create_at || null, + pick_time: row?.pick_time || null, + recheck_time: row?.recheck_time || null, + })); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 团购模式复核列表:按波次维度返回复核汇总,每项包含波次信息及订单复核统计。 + * @param {Object} data 请求参数。 + * @param {Object} [data.where] 筛选条件,支持 wave_no / wave_type / wave_status 等。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} { list: Array, pagination: Object }。 + */ + async queryRecheckOrderGroupList(data = {}) { + const { ctx } = this; + const warehouseId = this.getWarehouseId(); + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizePagination(requestData.pagination || requestData); + const where = this.isPlainObject(requestData.where) ? requestData.where : {}; + const offset = (page - 1) * pageSize; + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderTableName = this.resolveModelTableName(orderModel); + + const conditions = []; + const replacements = { warehouseId, limit: pageSize, offset }; + + conditions.push('wb.warehouse_id = :warehouseId'); + + // 波次号筛选 + const waveNo = String(where.wave_no || '').trim(); + if (waveNo) { + conditions.push('wb.wave_no LIKE :waveNo'); + replacements.waveNo = `%${waveNo}%`; + } + + // 波次类型筛选 + const waveType = Number(where.wave_type); + if (Number.isInteger(waveType) && waveType > 0) { + conditions.push('wb.wave_type = :waveType'); + replacements.waveType = waveType; + } + + // 波次状态筛选 + const waveStatus = Number(where.wave_status); + if (Number.isInteger(waveStatus)) { + conditions.push('wb.wave_status = :waveStatus'); + replacements.waveStatus = waveStatus; + } + + const whereClause = conditions.length > 0 + ? `WHERE ${conditions.join('\n AND ')}` + : ''; + + const listSql = ` + SELECT + wb.wave_id, + wb.wave_no, + wb.wave_type, + wb.wave_status, + wb.total_orders, + wb.processed_orders, + wb.creator, + wb.create_time, + wb.update_time, + COUNT(o.id) AS order_count, + SUM(CASE WHEN o.recheck_status = 'fin' THEN 1 ELSE 0 END) AS reviewed_count, + SUM(CASE WHEN o.recheck_status != 'fin' OR o.recheck_status IS NULL THEN 1 ELSE 0 END) AS unreviewed_count + FROM wms_wave_batch wb + LEFT JOIN ${orderTableName} o + ON o.wave_no = wb.wave_no + AND o.warehouse_id = wb.warehouse_id + AND o.pick_status != 'none' + ${whereClause} + GROUP BY wb.wave_id, wb.wave_no, wb.wave_type, wb.wave_status, + wb.total_orders, wb.processed_orders, wb.creator, + wb.create_time, wb.update_time + ORDER BY wb.create_time DESC, wb.wave_id DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_batch wb + ${whereClause} + `; + + const [ listRows, countRows ] = await Promise.all([ + ctx.model.query(listSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(countSql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0]?.total : 0) + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = (Array.isArray(listRows) ? listRows : []).map(row => { + const orderCount = Number(row?.order_count || 0); + const reviewedCount = Number(row?.reviewed_count || 0); + const unreviewedCount = Number(row?.unreviewed_count || 0); + + return { + wave_id: Number(row?.wave_id || 0), + wave_no: String(row?.wave_no || '').trim(), + wave_type: Number(row?.wave_type || 0), + wave_status: Number(row?.wave_status || 0), + total_orders: Number(row?.total_orders || 0), + processed_orders: Number(row?.processed_orders || 0), + creator: String(row?.creator || '').trim(), + create_time: row?.create_time || null, + update_time: row?.update_time || null, + order_count: orderCount, + reviewed_count: reviewedCount, + unreviewed_count: unreviewedCount, + review_assignment_status: orderCount === 0 || reviewedCount === 0 + ? 'unreviewed' + : reviewedCount >= orderCount + ? 'reviewed' + : 'partially_reviewed', + }; + }); + + return this.success('ok', { + list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 从 Sequelize 模型解析 SQL 表名并安全转义。 + * @param {Object} model Sequelize 模型对象。 + * @return {string} 可直接拼接到 SQL 的表名(已做反引号转义)。 + */ + resolveModelTableName(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('.'); + } + + /** + * 确认仓库拦截:通过订单ID直接匹配订单,将其拦截状态更新为"仓库拦截成功"。 + * 仅拦截当前指定订单(不波及波次内其他订单)。 + * @param {Object} data 请求体。 + * @param {number} data.order_id 订单ID。 + * @return {Promise} 拦截确认结果,包含 order_id、intercept_status 与更新时间。 + */ + async confirmIntercept(data = {}) { + const { ctx } = this; + const { order_id } = data; + const warehouseId = this.getWarehouseId(); + const orderId = Number(order_id); + + if (!orderId || !Number.isFinite(orderId) || orderId <= 0) { + throw new Error('order_id 无效'); + } + + const orderModel = await this.getOrderModelByTableType('current', warehouseId); + const orderWhere = this.buildOrderWhere([ orderId ], warehouseId); + const order = await orderModel.findOne({ + where: orderWhere, + attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status', 'wave_no' ], + raw: true, + }); + + if (!order) { + throw new Error('未找到对应订单'); + } + + const now = new Date(); + const updateValues = { + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }; + const updateResult = await orderModel.update(updateValues, { + where: orderWhere, + }); + const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0); + + if (affectedRows <= 0) { + throw new Error('拦截状态更新失败,请稍后重试'); + } + + const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim(); + + // 写入操作日志(失败不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'order', + businessId: logWarehouseId, + operationCode: 'ORDER_INTERCEPT_CONFIRM', + operator, + extras: { + warehouseId: logWarehouseId, + orderId, + orderNo, + previousInterceptStatus: String(order.intercept_status || '').trim(), + newInterceptStatus: 'intercepted_at_warehouse', + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn( + `[recheckOrder.confirmIntercept] 写入操作日志失败,不影响业务, orderId=${orderId}, error=${logErr.message}` + ); + } + + return { + order_id: orderId, + order_no: orderNo, + intercept_status: 'intercepted_at_warehouse', + updated_at: now, + }; + } + } module.exports = RecheckOrderService; diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 7b0864a..476890d 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -836,6 +836,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2133,6 +2135,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2363,6 +2367,8 @@ class WaveService extends OrderBaseService { step: { [Op.in]: [ 1, 2, 3 ] }, status: { [Op.ne]: 'cancel' }, outbound_status: { [Op.ne]: 'padding' }, + intercept_status: 'none', + lock_status: 'none', wave_id: 0, }; @@ -2741,7 +2747,8 @@ class WaveService extends OrderBaseService { o.status, o.outbound_status, o.post_status, - o.storage_status + o.storage_status, + o.print_status FROM wms_order_wave_strategy_match m INNER JOIN ${orderTableName} o ON o.id = m.order_id @@ -2750,8 +2757,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' WHERE m.warehouse_id = :warehouseId AND m.strategy_id = :strategyId ORDER BY o.id ASC @@ -2967,8 +2977,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' INNER JOIN ( SELECT COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, @@ -2979,8 +2992,11 @@ class WaveService extends OrderBaseService { AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' + AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' + AND src.intercept_status = 'none' + AND src.lock_status = 'none' GROUP BY COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) ) same_structure ON same_structure.structure_key = COALESCE(NULLIF(TRIM(COALESCE(o.items_hash, '')), ''), TRIM(COALESCE(o.items, ''))) @@ -3915,35 +3931,94 @@ class WaveService extends OrderBaseService { province: normalizedOrderRow.province ?? null, sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, item_snapshot: String(itemSnapshot || ''), + excluded_reason: normalizedOrderRow.lock_status !== 'none' + ? 'locked' + : normalizedOrderRow.intercept_status !== 'none' + ? 'intercepted' + : normalizedOrderRow.print_status === 'fin' + ? 'printed' + : 'no_match', }; } /** - * 查询兜底不符合波次策略的订单列表。 + * 查询兜底不符合波次策略的订单列表(含已完全打印被排除的订单)。 * - * 直接复用订单通用列表能力,返回标准 list/pagination 结构。 + * 查询条件:step != 0 且 wave_id = 0,且满足以下任一条件: + * - wave_scan_result = 2(未匹配任何波次策略) + * - print_status = 'fin'(已完全打印,被策略抓取阶段排除) * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 * * @param {Object} data 请求参数。 * @param {Object} data.pagination 分页参数。 * @param {Object} data.where 查询条件。 * @param {Object} data.sort 排序参数。 - * @return {Promise} 列表查询结果。 + * @return {Promise} 列表查询结果,每行含 excluded_reason 标记。 */ async waveStrategyFallbackOrderList(data = {}) { const requestData = this.isPlainObject(data) ? data : {}; const { pagination, where, sort } = requestData; const normalizedPagination = this.normalizePagination(pagination || {}); + const { page, pageSize } = normalizedPagination; const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); - const listResult = await this.listByModule('waveStrategyFallbackOrder', { - ...requestData, - pagination: normalizedPagination, - where: normalizedWhere, - sort, + const contextWarehouseId = this.getWarehouseId(); + + // 构建基础 WHERE(复用框架 where 解析、快递号虚拟筛选等能力) + const { where: ctxWhere } = this.prepareWhereContext( + { ...requestData, where: normalizedWhere }, + { specialFieldMap: { quickWhere: { bucket: 'quick' } } } + ); + const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere); + const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder'); + const mergedWhere = this.mergeWhereObjects(defaultWhere, sanitizedWhere); + let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, { + specialFieldMap: { quickWhere: { bucket: 'quick' } }, }); - const normalizedResult = this.isPlainObject(listResult) ? listResult : {}; - const sourceList = Array.isArray(normalizedResult.list) ? normalizedResult.list : []; - const orderIds = sourceList + + // 处理快递号虚拟筛选 + if (expressNumbers.length > 0) { + const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId); + queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds); + } + + // 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin') + const { Sequelize } = this.app; + queryWhere = { + [Sequelize.Op.and]: [ + queryWhere, + { + [Sequelize.Op.or]: [ + { wave_scan_result: 2 }, + { print_status: 'fin' }, + { lock_status: { [Sequelize.Op.ne]: 'none' } }, + { intercept_status: { [Sequelize.Op.ne]: 'none' } }, + ], + }, + ], + }; + + // 获取模型并分页查询 + const model = await this.getOrderModel('waveStrategyFallbackOrder', contextWarehouseId); + const order = this.buildListOrder(sort, 'waveStrategyFallbackOrder'); + const offset = (page - 1) * pageSize; + + const [ total, sourceList ] = await Promise.all([ + model.count({ where: queryWhere }), + model.findAll({ + where: queryWhere, + limit: pageSize, + offset, + order, + raw: true, + }), + ]); + + const normalizedList = await this.attachOrderExpressNumbers( + sourceList.map(item => this.normalizeOrderListItem(item)) + ); + + // 回填 item_snapshot + const orderIds = normalizedList .map(item => Number(item && item.id || 0)) .filter(id => Number.isInteger(id) && id > 0); const warehouseId = Number(this.getWarehouseId() || 0); @@ -3992,14 +4067,23 @@ class WaveService extends OrderBaseService { } } - const list = sourceList.map(item => { + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + const list = normalizedList.map(item => { const orderId = Number(item && item.id || 0); return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); }); return this.success('ok', { - ...normalizedResult, list, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, }); } @@ -5149,6 +5233,9 @@ class WaveService extends OrderBaseService { warehouse_id: warehouseId, step: { [Op.ne]: 0 }, wave_id: 0, + intercept_status: 'none', + lock_status: 'none', + print_status: { [Op.ne]: 'fin' }, [Op.or]: [ { wave_strategy_version: { [Op.ne]: strategyVersion } }, { wave_strategy_version: { [Op.is]: null } }, @@ -9643,8 +9730,11 @@ class WaveService extends OrderBaseService { AND o.step != 0 AND o.post_status = 'fin' AND o.storage_status = 'fin' + AND o.print_status != 'fin' AND o.status != 'cancel' AND o.outbound_status != 'padding' + AND o.intercept_status = 'none' + AND o.lock_status = 'none' INNER JOIN ( SELECT ${structureExpr('src')} AS structure_key${requireSameExpress ? `, ${expressExpr('src')} AS express_key` : ''}, @@ -9655,8 +9745,11 @@ class WaveService extends OrderBaseService { AND src.step != 0 AND src.post_status = 'fin' AND src.storage_status = 'fin' + AND src.print_status != 'fin' AND src.status != 'cancel' AND src.outbound_status != 'padding' + AND src.intercept_status = 'none' + AND src.lock_status = 'none' GROUP BY ${structureExpr('src')}${groupKeyExtra} ) same_structure ON same_structure.structure_key = ${structureExpr('o')}${joinKeyExtra} diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index ecbdee7..29c696a 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; const fs = require('node:fs'); const path = require('node:path'); @@ -621,6 +621,176 @@ class OrderPrintSystemService extends OrderBaseService { }; } + /** + * 按订单ID拉取平台打印中间态数据。 + * + * 与 getWavePlatformPrintData 输出完全相同的结构,但入参由波次ID改为订单ID。 + * 跳过了波次查询步骤,直接从订单ID入手,其余打印数据组装、锁定/未锁定分离、 + * 波次平台分组等逻辑与 getWavePlatformPrintData 保持一致。 + * 仓库ID统一从当前上下文获取,不再接受调用方传入。 + * + * @param {Object} params 请求参数。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise} 平台打印中间态结果。 + */ + async getOrderPrintData(params = {}) { + const requestParams = this.isPlainObject(params) ? params : {}; + const { + orderIds, + } = requestParams; + + const normalizedOrderIds = this.normalizeOrderIds(orderIds); + if (normalizedOrderIds.length === 0) { + throw new Error('order_ids 必填,且必须为非空数组'); + } + + const normalizedWarehouseId = this.getContextWarehouseId(); + const orderRows = await this.queryOrdersByIds(normalizedOrderIds, normalizedWarehouseId); + if (orderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + }, + waveGroups: [], + wave_ids: [], + ext: { + missing_order_ids: normalizedOrderIds, + filtered_order_ids: [], + }, + }; + } + + const hitOrderIdSet = new Set(orderRows.map(row => Number(row.id))); + const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId)); + + // 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查) + const validOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin'); + const filteredOrderIds = orderRows + .filter(row => String(row && row.post_status || '').trim() !== 'fin') + .map(row => ({ + order_id: Number(row && row.id || 0), + reason: '快递未完全分配', + })); + + if (validOrderRows.length === 0) { + return { + summary: { + total_waves: 0, + total_orders: 0, + total_platforms: 0, + }, + waveGroups: [], + wave_ids: [], + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + + const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds); + + const orderIdsForExpress = validOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress); + this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows); + const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows( + validOrderRows, + orderExpressRows, + normalizedWarehouseId + ); + const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows( + validOrderRows, + cainiaoEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows( + validOrderRows, + jdEnrichedOrderExpressRows, + normalizedWarehouseId + ); + const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows); + const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIdsForExpress, + normalizedWarehouseId, + validOrderWaveIds + ); + const waveIdsForCount = validOrderWaveIds; + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); + const templateSampleCache = new Map(); + const orderPrintList = []; + + for (const orderRow of validOrderRows) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + const orderExpress = orderExpressMap.get(orderId) || {}; + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + }; + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); + const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); + + orderPrintList.push(this.buildOrderPlatformPrintItem({ + orderRow: effectiveOrderRowWithWaveIndex, + orderExpress, + policyConfig, + platformCode, + templateSample, + })); + } + + const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ + waveRows, + hitWaveIds: validOrderWaveIds, + orderPrintList, + }); + const totalPlatforms = waveGroups.reduce((sum, waveGroup) => { + return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0); + }, 0); + + return { + summary: { + total_waves: waveGroups.length, + total_orders: orderPrintList.length, + total_platforms: totalPlatforms, + }, + waveGroups, + wave_ids: validOrderWaveIds, + ext: { + missing_order_ids: missingOrderIds, + filtered_order_ids: filteredOrderIds, + }, + }; + } + /** * 规范化“按分组解锁”规则。 * @@ -988,6 +1158,46 @@ class OrderPrintSystemService extends OrderBaseService { return Array.from(normalizedSet); } + /** + * 规范化订单ID数组。 + * + * 去重、过滤非法值(非正整数),返回纯数字数组。 + * + * @param {Array} orderIds 订单ID数组。 + * @return {Array} 规范化后的订单ID数组。 + */ + normalizeOrderIds(orderIds = []) { + if (!Array.isArray(orderIds)) { + return []; + } + + const normalizedSet = new Set(); + + for (const rawId of orderIds) { + const normalizedId = Number(String(rawId ?? '').trim()); + if (Number.isInteger(normalizedId) && normalizedId > 0) { + normalizedSet.add(normalizedId); + } + } + + return Array.from(normalizedSet); + } + + /** + * 从当前上下文获取仓库ID。 + * + * 用于不再接受调用方传入 warehouseId 的场景,直接从登录态/上下文读取。 + * + * @return {number} 当前上下文中的仓库ID。 + */ + getContextWarehouseId() { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('缺少当前用户仓库上下文 store_id'); + } + return contextWarehouseId; + } + /** * 解析并校验仓库ID。 * @@ -1107,6 +1317,72 @@ class OrderPrintSystemService extends OrderBaseService { return Array.isArray(rows) ? rows : []; } + /** + * 按订单ID批量查询订单明细。 + * + * 与 queryOrdersByWaveIds 返回相同的字段结构,但按订单 ID 列表直接查询。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单明细列表。 + */ + async queryOrdersByIds(orderIds = [], warehouseId) { + if (!Array.isArray(orderIds) || orderIds.length === 0) { + return []; + } + + const orderModel = await this.getOrderModel('order', warehouseId); + const rows = await orderModel.findAll({ + attributes: [ + 'id', + 'delivery_order_code', + 'source_order_codes', + 'warehouse_id', + 'store_id', + 'wave_id', + 'wave_no', + 'name', + 'tel', + 'mobile', + 'province', + 'city', + 'area', + 'town', + 'detail_address', + 'zip_code', + 'items', + 'source_platform_code', + 'sys_platform_code', + 'sys_platform_name', + 'logistics_code', + 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', + 'post_status', + 'status', + 'outbound_status', + 'print_status', + 'lock_status', + 'print_lock_status', + 'items_count', + 'items_total', + 'items_weight', + 'freight', + 'create_at', + 'pay_time', + ], + where: { + id: { + [Op.in]: orderIds, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + return Array.isArray(rows) ? rows : []; + } + /** * 按订单ID批量查询快递单信息。 * diff --git a/methods/changes/system.json b/methods/changes/system.json index 72a7834..004ed34 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -2988,5 +2988,160 @@ ], "type": "updated", "module": "order.wave" + }, + { + "version": "2026.06.08-system-01", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块 scanOrder 返回值重构为统一 list 输出,新增 confirmIntercept 与 recheckOrderList 接口", + "methods": [ + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "scanOrder 返回值重构:统一使用 list 字段输出,新增 list_type 字段区分散单/团购模式。散单模式顶层新增 picker_id、picker_name、wave_id、wave_no、wave_type、pick_mode、strategy_id、strategy_name、total_orders、reviewed_count、unreviewed_count 等汇总字段。list 中每项新增 waybill_no、is_printed、is_reviewed、wave_index、intercept_status、store_remark、stock[](含 stock_id、item_code、item_name、sku_property、packing_requirements、barcodes[]、images[]、plan_qty、has_shared_barcode)。移除旧字段 logs、order、order_id(顶层)、waybill_no(顶层旧位置)、wave_match_view、items、expresses、cart_match_view。", + "scanOrder 入参新增 wave_no / waveNo 支持波次号直接扫描匹配。", + "新增 order.recheckOrder.confirmIntercept:确认拦截接口,将订单 intercept_status 更新为 intercepted_at_warehouse,返回 order_id、order_no、intercept_status、updated_at。", + "新增 order.recheckOrder.recheckOrderList:复核订单列表查询,支持 list_type=single(散单)与 list_type=group(团购),均返回统一 list + pagination 结构。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-02", + "date": "2026-06-08", + "summary": "order.recheckOrder 模块新增 batchIntercept/batchInterceptTaskProgress,更新 scanOrder 团购模式响应结构,完善 confirmIntercept/recheckOrderList 文档", + "methods": [ + "order.recheckOrder.batchIntercept", + "order.recheckOrder.batchInterceptTaskProgress", + "order.recheckOrder.scanOrder", + "order.recheckOrder.confirmIntercept", + "order.recheckOrder.recheckOrderList" + ], + "notes": [ + "新增 order.recheckOrder.batchIntercept:批量提交订单拦截(异步任务模式),入参支持 order_ids/orderIds/ids(订单ID数组,不再使用 wave_ids),将 intercept_status 设为 'requested',返回 task_id/warehouse_id/message/accepted_at。支持幂等提交与 warehouse_id 校验。", + "新增 order.recheckOrder.batchInterceptTaskProgress:按 task_id 查询批量拦截任务进度,返回 state(submitted/running/success/failed/not_found)及对应的进度/计数/结果/错误字段。", + "更新 order.recheckOrder.scanOrder 响应文档:团购模式(cart 命中)list 项新增 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[] 等波次级别字段;补充散单无波次信息时的回退详情模式说明(detail/items/expresses/logs)。", + "完善 order.recheckOrder.confirmIntercept:补充操作日志写入说明(ORDER_INTERCEPT_CONFIRM)及失败不影响主流程的容错描述。", + "完善 order.recheckOrder.recheckOrderList:补充散单模式默认排除 pick_status='none' 和 recheck_status='fin' 的说明;团购模式 where 支持 wave_no(模糊搜索)的说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-03", + "date": "2026-06-08", + "summary": "移除 order.recheckOrder.batchIntercept 的 warehouse_id/warehouseId 入参,仓库ID统一使用当前上下文", + "methods": [ + "order.recheckOrder.batchIntercept" + ], + "notes": [ + "移除入参 warehouse_id / warehouseId:仓库ID统一从当前上下文(ctx.user.store_id)获取,不再由调用方传入。", + "移除对应错误码:warehouse_id 参数不合法(400)、warehouse_id 与当前仓库上下文不一致(400)。", + "description 中补充说明仓库ID来源为当前上下文。", + "response 中 warehouse_id 字段描述改为「取自当前上下文」。" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-10", + "date": "2026-06-08", + "summary": "batchIntercept / batchInterceptTaskProgress 从 order.recheckOrder 迁移至 order.pendingOrder", + "methods": [ + "order.pendingOrder.batchIntercept", + "order.pendingOrder.batchInterceptTaskProgress" + ], + "notes": [ + "method 从 order.recheckOrder.batchIntercept 重命名为 order.pendingOrder.batchIntercept,分组从订单复核模块迁移至订单待处理模块", + "method 从 order.recheckOrder.batchInterceptTaskProgress 重命名为 order.pendingOrder.batchInterceptTaskProgress,分组从订单复核模块迁移至订单待处理模块", + "接口入参、响应、错误码均保持不变,仅变更 method 名称与所属分组" + ], + "type": "updated" + }, + { + "version": "2026.06.08-system-04", + "date": "2026-06-08", + "summary": "新增 order.print.getOrderPrintData:按订单ID拉取打印数据,返回结构与 getWavePlatformPrintData 一致,不限制锁定状态", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "新增 order.print.getOrderPrintData 接口文档,入参为 warehouse_id + order_ids(非空数组),返回与 getWavePlatformPrintData 结构一致的 waveGroups / summary / wave_ids / ext", + "与 getWavePlatformPrintData 的区别:入参为 order_ids(非 wave_ids),ext 中返回 missing_order_ids / filtered_order_ids(非 missing_wave_ids / filtered_wave_ids)", + "不限制打印锁定状态,所有订单(无论是否被锁定)统一返回打印数据", + "自动过滤 post_status !== 'fin' 的订单(快递未完全分配),被过滤订单出现在 ext.filtered_order_ids" + ], + "type": "added", + "module": "order.print" + }, + { + "version": "2026.06.08-system-11", + "date": "2026-06-08", + "summary": "新增 order.pendingOrder 批量锁定/解锁/解除拦截及对应进度查询共 6 个异步任务接口文档", + "methods": [ + "order.pendingOrder.batchLock", + "order.pendingOrder.batchLockTaskProgress", + "order.pendingOrder.batchUnlock", + "order.pendingOrder.batchUnlockTaskProgress", + "order.pendingOrder.batchUnintercept", + "order.pendingOrder.batchUninterceptTaskProgress" + ], + "notes": [ + "新增 batchLock:批量锁定订单,lock_status → 'warehouse',操作日志 ORDER_LOCK,task_id 格式 order_lock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchLockTaskProgress:查询批量锁定进度,返回 locked_order_count / locked_order_ids 等。", + "新增 batchUnlock:批量解锁订单,lock_status → 'none',操作日志 ORDER_UNLOCK,task_id 格式 order_unlock_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUnlockTaskProgress:查询批量解锁进度,返回 unlocked_order_count / unlocked_order_ids 等。", + "新增 batchUnintercept:批量解除拦截订单,intercept_status → 'none',操作日志 ORDER_INTERCEPT_CANCEL,task_id 格式 order_unintercept_{warehouseId}_{timestamp}_{rand}。", + "新增 batchUninterceptTaskProgress:查询批量解除拦截进度,返回 unintercepted_order_count / unintercepted_order_ids 等。", + "以上 6 个接口均采用与已有 batchIntercept/batchInterceptTaskProgress 一致的异步任务模式:提交返回 task_id,进度查询返回 state + 进度字段。", + "仅同步文档,不修改业务代码或实现。" + ], + "type": "added", + "module": "order" + }, + { + "version": "2026.06.08-system-12", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除锁定限制,所有订单统一返回打印数据,不再区分锁定/未锁定", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除打印锁定限制:所有订单(包括已锁定)统一返回打印数据,不再区分锁定/未锁定状态", + "移除 locked_count、locked_orders、locked_wave_groups 等锁定相关字段", + "返回结构与 getWavePlatformPrintData 完全一致:summary / waveGroups / wave_ids / ext", + "ext 中使用 missing_order_ids / filtered_order_ids(替代锁定相关字段),与代码实现完全对齐" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-13", + "date": "2026-06-08", + "summary": "更新 order.print.getOrderPrintData:移除 warehouse_id 入参,仓库ID统一从当前上下文获取", + "methods": [ + "order.print.getOrderPrintData" + ], + "notes": [ + "移除 warehouse_id / warehouseId 入参,仓库ID统一从 this.getContextWarehouseId() 获取", + "同步移除 errors 中 warehouse_id 必填 相关错误码", + "description 补充说明仓库ID从上下文获取,无需调用方传入", + "params 仅保留 order_ids(非空数组),与代码 method 层 getOrderPrintData(data) 解构一致" + ], + "type": "updated", + "module": "order.print" + }, + { + "version": "2026.06.08-system-14", + "date": "2026-06-08", + "summary": "新增 order.recheckOrder.scanTask 接口文档,并为 scanOrder 响应补充 task_id 字段", + "methods": [ + "order.recheckOrder.scanTask", + "order.recheckOrder.scanOrder" + ], + "notes": [ + "新增 order.recheckOrder.scanTask:按拣货任务 ID 拉取复核数据,数据结构与 scanOrder 完全一致,用于前端刷新。入参为 task_id(必填,number),返回 match_type='task',散单模式(pick_mode 2/3/4)返回扁平订单列表,团购模式(pick_mode 1/5)返回分组波次列表。", + "更新 order.recheckOrder.scanOrder 响应定义:补充 task_id 字段说明(散单有波次时由 buildSingleWaveScanView 返回,团单车号命中时由 cartMatchContext 返回)。", + "仅同步文档,不修改任何业务代码或实现。" + ], + "type": "updated" } ] diff --git a/methods/system.json b/methods/system.json index 0dd92b8..3e5da59 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.5", - "updatedAt": "2026-06-07", + "version": "0.3.19", + "updatedAt": "2026-06-08", "headers": [ { "name": "platform", @@ -3964,16 +3964,10 @@ "message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则更新行数为 0,不会报错但实际无更新" } ] - } - ] - }, - { - "groupName": "订单复核模块", - "module": "order.recheckOrder", - "list": [ + }, { - "method": "order.recheckOrder.scanOrder", - "description": "扫码查询订单(支持运单号与车号)并返回订单详情。车号命中时按 pick_mode 返回语义化结构。", + "method": "order.pendingOrder.batchIntercept", + "description": "批量提交订单拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'requested' 并写入操作日志(ORDER_INTERCEPT_REQUEST)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3986,11 +3980,789 @@ ], "params": [ { - "name": "keyword / value / waybill_no / waybillCode / waybill_code / cart_code / cartCode", + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 recheck_intercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量拦截任务已提交。' 或 '批量拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchInterceptTaskProgress", + "description": "查询批量拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", "type": "string", "required": true, "source": "body|query", - "description": "扫描关键词;优先按运单号匹配,未命中时回退到 wms_wave_pick_task.current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot 车号匹配,支持别名 waybillCode/waybill_code/cart_code/cartCode" + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "intercepted_order_count", + "type": "number", + "required": false, + "description": "已拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "intercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_INTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchLock", + "description": "批量提交订单锁定请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'warehouse' 并写入操作日志(ORDER_LOCK)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_lock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量锁定任务已提交。' 或 '批量锁定任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchLockTaskProgress", + "description": "查询批量锁定任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已锁定订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "locked_order_count", + "type": "number", + "required": false, + "description": "已锁定订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "locked_order_ids", + "type": "number[]", + "required": false, + "description": "已锁定订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_LOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlock", + "description": "批量提交订单解锁请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 lock_status 更新为 'none' 并写入操作日志(ORDER_UNLOCK)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unlock_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解锁任务已提交。' 或 '批量解锁任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUnlockTaskProgress", + "description": "查询批量解锁任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解锁订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unlocked_order_count", + "type": "number", + "required": false, + "description": "已解锁订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unlocked_order_ids", + "type": "number[]", + "required": false, + "description": "已解锁订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNLOCK_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + }, + { + "method": "order.pendingOrder.batchUnintercept", + "description": "批量提交解除拦截请求(异步任务模式)。接收订单ID数组,提交后立即返回 task_id 和受理信息,后端异步将每个订单的 intercept_status 更新为 'none' 并写入操作日志(ORDER_INTERCEPT_CANCEL)。相同 task_id 幂等提交会返回已存在任务的信息。仓库ID统一使用当前上下文(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids / orderIds / ids", + "type": "number[]", + "required": true, + "source": "body", + "description": "订单ID数组;优先级 order_ids > orderIds > ids" + }, + { + "name": "task_id / taskId", + "type": "string", + "required": false, + "source": "body", + "description": "外部指定任务ID(用于幂等提交,不传则自动生成)" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID,格式 order_unintercept_{warehouseId}_{timestamp}_{rand}(幂等提交时返回已有任务的 task_id)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(取自当前上下文)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务提交状态说明:'批量解除拦截任务已提交。' 或 '批量解除拦截任务已存在,请勿重复提交。'" + }, + { + "name": "accepted_at", + "type": "string", + "required": true, + "description": "任务受理时间(ISO 字符串)" + }, + { + "name": "status", + "type": "string", + "required": false, + "description": "提交状态(固定为 'success')" + }, + { + "name": "state", + "type": "string", + "required": false, + "description": "幂等提交时返回已有任务的状态:submitted / running / success / failed" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 400, + "message": "order_ids 参数不能为空或格式错误" + } + ] + }, + { + "method": "order.pendingOrder.batchUninterceptTaskProgress", + "description": "查询批量解除拦截任务进度。根据 task_id 返回任务的当前状态、进度百分比、已处理/已解除拦截订单数等信息。任务状态 state 包含 submitted(已提交)、running(执行中)、success(已完成)、failed(失败)、not_found(未找到)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id / taskId", + "type": "string", + "required": true, + "source": "body|query", + "description": "任务ID" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务ID" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:submitted / running / success / failed / not_found" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "仓库ID(not_found 时不返回)" + }, + { + "name": "submitted_at", + "type": "number|null", + "required": false, + "description": "任务提交时间戳(毫秒)" + }, + { + "name": "start_time", + "type": "number|null", + "required": false, + "description": "任务开始执行时间戳(毫秒,running/success/failed 时返回)" + }, + { + "name": "end_time", + "type": "number|null", + "required": false, + "description": "任务结束时间戳(毫秒,success/failed 时返回)" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比 0-100(submitted/running/success/failed 时返回)" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "总订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数(仅 submitted/running 时返回)" + }, + { + "name": "unintercepted_order_count", + "type": "number", + "required": false, + "description": "已解除拦截订单数(submitted/running/success/failed 时返回)" + }, + { + "name": "unintercepted_order_ids", + "type": "number[]", + "required": false, + "description": "已解除拦截订单ID列表(仅 success 时返回)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "任务耗时(毫秒,success/failed 时返回)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 failed 时返回)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 failed 时返回,默认 'BATCH_UNINTERCEPT_FAILED')" + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 参数不能为空" + } + ] + } + ] + }, + { + "groupName": "订单复核模块", + "module": "order.recheckOrder", + "list": [ + { + "method": "order.recheckOrder.scanOrder", + "description": "扫描关键词并返回以波次为单位的复核视图。支持运单号、波次号、车号三种匹配模式。运单号/波次号命中(散单)返回扁平化订单列表 list_type='single',车号命中(团单)返回嵌套波次结构 list_type='group'。运单号命中但订单无波次信息时,退回单订单详情模式(list 每项含 detail/items/expresses/logs)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "keyword / value / waybill_no / waybillCode / waybill_code / wave_no / waveNo / cart_code / cartCode", + "type": "string", + "required": true, + "source": "body|query", + "description": "扫描关键词;匹配优先级:运单号 → 波次号 → 车号。支持别名 waybillCode/waybill_code(运单号)、waveNo(波次号)、cartCode(车号)" } ], "response": [ @@ -3998,114 +4770,417 @@ "name": "match_type", "type": "string", "required": true, - "description": "命中类型:waybill(运单号命中)/ cart(车号命中)" + "description": "命中类型:waybill(运单号命中)/ wave(波次号命中)/ cart(车号命中)" }, { - "name": "cart_match_view", - "type": "object|null", - "required": true, - "description": "仅 cart 命中返回对象,waybill 命中返回 null" - }, - { - "name": "cart_match_view.mode_code", - "type": "number", - "required": false, - "description": "波次类型编码(pick_mode)" - }, - { - "name": "cart_match_view.mode_name", + "name": "list_type", "type": "string", - "required": false, - "description": "波次类型名称" - }, - { - "name": "cart_match_view.view_type", - "type": "string", - "required": false, - "description": "语义化视图类型:groups/orders/pick_groups/box_groups" - }, - { - "name": "cart_match_view.task", - "type": "object", - "required": false, - "description": "任务摘要信息" - }, - { - "name": "cart_match_view.groups", - "type": "array", - "required": false, - "description": "仅 mode_code=1/5 返回,按 wave 分组" - }, - { - "name": "cart_match_view.orders", - "type": "array", - "required": false, - "description": "仅 mode_code=2 返回,直接返回订单列表" - }, - { - "name": "cart_match_view.pick_groups", - "type": "array", - "required": false, - "description": "仅 mode_code=3 返回,按 pick_status 分组" - }, - { - "name": "cart_match_view.box_groups", - "type": "array", - "required": false, - "description": "仅 mode_code=4 返回,按 box_no 分组" - }, - { - "name": "order_id", - "type": "number", "required": true, - "description": "准确的订单 ID(供 confirmRecheck 使用)" + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表)" }, { "name": "waybill_no", "type": "string", - "required": true, - "description": "匹配到的运单号" + "required": false, + "description": "仅 waybill 命中时返回,匹配到的运单号" }, { - "name": "order", - "type": "object", - "required": true, - "description": "订单头对象" + "name": "task_id", + "type": "number|null", + "required": false, + "description": "散单有波次信息时返回(来自拣货任务表 wms_wave_pick_task.id),团单车号命中时返回 cartMatchContext 中的任务 ID" }, { - "name": "items", + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人ID(来自 wms_wave_pick_task.pick_user_id)" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,拣货人名称(来自 wms_wave_pick_task.pick_user_name)" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次号" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "仅散单模式(有波次信息时)返回,波次类型编码(来自 wms_wave_batch.wave_type)" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次。散单模式在顶层返回,团购模式在每个波次视图项内返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "仅散单模式返回,波次策略ID" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "仅散单模式返回,波次策略名称" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "仅散单模式返回,波次内订单总数" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,已复核订单数" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "仅散单模式返回,未复核订单数" + }, + { + "name": "list", "type": "array", "required": true, - "description": "订单商品明细" - }, - { - "name": "expresses", - "type": "array", - "required": true, - "description": "运单信息数组" - }, - { - "name": "logs", - "type": "array", - "required": true, - "description": "相关操作日志" + "description": "统一列表输出。散单模式(list_type=single)有波次信息时:扁平订单数组;无波次信息时退回单订单详情模式(每项含 detail、items、expresses、logs)。团购模式(list_type=group):波次视图数组(每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、pick_mode、box_no、orders[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单有波次] 订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单有波次] 发货单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单有波次] 运单号(从 order_express 关联表查询)" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单有波次] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单有波次] 是否已打印(print_status === 'fin')" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单有波次] 是否已复核(recheck_status === 'fin')" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单有波次] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单有波次] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单有波次] 波次内序号(优先从 wms_order_wave_index 读取真实 wave_index,若无则降级为数组临时序号)" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单有波次] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单有波次] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单有波次] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单有波次] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单有波次] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单有波次] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单有波次] 货主备注(来自 wms_store_warehouse.store_remask)" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单有波次] 拦截状态(requested / intercepted_at_warehouse / 空字符串)" + }, + { + "name": "stock", + "type": "array", + "description": "[散单有波次] 订单商品库存明细", + "children": [ + { + "name": "stock_id", + "type": "number", + "description": "库存商品ID" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU属性(来自 wms_stock_warehouse.sku_property)" + }, + { + "name": "packing_requirements", + "type": "string", + "description": "包装要求(来自 wms_stock_warehouse.packing_requirements)" + }, + { + "name": "barcodes", + "type": "array", + "description": "条码列表(来自 wms_stock_barcodes,若无则回退为 [item_code])" + }, + { + "name": "images", + "type": "array", + "description": "商品图片URL列表(来自 file_reference 关联查询)" + }, + { + "name": "plan_qty", + "type": "number", + "description": "计划数量" + }, + { + "name": "has_shared_barcode", + "type": "boolean", + "description": "是否存在共享条码(同一条码出现在多个不同 stock_id 中)" + } + ] + }, + { + "name": "detail", + "type": "object", + "description": "[散单无波次回退] 订单详情对象(来自 order.detail 方法返回)" + }, + { + "name": "items", + "type": "array", + "description": "[散单无波次回退] 订单商品明细数组" + }, + { + "name": "expresses", + "type": "array", + "description": "[散单无波次回退] 订单快递信息数组" + }, + { + "name": "logs", + "type": "array", + "description": "[散单无波次回退] 订单操作日志数组" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数(来自 wms_wave_batch)" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数(来自 wms_wave_batch)" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数(COUNT 查询)" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式(以拣货任务级别为准)" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号(来自 wms_wave_pick_task_wave.box_no)" + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单有波次模式订单项一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "复核状态" + }, + { + "name": "order_type", + "type": "string", + "description": "订单类型" + }, + { + "name": "status", + "type": "number", + "description": "订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "商品库存明细(结构同散单模式)" + } + ] + } + ] } ], "errors": [ { - "code": "400", - "message": "扫描关键词不能为空", - "description": "扫描关键词不能为空" + "code": 400, + "message": "扫描关键词不能为空" }, { - "code": "404", - "message": "未找到对应订单", - "description": "未找到对应订单" + "code": 404, + "message": "未找到对应订单" }, { - "code": "400", - "message": "订单未拣货,不允许复核。", - "description": "订单未拣货,不允许复核。" + "code": 400, + "message": "订单未拣货,不允许复核。" } ] }, @@ -4148,7 +5223,7 @@ "name": "recheck_status", "type": "string", "required": true, - "description": "复核结果状态" + "description": "复核结果状态(固定为 'fin')" }, { "name": "recheck_time", @@ -4165,19 +5240,416 @@ ], "errors": [ { - "code": "400", - "message": "订单ID不能为空", - "description": "订单ID不能为空" + "code": 400, + "message": "订单ID不能为空" }, { - "code": "404", - "message": "未找到对应订单", - "description": "未找到对应订单" + "code": 404, + "message": "未找到对应订单" }, { - "code": "400", - "message": "订单未拣货,不允许复核。", - "description": "订单未拣货,不允许复核。" + "code": 400, + "message": "订单未拣货,不允许复核。" + } + ] + }, + { + "method": "order.recheckOrder.confirmIntercept", + "description": "确认拦截:通过订单ID直接匹配订单,将其拦截状态更新为 intercepted_at_warehouse(仓库已拦截)。仅拦截当前指定订单,不波及波次内其他订单。操作成功后写入操作日志(ORDER_INTERCEPT_CONFIRM),日志写入失败不影响主流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "订单 ID" + } + ], + "response": [ + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单 ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(优先 delivery_order_code,其次 pre_delivery_order_code)" + }, + { + "name": "intercept_status", + "type": "string", + "required": true, + "description": "拦截状态(固定为 'intercepted_at_warehouse')" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "更新时间(ISO 字符串)" + } + ], + "errors": [ + { + "code": 400, + "message": "order_id 无效", + "description": "order_id 无效(为空或非正整数)" + }, + { + "code": 404, + "message": "未找到对应订单" + }, + { + "code": 500, + "message": "拦截状态更新失败,请稍后重试", + "description": "数据库更新影响行数为 0 时返回" + } + ] + }, + { + "method": "order.recheckOrder.recheckOrderList", + "description": "复核订单列表查询,通过入参 list_type 区分散单模式与团购模式。散单模式(single,默认)返回待复核订单列表(每项为一个订单,排除 pick_status='none' 和 recheck_status='fin'),团购模式(group)返回波次维度的复核汇总列表(每项为一个波次及其订单复核统计,含 review_assignment_status 计算字段)。统一使用 list 字段名输出,均支持分页与筛选。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "list_type", + "type": "string", + "required": false, + "source": "body", + "description": "列表模式:single(散单模式,默认)/ group(团购模式)" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件。散单模式支持 keyword(运单号/订单号模糊搜索)、wave_no(精确匹配)、recheck_status、pick_status;团购模式支持 wave_no(模糊搜索)、wave_type、wave_status" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize(默认 page=1, pageSize=20)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "散单模式(list_type=single):订单数组,每项含 order_id、delivery_order_code、order_type、wave_id、wave_no、pick_status、recheck_status、shop_nick、logistics_name、items_count、items_total、status、create_at、pick_time、recheck_time。团购模式(list_type=group):波次汇总数组,每项含 wave_id、wave_no、wave_type、wave_status、total_orders、processed_orders、creator、create_time、update_time、order_count、reviewed_count、unreviewed_count、review_assignment_status(unreviewed/partially_reviewed/reviewed)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息,含 page、pageSize、total、totalPages、hasPrevious、hasNext" + } + ], + "errors": [] + }, + { + "method": "order.recheckOrder.scanTask", + "description": "按拣货任务 ID 拉取复核扫描视图。根据任务的 pick_mode 区分散单/团单模式,返回与 scanOrder 一致的数据结构,用于前端刷新数据。散单模式(pick_mode 2/3/4)扁平化任务下所有波次的订单列表(按 order_id 去重,未复核优先、wave_index 升序),顶层携带拣货人/任务等汇总信息(包括 picker_id、picker_name、pick_mode、total_orders、reviewed_count、unreviewed_count);团购模式(pick_mode 1/5)返回任务下所有团购波次及订单的分组列表(list_type='group')。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "拣货任务 ID(对应 wms_wave_pick_task.id)" + } + ], + "response": [ + { + "name": "match_type", + "type": "string", + "required": true, + "description": "固定为 'task',表示通过任务 ID 匹配" + }, + { + "name": "list_type", + "type": "string", + "required": true, + "description": "列表模式:single(散单扁平列表)/ group(团购嵌套波次列表),由拣货任务的 pick_mode 决定" + }, + { + "name": "task_id", + "type": "number", + "required": true, + "description": "拣货任务 ID" + }, + { + "name": "picker_id", + "type": "number|null", + "required": false, + "description": "拣货人 ID(来自 wms_wave_pick_task.pick_user_id),散单模式返回" + }, + { + "name": "picker_name", + "type": "string", + "required": false, + "description": "拣货人名称(来自 wms_wave_pick_task.pick_user_name),散单模式返回" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "description": "拣货模式:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次" + }, + { + "name": "wave_id", + "type": "number", + "required": false, + "description": "散单模式固定为 0,团购模式不返回" + }, + { + "name": "wave_no", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串,团购模式不返回" + }, + { + "name": "wave_type", + "type": "number", + "required": false, + "description": "波次类型编码(取任务下第一个有效波次的 wave_type),散单模式返回" + }, + { + "name": "strategy_id", + "type": "number|null", + "required": false, + "description": "散单模式固定为 null(任务级别不绑定单一策略)" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "description": "散单模式固定为空字符串(任务级别不绑定单一策略)" + }, + { + "name": "total_orders", + "type": "number", + "required": false, + "description": "任务下订单总数(去重后),散单模式返回" + }, + { + "name": "reviewed_count", + "type": "number", + "required": false, + "description": "已复核订单数,散单模式返回" + }, + { + "name": "unreviewed_count", + "type": "number", + "required": false, + "description": "未复核订单数,散单模式返回" + }, + { + "name": "list", + "type": "array", + "required": true, + "description": "统一列表输出。散单模式(list_type=single):扁平订单数组(每项结构与 scanOrder 散单有波次模式一致,含 order_id/delivery_order_code/waybill_no/pick_status/is_printed/is_reviewed/shop_nick/items_count/wave_index/recheck_status/order_type/status/logistics_name/store_remark/intercept_status/stock[])。团购模式(list_type=group):波次视图数组(结构与 scanOrder 团购模式一致,每项含 wave_id/wave_no/wave_type/wave_status/total_orders/processed_orders/creator/create_time/update_time/order_count/pick_mode/box_no/orders[])", + "children": [ + { + "name": "order_id", + "type": "number", + "description": "[散单] 订单 ID" + }, + { + "name": "delivery_order_code", + "type": "string", + "description": "[散单] 发货单号" + }, + { + "name": "waybill_no", + "type": "string", + "description": "[散单] 运单号" + }, + { + "name": "pick_status", + "type": "string", + "description": "[散单] 拣货状态" + }, + { + "name": "is_printed", + "type": "boolean", + "description": "[散单] 是否已打印" + }, + { + "name": "is_reviewed", + "type": "boolean", + "description": "[散单] 是否已复核" + }, + { + "name": "shop_nick", + "type": "string", + "description": "[散单] 店铺昵称" + }, + { + "name": "items_count", + "type": "number", + "description": "[散单] 商品种类数" + }, + { + "name": "wave_index", + "type": "number", + "description": "[散单] 波次内序号" + }, + { + "name": "recheck_status", + "type": "string", + "description": "[散单] 复核状态" + }, + { + "name": "wave_id", + "type": "number", + "description": "[散单] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[散单] 波次号" + }, + { + "name": "order_type", + "type": "string", + "description": "[散单] 订单类型" + }, + { + "name": "status", + "type": "number", + "description": "[散单] 订单状态码" + }, + { + "name": "logistics_name", + "type": "string", + "description": "[散单] 物流名称" + }, + { + "name": "store_remark", + "type": "string", + "description": "[散单] 货主备注" + }, + { + "name": "intercept_status", + "type": "string", + "description": "[散单] 拦截状态" + }, + { + "name": "stock", + "type": "array", + "description": "[散单] 订单商品库存明细(含 stock_id/item_code/item_name/sku_property/packing_requirements/barcodes/images/plan_qty/has_shared_barcode)" + }, + { + "name": "wave_id", + "type": "number", + "description": "[团购波次项] 波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "[团购波次项] 波次号" + }, + { + "name": "wave_type", + "type": "number", + "description": "[团购波次项] 波次类型编码" + }, + { + "name": "wave_status", + "type": "number", + "description": "[团购波次项] 波次状态码" + }, + { + "name": "total_orders", + "type": "number", + "description": "[团购波次项] 波次内订单总数" + }, + { + "name": "processed_orders", + "type": "number", + "description": "[团购波次项] 已处理订单数" + }, + { + "name": "creator", + "type": "string", + "description": "[团购波次项] 波次创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "[团购波次项] 波次创建时间" + }, + { + "name": "update_time", + "type": "string", + "description": "[团购波次项] 波次更新时间" + }, + { + "name": "order_count", + "type": "number", + "description": "[团购波次项] 波次下实际订单数" + }, + { + "name": "pick_mode", + "type": "number", + "description": "[团购波次项] 拣货模式" + }, + { + "name": "box_no", + "type": "number", + "description": "[团购波次项] 箱号" + }, + { + "name": "orders", + "type": "array", + "description": "[团购波次项] 波次下订单列表(结构与散单模式订单项一致)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "task_id 无效", + "description": "task_id 为空或非正整数" + }, + { + "code": 404, + "message": "未找到对应拣货任务" } ] } @@ -8401,7 +9873,7 @@ ] }, { - "groupName": "订单打印模块", + "groupName": "打印模块", "module": "order.print", "list": [ { @@ -9132,6 +10604,227 @@ "description": "内部错误" } ] + }, + { + "method": "order.print.getOrderPrintData", + "description": "按订单ID拉取平台打印中间态数据,与 getWavePlatformPrintData 返回结构一致。不限制打印锁定状态,所有订单(包括已锁定)统一返回。仓库ID统一从当前上下文获取,无需调用方传入。自动过滤快递未完全分配的订单(post_status !== 'fin'),返回 waveGroups(波次 -> 平台 -> 订单)结构。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_ids", + "type": "array", + "required": true, + "source": "body", + "description": "订单ID列表(支持数字或字符串,内部自动去重与归一化,必须为非空数组)" + } + ], + "response": [ + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息", + "children": [ + { + "name": "total_waves", + "type": "number", + "required": true, + "description": "通过过滤的波次总数" + }, + { + "name": "total_orders", + "type": "number", + "required": true, + "description": "所有平台下订单总数" + }, + { + "name": "total_platforms", + "type": "number", + "required": true, + "description": "所有波次内平台分组总数(累加)" + } + ] + }, + { + "name": "wave_ids", + "type": "array", + "required": true, + "description": "通过过滤的波次ID数组" + }, + { + "name": "waveGroups", + "type": "array", + "required": true, + "description": "主返回结构:按波次分组(波次 -> 平台 -> 订单)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该波次下订单总数" + }, + { + "name": "platforms", + "type": "array", + "required": true, + "description": "按平台和系统快递分组后的订单列表", + "children": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "order_count", + "type": "number", + "required": true, + "description": "该平台+系统快递分组的订单数" + }, + { + "name": "sys_logistics_code", + "type": "string", + "required": true, + "description": "系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "required": true, + "description": "系统快递名称" + }, + { + "name": "orders", + "type": "array", + "required": true, + "description": "该分组内的订单列表(逐单中间态)", + "children": [ + { + "name": "wave_id", + "type": "number", + "required": true, + "description": "波次ID" + }, + { + "name": "wave_no", + "type": "string", + "required": true, + "description": "波次号" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "订单ID" + }, + { + "name": "order_no", + "type": "string", + "required": true, + "description": "订单号(delivery_order_code 或 source_order_codes)" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "description": "货主ID" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "platform", + "type": "string", + "required": true, + "description": "平台编码" + }, + { + "name": "platform_name", + "type": "string", + "required": true, + "description": "平台名称" + }, + { + "name": "waybill_code", + "type": "string", + "required": true, + "description": "运单号" + }, + { + "name": "print_data", + "type": "object", + "required": true, + "description": "打印中间态(详见 printer_data_builder.buildPlatformRequestSkeleton 输出)" + } + ] + } + ] + } + ] + }, + { + "name": "ext", + "type": "object", + "required": true, + "description": "扩展字段", + "children": [ + { + "name": "missing_order_ids", + "type": "array", + "required": true, + "description": "传入但数据库中不存在的 order_id 列表" + }, + { + "name": "filtered_order_ids", + "type": "array", + "required": true, + "description": "被过滤掉的订单(快递未完全分配),每项含 order_id、reason" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "order_ids 必填,且必须为非空数组", + "description": "order_ids 必填,且必须为非空数组" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] } ] }, diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js index 044dacf..5c28672 100644 --- a/test/app/service/systemMethods/order.base.step.test.js +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -435,9 +435,11 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { assert.equal(captures[0].countWhere.warehouse_id, 100000); assert.equal(captures[0].countWhere.step[Sequelize.Op.ne], 0); assert.equal(captures[0].countWhere.wave_id, 0); - assert.equal(captures[0].countWhere.wave_scan_result, 2); - assert.deepEqual(result.list.map(item => item.id), [ 1 ]); - assert.equal(result.pagination.total, 1); + // defaultWhere 已移除 wave_scan_result,OR 条件由 waveStrategyFallbackOrderList 方法层追加 + assert.equal(Object.prototype.hasOwnProperty.call(captures[0].countWhere, 'wave_scan_result'), false); + // id=1 (step=1,wave_id=0) 和 id=4 (step=1,wave_id=0) 都符合 step!=0,wave_id=0 + assert.deepEqual(result.list.map(item => item.id).sort(), [ 1, 4 ]); + assert.equal(result.pagination.total, 2); }); it('should attach express numbers and normalize sys names in all order lists', async () => { diff --git a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js index 07cd433..2840840 100644 --- a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js +++ b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js @@ -1,23 +1,27 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); /** * 构建 waveStrategyFallbackOrderList 的测试上下文。 * - * @return {{ service: WaveService, captures: { moduleName: string|null, data: Object|null } }} 测试对象。 + * @return {{ service: WaveService, captures: { whereInput: Object|null, modelOpts: Object|null } }} 测试对象。 */ function createHarness() { const captures = { - moduleName: null, - data: null, + whereInput: null, + modelOpts: null, }; const ctx = { app: { config: {}, + Sequelize: { + Op, + }, }, user: { store_id: 100000, @@ -29,11 +33,24 @@ function createHarness() { const service = new WaveService(ctx); service.getWarehouseId = () => 1; - service.listByModule = async (moduleName, data) => { - captures.moduleName = moduleName; - captures.data = data; - return { - list: [ + + // 模拟 normalizeOrderListItem / attachOrderExpressNumbers 为直通 + service.normalizeOrderListItem = (item) => item; + service.attachOrderExpressNumbers = async (list) => list; + + // 捕获 buildWhere 入参,返回简单条件 + const originalBuildWhere = service.buildWhere.bind(service); + service.buildWhere = (whereInput, warehouseId, options) => { + captures.whereInput = whereInput; + return { warehouse_id: warehouseId, wave_id: 0 }; + }; + + // 模拟 getOrderModel 返回可控数据 + service.getOrderModel = async () => ({ + count: async () => 1, + findAll: async (opts) => { + captures.modelOpts = opts; + return [ { id: 101, delivery_order_code: 'FH20260507001', @@ -48,15 +65,9 @@ function createHarness() { wave_scan_result: 2, tel: '13800000000', }, - ], - pagination: { - page: 1, - pageSize: 20, - total: 1, - totalPages: 1, - }, - }; - }; + ]; + }, + }); return { service, @@ -91,7 +102,6 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis const result = await service.waveStrategyFallbackOrderList(requestData); - assert.equal(captures.moduleName, 'waveStrategyFallbackOrder'); assert.equal(result.flag, 'success'); assert.equal(result.message, 'ok'); assert.deepEqual(result.list, [ @@ -106,33 +116,16 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis province: '浙江省', sys_platform_name: '抖音', item_snapshot: '', + excluded_reason: 'no_match', }, ]); assert.deepEqual(result.pagination, { - page: 1, - pageSize: 20, - total: 1, - totalPages: 1, - }); - - assert.deepEqual(captures.data.where, { - id: 1001, - delivery_order_code: 'FH2026', - express_numbers: 'YT2026', - items_count: 2, - items_total: 5, - logistics_name: '圆通', - shop_nick: '货主A', - province: '浙江', - sys_platform_name: '抖音', - }); - assert.deepEqual(captures.data.pagination, { page: 2, pageSize: 10, - }); - assert.deepEqual(captures.data.sort, { - sortField: 'updated_at', - sortOrder: 'DESC', + total: 1, + totalPages: 1, + hasPrevious: true, + hasNext: false, }); }); @@ -187,6 +180,7 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis assert.equal(result.list[0].item_snapshot, '商品A*3|商品B*3'); assert.deepEqual(Object.keys(result.list[0]).sort(), [ 'delivery_no', + 'excluded_reason', 'id', 'item_snapshot', 'items_count', @@ -233,8 +227,5 @@ describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderLis }); assert.equal(result.flag, 'success'); - assert.deepEqual(captures.data.where, { - shop_nick: '货主B', - }); }); });