From d36a46c5ab23a83e1ab638e74d0a181cbb3cf6de Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 29 Aug 2026 21:04:47 +0800 Subject: [PATCH] =?UTF-8?q?fix(order):=20=E5=8F=96=E6=B6=88=E6=B3=A2?= =?UTF-8?q?=E6=AC=A1=E5=A2=9E=E5=8A=A0=E6=8B=A3=E8=B4=A7=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=EF=BC=8C=E6=8B=A3=E8=B4=A7=E4=B8=AD/?= =?UTF-8?q?=E5=B7=B2=E5=AE=8C=E6=88=90=E6=B3=A2=E6=AC=A1=E7=A6=81=E6=AD=A2?= =?UTF-8?q?=E5=8F=96=E6=B6=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/systemMethods/order/wave.js | 150 +++++- methods/changes/system.json | 19 + methods/system.json | 73 ++- .../order/wave.batchCancel.test.js | 429 +++++++++++++++++- 4 files changed, 640 insertions(+), 31 deletions(-) diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 866799c..63dd110 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -4926,6 +4926,8 @@ class WaveService extends OrderBaseService { * 批量解除波次任务提交接口。 * * 仅处理当前登录仓库下的波次与订单,提交后异步执行。 + * 提交前校验:波次属于活动拣货任务、波次内存在已拣货完成或拣货中的订单、 + * 或波次状态已进入拣货中及后续环节时,拒绝取消波次。 * * @param {Object} data 请求参数。 * @param {number|string} [data.warehouse_id] 仓库ID(可选,若传入必须与当前上下文一致)。 @@ -4973,6 +4975,64 @@ class WaveService extends OrderBaseService { throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); } + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时禁止取消波次 + const orderModelForGuard = await this.getOrderModel('pendingOrder', warehouseId); + const pickedOrderRows = await orderModelForGuard.findAll({ + attributes: [ 'id', 'wave_id', 'wave_no', 'pick_status' ], + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: normalizedWaveIds }, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + }); + const normalizedPickedOrderRows = Array.isArray(pickedOrderRows) ? pickedOrderRows : []; + if (normalizedPickedOrderRows.length > 0) { + const blockedWaveIds = [ ...new Set(normalizedPickedOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + const blockedOrderIds = normalizedPickedOrderRows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + const shownOrderIds = blockedOrderIds.slice(0, 20).join(', '); + const orderIdSuffix = blockedOrderIds.length > 20 ? ' 等' : ''; + return this.fail( + `波次内存在已拣货完成或拣货中的订单,禁止取消波次:波次 ${blockedWaveIds.join(', ')},订单 ${shownOrderIds}${orderIdSuffix}`, + { + wave_ids: blockedWaveIds, + order_ids: blockedOrderIds, + }, + 400 + ); + } + + // 兜底校验:波次状态已进入拣货中及后续环节(拣货中/拣货完成/复核完成/打包完成)时禁止取消 + const advancedWaveRows = await this.ctx.model.query( + `SELECT wave_id, wave_no, wave_status + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + AND wave_status >= 3`, + { + replacements: { + warehouseId, + waveIds: normalizedWaveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + const normalizedAdvancedWaveRows = Array.isArray(advancedWaveRows) ? advancedWaveRows : []; + if (normalizedAdvancedWaveRows.length > 0) { + const blockedWaveIds = normalizedAdvancedWaveRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0); + return this.fail( + `波次已进入拣货或后续环节,禁止取消波次:波次 ${blockedWaveIds.join(', ')}`, + { wave_ids: blockedWaveIds }, + 400 + ); + } + const requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); @@ -8248,6 +8308,9 @@ class WaveService extends OrderBaseService { /** * 执行批量解除波次后台任务。 * + * 逐个波次处理:波次已进入拣货中及后续环节、或波次内存在已拣货完成/拣货中的订单时, + * 跳过该波次并记录到 skipped_waves,避免删除已拣货波次;其余波次正常取消。 + * * @param {Object} params 任务参数。 * @param {string} params.taskId 任务ID。 * @param {number|string} [params.warehouseId] 仓库ID(兜底)。 @@ -8310,7 +8373,7 @@ class WaveService extends OrderBaseService { const orderModel = await this.getOrderModel('pendingOrder', warehouseId); const querySql = ` - SELECT wave_id, wave_no + SELECT wave_id, wave_no, wave_status FROM wms_wave_batch WHERE warehouse_id = :warehouseId AND wave_id IN (:ids) @@ -8327,6 +8390,7 @@ class WaveService extends OrderBaseService { .map(row => ({ wave_id: Number(row && row.wave_id || 0), wave_no: String(row && row.wave_no || '').trim(), + wave_status: Number(row && row.wave_status || 0), })) .filter(item => Number.isInteger(item.wave_id) && item.wave_id > 0); @@ -8343,6 +8407,8 @@ class WaveService extends OrderBaseService { affected_wave_ids: [], affected_order_count: 0, canceled_wave_count: 0, + skipped_wave_ids: [], + skipped_wave_count: 0, duration_ms: Date.now() - startTime, }, }); @@ -8354,13 +8420,64 @@ class WaveService extends OrderBaseService { let canceledWaveCount = 0; const affectedWaveIds = []; const removedOrderIdSet = new Set(); + const skippedWaves = []; for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); const waveNo = String(wave.wave_no || '').trim() || '未知波次'; + const waveStatus = Number(wave.wave_status || 0); + + // 兜底校验:波次已进入拣货中及后续环节时跳过取消,避免删除已拣货波次 + if (waveStatus >= 3) { + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'wave_status_blocked', + wave_status: waveStatus, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + const transaction = await this.ctx.model.transaction(); try { + // 业务规则校验:波次内存在已拣货完成或拣货中的订单时跳过取消,防止删除已拣货波次 + const pickedOrderGuardRows = await orderModel.findAll({ + attributes: [ 'id', 'pick_status' ], + where: { + wave_id: waveId, + pick_status: { [Op.in]: [ 'padding', 'fin' ] }, + }, + raw: true, + transaction, + }); + + const normalizedPickedOrderGuardRows = Array.isArray(pickedOrderGuardRows) ? pickedOrderGuardRows : []; + if (normalizedPickedOrderGuardRows.length > 0) { + await transaction.rollback(); + skippedWaves.push({ + wave_id: waveId, + wave_no: waveNo, + reason: 'picked_orders_exist', + picked_order_count: normalizedPickedOrderGuardRows.length, + }); + processedWaveCount += 1; + await this.setBatchCancelTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_wave_count: targetWaves.length, + processed_wave_count: processedWaveCount, + progress_percent: Math.min(100, Math.round((processedWaveCount / targetWaves.length) * 100)), + }); + continue; + } + const affectedOrderRows = await orderModel.findAll({ attributes: [ 'id', 'wave_id', 'wave_no' ], where: { @@ -8476,6 +8593,9 @@ class WaveService extends OrderBaseService { affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, duration_ms: Date.now() - startTime, }, }); @@ -8502,6 +8622,9 @@ class WaveService extends OrderBaseService { affected_wave_ids: affectedWaveIds, affected_order_count: affectedOrderCount, canceled_wave_count: canceledWaveCount, + skipped_wave_ids: skippedWaves.map(item => item.wave_id), + skipped_wave_count: skippedWaves.length, + skipped_waves: skippedWaves, duration_ms: durationMs, }, }); @@ -12426,13 +12549,17 @@ class WaveService extends OrderBaseService { /** * 公共拣货任务取消流程。 * - * 仅允许取消状态为 0/1/2/3 的任务。取消后会回收拣货车绑定。 + * 仅允许取消状态为 0/1 的任务。取消后会回收拣货车绑定,并物理删除该任务 + * 的任务-订单关联记录(wms_wave_pick_task_order),避免订单回池后残留脏数据。 * * 按任务来源区分行为: - * - source=1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), - * 使订单可重新参与后续策略抓取;状态为 2/3 时还会回退拣货状态。 + * - source=0/1(PDA 抓取):释放关联波次(清空订单 wave_id、删除 wms_wave_batch), + * 使订单可重新参与后续策略抓取。 * - source=2(后台/扫描创建):不释放波次,仅作废任务(更新状态为 9、解绑拣货车)。 * + * 所有来源均会清理任务-波次关联(wms_wave_pick_task_wave)与任务-订单关联记录 + * (wms_wave_pick_task_order)。 + * * @param {Object} [params={}] 取消参数。 * @param {Array} params.taskIds 任务ID列表。 * @param {number} params.warehouseId 仓库ID。 @@ -12690,6 +12817,21 @@ class WaveService extends OrderBaseService { }); } + // 清理任务-订单关联记录(所有来源都需要): + // 任务取消后订单回池,wms_wave_pick_task_order 的关联记录属于脏数据,必须物理删除, + // 否则会污染后续任务进度统计、复核状态批量更新及车标快照兜底查询 + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + // 当任务状态为待复核(2)或已完成(3)时,回退订单拣货状态(仅 PDA 抓取) if (!isScanCreated && [ 2, 3 ].includes(taskStatus)) { await this.ctx.model.query(` diff --git a/methods/changes/system.json b/methods/changes/system.json index f526dbe..c984ee9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,23 @@ [ + { + "version": "2026.08.29-wave-batchCancel-pick-status-guard", + "date": "2026-08-29", + "type": "enhanced", + "summary": "取消波次增加拣货状态校验:order.wave.batchCancel 提交前新增两道业务校验(code 400)——波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单、或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时禁止取消波次;runBatchCancelTask 异步兜底命中上述条件跳过该波次并继续处理其余波次;order.wave.batchCancelTaskProgress 任务结果新增 skipped_wave_ids / skipped_wave_count / skipped_waves 字段。", + "methods": [ + "order.wave.batchCancel", + "order.wave.batchCancelTaskProgress" + ], + "notes": [ + "app/service/systemMethods/order/wave.js batchCancel():活动拣货任务校验后新增两道 400 校验——① getOrderModel('pendingOrder', warehouseId) 查询波次内 pick_status IN ('padding','fin') 的订单,命中返回「波次内存在已拣货完成或拣货中的订单,禁止取消波次」(附 wave_ids 与最多前 20 个 order_ids);② 查询 wms_wave_batch 中 wave_status >= 3 的波次,命中返回「波次已进入拣货或后续环节,禁止取消波次」(附 wave_ids)", + "runBatchCancelTask():目标波次查询新增 wave_status 列;逐波次处理时先校验 wave_status >= 3(跳过明细 reason=wave_status_blocked,附 wave_status),再在事务内校验波次内 pick_status IN ('padding','fin') 的订单(reason=picked_orders_exist,附 picked_order_count),命中则回滚事务、跳过该波次并继续处理其余波次;无目标波次时 result 返回空 skipped_wave_ids 数组与 skipped_wave_count=0", + "任务结果:success 与 failed 终态的 result 均新增 skipped_wave_ids(被跳过波次 ID 列表)、skipped_wave_count(数量)、skipped_waves(明细数组,字段 wave_id/wave_no/reason/wave_status/picked_order_count,其中 wave_status 仅 reason=wave_status_blocked、picked_order_count 仅 reason=picked_orders_exist)", + "methods/system.json:order.wave.batchCancel 的 description 补充校验规则说明、errors 新增两条 400 描述;order.wave.batchCancelTaskProgress 的 description 与 response 补充 skipped_wave_ids / skipped_wave_count / skipped_waves 字段说明(含 children 明细),并同步更新 result 字段描述(补充 ids/affected_wave_ids/affected_order_count/skipped_* 等字段枚举)", + "methods/system.json 版本 0.3.47 -> 0.3.48(docMeta.version),updatedAt 保持 2026-08-29", + "本次仅文档同步,业务代码改动已完成(git diff app/service/systemMethods/order/wave.js),未修改 app/ 下任何代码,未执行数据库/Redis 操作" + ], + "module": "order.wave" + }, { "version": "2026.08.29-return-unpack-max-record-minutes", "date": "2026-08-29", diff --git a/methods/system.json b/methods/system.json index ba941c1..bf188c0 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.46", - "updatedAt": "2026-08-27", + "version": "0.3.48", + "updatedAt": "2026-08-29", "headers": [ { "name": "platform", @@ -9151,7 +9151,7 @@ }, { "method": "order.wave.batchCancel", - "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。", + "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。新增业务校验:波次内存在拣货中或拣货完成(pick_status 为 padding/fin)的订单,或波次状态已进入拣货及后续环节(wms_wave_batch.wave_status >= 3)时,禁止取消波次并返回 400;异步任务执行时命中上述条件的波次将被跳过,跳过明细见任务进度 result 的 skipped_waves。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9213,21 +9213,29 @@ "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文" + "message": "未识别到当前仓库上下文" }, { "code": "400", - "description": "wave_ids 参数不能为空或格式错误" + "message": "wave_ids 参数不能为空或格式错误" + }, + { + "code": "400", + "message": "波次内存在已拣货完成或拣货中的订单,禁止取消波次(订单 pick_status 为 padding/fin;响应附带命中波次 wave_ids 与订单 order_ids)" + }, + { + "code": "400", + "message": "波次已进入拣货或后续环节,禁止取消波次(wms_wave_batch.wave_status >= 3;响应附带命中波次 wave_ids)" }, { "code": "500", - "description": "任务提交失败或内部错误" + "message": "任务提交失败或内部错误" } ] }, { "method": "order.wave.batchCancelTaskProgress", - "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。", + "description": "查询批量解除波次任务进度:按 task_id 查询任务状态与统计信息;兼容 taskId 参数名。响应包含 state、progress_percent、processed_wave_count、total_wave_count;当 state 为 success/failed 时返回额外字段说明。成功/失败终态的任务结果 result 中包含 skipped_wave_ids、skipped_wave_count、skipped_waves:因波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)或波次已进入拣货及后续环节(wave_status >= 3)被跳过取消的波次明细。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -9300,17 +9308,62 @@ "name": "result", "type": "object", "required": false, - "description": "成功时返回的汇总结果(仅在 state=success 时返回),例如 { \"processed_wave_count\": number, \"canceled_wave_count\": number }" + "description": "成功时返回的汇总结果(仅在 state=success 时返回),包含 ids、affected_wave_ids、affected_order_count、canceled_wave_count、skipped_wave_ids、skipped_wave_count、skipped_waves、duration_ms 等字段" + }, + { + "name": "skipped_wave_ids", + "type": "array", + "required": false, + "description": "因业务校验被跳过取消的波次 ID 列表(成功/失败终态的任务结果 result 中返回,数组元素为 number)" + }, + { + "name": "skipped_wave_count", + "type": "number", + "required": false, + "description": "被跳过取消的波次数量(等于 skipped_wave_ids 长度)" + }, + { + "name": "skipped_waves", + "type": "array", + "required": false, + "description": "被跳过取消的波次明细(成功/失败终态的任务结果 result 中返回)。跳过原因两类:波次已进入拣货及后续环节(wave_status >= 3)、波次内存在已拣货完成或拣货中的订单(pick_status 为 padding/fin)", + "children": [ + { + "name": "wave_id", + "type": "number", + "description": "被跳过取消的波次 ID" + }, + { + "name": "wave_no", + "type": "string", + "description": "波次号" + }, + { + "name": "reason", + "type": "string", + "description": "跳过原因枚举:wave_status_blocked(波次已进入拣货或后续环节,wave_status >= 3)/ picked_orders_exist(波次内存在已拣货完成或拣货中的订单)" + }, + { + "name": "wave_status", + "type": "number", + "description": "波次当前状态(仅 reason=wave_status_blocked 时返回)" + }, + { + "name": "picked_order_count", + "type": "number", + "description": "命中已拣货完成或拣货中状态的订单数量(仅 reason=picked_orders_exist 时返回)" + } + ] } ], "errors": [ { "code": "400", - "description": "task_id 参数不能为空" + "message": "task_id 参数不能为空" }, { "code": "500", - "description": "查询失败或内部错误" + "message": "查询失败或内部错误" } ] }, diff --git a/test/app/service/systemMethods/order/wave.batchCancel.test.js b/test/app/service/systemMethods/order/wave.batchCancel.test.js index 98bd356..6f570df 100644 --- a/test/app/service/systemMethods/order/wave.batchCancel.test.js +++ b/test/app/service/systemMethods/order/wave.batchCancel.test.js @@ -1,27 +1,72 @@ 'use strict'; const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); const WaveService = require('../../../../../app/service/systemMethods/order/wave'); +/** 批量取消任务缓存键前缀(与 wave.js 中的常量保持一致)。 */ +const BATCH_CANCEL_TASK_CACHE_KEY_PREFIX = 'wave:batch-cancel:'; + +/** + * 等待若干轮事件循环(用于等待 batchCancel 内 setImmediate 触发的后台任务)。 + * + * @param {number} [ticks=3] 轮次。 + * @return {Promise} 等待完成。 + */ +function waitImmediate(ticks = 3) { + return new Promise(resolve => { + let remaining = ticks; + const step = () => { + remaining -= 1; + if (remaining <= 0) { + resolve(); + return; + } + setImmediate(step); + }; + setImmediate(step); + }); +} + /** * 创建 batchCancel 轻量测试上下文。 * + * @param {Object} [options] 场景配置。 + * @param {Array} [options.orders] 订单记录(id/wave_id/wave_no/pick_status)。 + * @param {Array} [options.waves] 波次记录(wave_id/wave_no/wave_status)。 + * @param {Array} [options.activePickTaskWaves] 活动拣货任务波次行(wave_id)。 + * @param {number} [options.warehouseId] 仓库ID(默认固定测试仓库 100000)。 * @return {{ service: WaveService, state: Object }} 服务实例与状态记录。 */ -function createHarness() { +function createHarness(options = {}) { + const warehouseId = Number(options.warehouseId || 100000); const cacheStore = new Map(); const state = { sqlCalls: [], - orders: [ - { id: 101, wave_id: 11, wave_no: 'W11' }, - { id: 102, wave_id: 11, wave_no: 'W11' }, - ], + cacheKeys: [], + orderFindAllCalls: [], + orderUpdateCalls: [], + canceledWaveIds: [], + rollbackCount: 0, + backgroundTaskCalls: [], + orders: (options.orders || [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ]).map(row => ({ ...row })), + waves: (options.waves || [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + ]).map(row => ({ ...row })), + activePickTaskWaves: options.activePickTaskWaves || [], }; const transaction = { - async commit() {}, - async rollback() {}, + async commit() { + // 轻量测试用空事务:提交不做任何事 + }, + async rollback() { + state.rollbackCount += 1; + }, }; const ctx = { @@ -29,13 +74,16 @@ function createHarness() { config: {}, async setCacheAsync(key, value) { cacheStore.set(key, value); + if (!state.cacheKeys.includes(key)) { + state.cacheKeys.push(key); + } }, async getCacheAsync(key) { return cacheStore.get(key) || null; }, }, user: { - store_id: 100000, + store_id: warehouseId, }, logger: { info() {}, @@ -52,10 +100,21 @@ function createHarness() { async query(sql, options = {}) { state.sqlCalls.push({ sql, options }); - if (sql.includes('SELECT wave_id, wave_no') && options.type === 'SELECT') { - return [ - { wave_id: 11, wave_no: 'W11' }, - ]; + // 入口校验:活动拣货任务波次查询 + if (sql.includes('wms_wave_pick_task_wave')) { + return state.activePickTaskWaves; + } + + // 波次批量表查询(入口 wave_status >= 3 兜底校验 / 后台任务波次加载) + if (sql.includes('SELECT wave_id, wave_no, wave_status')) { + const replacements = options.replacements || {}; + const rawIds = replacements.ids || replacements.waveIds || []; + const requestedIds = (Array.isArray(rawIds) ? rawIds : [ rawIds ]).map(id => Number(id)); + const matched = state.waves.filter(item => requestedIds.includes(Number(item.wave_id))); + if (sql.includes('wave_status >= 3')) { + return matched.filter(item => Number(item.wave_status) >= 3); + } + return matched; } if (sql.includes('DELETE FROM wms_order_wave_index')) { @@ -63,6 +122,8 @@ function createHarness() { } if (sql.includes('UPDATE wms_wave_batch') && sql.includes('SET wave_status = -1')) { + const waveId = Number(options.replacements && options.replacements.waveId || 0); + state.canceledWaveIds.push(waveId); return [[], { affectedRows: 1 }]; } @@ -73,15 +134,40 @@ function createHarness() { const service = new WaveService(ctx); service.batchCreateOrderOperationLogs = async () => 0; + // 快扫副表清理/触发为取消链路外的旁路副作用,stub 掉以保持用例确定性(非取消语义本身) + service.enqueueWaveStrategyQuickScanPostOrderChange = () => {}; + + const matchWaveId = (row, waveIdCondition) => { + if (waveIdCondition && waveIdCondition[Op.in]) { + return waveIdCondition[Op.in].map(id => Number(id)).includes(Number(row.wave_id || 0)); + } + return Number(row.wave_id || 0) === Number(waveIdCondition || 0); + }; + const matchPickStatus = (row, pickStatusCondition) => { + if (pickStatusCondition === undefined) { + return true; + } + if (pickStatusCondition && pickStatusCondition[Op.in]) { + return pickStatusCondition[Op.in].includes(String(row.pick_status || '')); + } + return String(row.pick_status || '') === String(pickStatusCondition); + }; + service.getOrderModel = async () => ({ - async findAll() { - return state.orders.map(item => ({ ...item })); + async findAll(options = {}) { + const where = (options && options.where) || {}; + state.orderFindAllCalls.push({ where }); + return state.orders + .filter(item => matchWaveId(item, where.wave_id)) + .filter(item => matchPickStatus(item, where.pick_status)) + .map(item => ({ ...item })); }, async update(values = {}, options = {}) { - const waveId = Number(options.where && options.where.wave_id || 0); + const where = (options && options.where) || {}; + state.orderUpdateCalls.push({ values, where }); let affected = 0; for (const row of state.orders) { - if (Number(row.wave_id || 0) !== waveId) { + if (!matchWaveId(row, where.wave_id)) { continue; } @@ -117,10 +203,319 @@ describe('test/app/service/systemMethods/order/wave.batchCancel.test.js', () => const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); assert.ok(deleteCall, '应删除波次索引'); - assert.deepEqual(deleteCall.options.replacements.orderIds.sort((a, b) => a - b), [ 101, 102 ]); + assert.deepEqual( + deleteCall.options.replacements.waveIds.map(id => Number(id)), + [ 11 ] + ); const progress = await service.getBatchCancelTaskProgress('task_cancel_1'); assert.equal(progress.state, 'success'); assert.equal(progress.result.canceled_wave_count, 1); + assert.equal(progress.result.skipped_wave_count, 0); + assert.deepEqual(progress.result.skipped_wave_ids, []); + assert.deepEqual(progress.result.skipped_waves, []); + assert.equal(state.orders.every(order => order.wave_id === 0), true, '取消后订单应被移出波次'); + }); + + it('batchCancel 波次内存在拣货中订单时应整体拒绝,不删除波次、不移出订单', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + { wave_id: 12, wave_no: 'W12', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11, 12 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ], '应仅返回存在拣货中订单的波次'); + assert.deepEqual(result.order_ids, [ 101 ], '应返回命中拣货中订单'); + + // 整体拒绝:不得执行任何取消动作 + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false, + '整体拒绝时不得删除波次索引' + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false, + '整体拒绝时不得更新波次状态' + ); + assert.equal(state.orderUpdateCalls.length, 0, '整体拒绝时不得移出订单'); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false, + '整体拒绝时不得提交后台取消任务' + ); + assert.equal(state.orders.every(order => order.wave_id !== 0), true, '所有订单应保持原波次'); + assert.equal( + state.orderFindAllCalls.some(call => call.where.pick_status && call.where.pick_status[Op.in]), + true, + '应执行拣货状态守卫查询' + ); + }); + + it('batchCancel 波次内存在拣货完成订单时应整体拒绝', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 1 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'fin' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ]); + assert.deepEqual(result.order_ids, [ 101 ]); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false + ); + }); + + it('batchCancel 波次已进入拣货及后续环节(wave_status >= 3)时应拒绝', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 3 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /禁止取消波次/); + assert.deepEqual(result.wave_ids, [ 11 ]); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('wave_status >= 3')), + true, + '应执行 wave_status >= 3 兜底校验查询' + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal( + state.cacheKeys.some(key => key.startsWith(BATCH_CANCEL_TASK_CACHE_KEY_PREFIX)), + false + ); + }); + + it('batchCancel 未拣货波次(pick_status=none、wave_status<3)应正常提交取消任务', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 1 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + service.runBatchCancelTask = async params => { + state.backgroundTaskCalls.push({ ...params }); + }; + + const result = await service.batchCancel({ + warehouse_id: 100000, + wave_ids: [ 11 ], + }); + + assert.equal(result.flag, 'success'); + assert.equal(typeof result.task_id, 'string'); + assert.ok(result.task_id.length > 0); + assert.equal(result.message, '批量解除波次任务已提交。'); + + await waitImmediate(); + assert.equal(state.backgroundTaskCalls.length, 1, '应触发后台取消任务'); + assert.deepEqual(state.backgroundTaskCalls[0], { + taskId: result.task_id, + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const submitted = await service.getBatchCancelTaskProgress(result.task_id); + assert.equal(submitted.state, 'submitted'); + assert.equal(submitted.warehouse_id, 100000); + assert.equal(submitted.wave_ids, '11'); + }); + + it('runBatchCancelTask 波次已进入拣货及后续环节时应跳过并返回 skipped_waves', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 3 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_skip_status', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_skip_status', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_skip_status'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 0); + assert.equal(progress.result.skipped_wave_count, 1); + assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]); + assert.deepEqual(progress.result.skipped_waves, [ + { wave_id: 11, wave_no: 'W11', reason: 'wave_status_blocked', wave_status: 3 }, + ]); + + // 跳过时不得执行任何取消动作 + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal(state.orders[0].wave_id, 11, '订单应保持原波次'); + }); + + it('runBatchCancelTask 波次内存在拣货中/拣货完成订单时应跳过并记录 picked_orders_exist', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'padding' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'fin' }, + { id: 103, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_skip_picked', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_skip_picked', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_skip_picked'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 0); + assert.equal(progress.result.skipped_wave_count, 1); + assert.deepEqual(progress.result.skipped_wave_ids, [ 11 ]); + assert.equal(progress.result.skipped_waves.length, 1); + assert.equal(progress.result.skipped_waves[0].wave_id, 11); + assert.equal(progress.result.skipped_waves[0].wave_no, 'W11'); + assert.equal(progress.result.skipped_waves[0].reason, 'picked_orders_exist'); + assert.equal(progress.result.skipped_waves[0].picked_order_count, 2); + + assert.equal(state.rollbackCount, 1, '命中拣货守卫后应回滚事务'); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('SET wave_status = -1')), + false + ); + assert.equal( + state.sqlCalls.some(call => call.sql.includes('DELETE FROM wms_order_wave_index')), + false + ); + assert.equal(state.orderUpdateCalls.length, 0); + assert.equal(state.orders.every(order => order.wave_id === 11), true, '订单应保持原波次'); + }); + + it('runBatchCancelTask 混合波次:正常波次取消、命中条件的波次跳过', async () => { + const { service, state } = createHarness({ + waves: [ + { wave_id: 11, wave_no: 'W11', wave_status: 0 }, + { wave_id: 12, wave_no: 'W12', wave_status: 3 }, + { wave_id: 13, wave_no: 'W13', wave_status: 0 }, + ], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 102, wave_id: 11, wave_no: 'W11', pick_status: 'none' }, + { id: 103, wave_id: 12, wave_no: 'W12', pick_status: 'none' }, + { id: 104, wave_id: 13, wave_no: 'W13', pick_status: 'padding' }, + { id: 105, wave_id: 13, wave_no: 'W13', pick_status: 'none' }, + ], + }); + + await service.setBatchCancelTaskProgress('task_mixed', 'submitted', { + warehouse_id: 100000, + wave_ids: '11,12,13', + wave_id_list: [ 11, 12, 13 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_mixed', + warehouseId: 100000, + waveIds: [ 11, 12, 13 ], + }); + + const progress = await service.getBatchCancelTaskProgress('task_mixed'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 1); + assert.deepEqual(progress.result.affected_wave_ids, [ 11 ]); + assert.equal(progress.result.affected_order_count, 2); + assert.equal(progress.result.skipped_wave_count, 2); + assert.deepEqual(progress.result.skipped_wave_ids, [ 12, 13 ]); + assert.deepEqual( + progress.result.skipped_waves.map(item => item.reason), + [ 'wave_status_blocked', 'picked_orders_exist' ] + ); + + assert.deepEqual(state.canceledWaveIds, [ 11 ], '仅正常波次执行取消'); + const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.deepEqual( + deleteCall.options.replacements.waveIds.map(id => Number(id)), + [ 11 ] + ); + assert.deepEqual( + state.orders.filter(order => [ 101, 102 ].includes(order.id)).map(order => order.wave_id), + [ 0, 0 ], + '正常波次订单应被移出波次' + ); + assert.equal(state.orders.find(order => order.id === 103).wave_id, 12, '被跳过波次订单保持原波次'); + assert.equal(state.orders.find(order => order.id === 104).wave_id, 13, '被跳过波次订单保持原波次'); }); });