From 9c2b25420671adc78de1eaa4654cf63ccd528c54 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 11 May 2026 08:44:27 +0800 Subject: [PATCH] 1 Co-authored-by: Copilot --- app/lib/wave_strategy_quick_scan_runner.js | 195 + app/model/notification_webhook.js | 1 + app/model/order_delivery.js | 12 + app/model/order_wave_strategy_match.js | 53 + app/model/picking_strategy.js | 13 +- .../wave_strategy_quick_scan_fallback.js | 150 + app/service/systemMethods/order/base.js | 51 + app/service/systemMethods/order/wave.js | 5617 ++++++++++++++++- app/service/systemMethods/pick.js | 53 +- .../systemMethods/setting/warehouse.js | 2 +- app/service/systems/delivery_order.js | 20 + app/service/systems/notice/index.js | 1 + app/service/systems/pick.js | 667 ++ app/service/systems/setting/warehouse.js | 208 +- database/config.js | 17 +- ...-add-box-fields-to-wms_receiving_detail.js | 37 + ...s_picking_strategy-to-wms_wave_strategy.js | 37 + ...00-create-wms_order_wave_strategy_match.js | 70 + ...0508123000-create-wave-pick-task-tables.js | 1108 ++++ ...20260508140000-add-source-to-wave-batch.js | 56 + ...0508150000-add-source-to-wave-pick-task.js | 50 + ...3000-repair-wave-pick-task-schema-drift.js | 349 + methods/changes/2026.05.08-system-06.json | 16 + methods/changes/system.json | 284 +- methods/system.json | 1760 +++++- script/check_tables.cjs | 21 + script/run-single-migration.cjs | 156 + .../systemMethods/order.base.step.test.js | 95 + .../order/wave.buildTaskBoxRows.test.js | 131 + .../order/wave.singleFetchByIds.test.js | 60 +- .../order/wave.wavePickTaskList.test.js | 143 + ...wave.waveStrategyFallbackOrderList.test.js | 240 + .../order/wave.waveStrategyFetch.test.js | 255 + .../order/wave.waveStrategyList.test.js | 201 + .../order/wave.waveStrategyQuickScan.test.js | 394 ++ .../service/systems/setting/warehouse.test.js | 109 + tmp/verify_migration.cjs | 37 + 37 files changed, 12559 insertions(+), 110 deletions(-) create mode 100644 app/lib/wave_strategy_quick_scan_runner.js create mode 100644 app/model/order_wave_strategy_match.js create mode 100644 app/schedule/wave_strategy_quick_scan_fallback.js create mode 100644 database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js create mode 100644 database/migrations/20260507100000-create-wms_order_wave_strategy_match.js create mode 100644 database/migrations/20260508123000-create-wave-pick-task-tables.js create mode 100644 database/migrations/20260508140000-add-source-to-wave-batch.js create mode 100644 database/migrations/20260508150000-add-source-to-wave-pick-task.js create mode 100644 database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js create mode 100644 methods/changes/2026.05.08-system-06.json create mode 100644 script/check_tables.cjs create mode 100644 script/run-single-migration.cjs create mode 100644 test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js create mode 100644 test/app/service/systemMethods/order/wave.wavePickTaskList.test.js create mode 100644 test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js create mode 100644 test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js create mode 100644 test/app/service/systemMethods/order/wave.waveStrategyList.test.js create mode 100644 test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js create mode 100644 tmp/verify_migration.cjs diff --git a/app/lib/wave_strategy_quick_scan_runner.js b/app/lib/wave_strategy_quick_scan_runner.js new file mode 100644 index 0000000..872078c --- /dev/null +++ b/app/lib/wave_strategy_quick_scan_runner.js @@ -0,0 +1,195 @@ +'use strict'; + +/** + * 执行波次策略快速扫描通用流程。 + * + * @param {Object} [options={}] 扫描参数。 + * @param {Array} [options.orders] 订单数组。 + * @param {Array} [options.strategyList] 策略数组。 + * @param {Function} [options.getStructureKey] 获取订单结构 key。 + * @param {Function} [options.getExpressKey] 获取订单快递 key。 + * @param {Function} [options.isOrderMatched] 判断订单是否命中策略。 + * @param {Function} [options.getMatchedStrategyIds] 获取订单命中策略ID数组。 + * @param {Function} [options.onProgress] 异步进度回调。 + * @return {Promise<{totalOrderCount:number, processedOrderCount:number, matchedOrderIds:Array, unmatchedOrderIds:Array, matchedStrategyIdsByOrder:Object}>} 扫描结果。 + */ +async function runWaveStrategyQuickScanRunner(options = {}) { + const normalizedOptions = options && typeof options === 'object' ? options : {}; + const normalizedOrders = Array.isArray(normalizedOptions.orders) ? normalizedOptions.orders : []; + const strategyList = Array.isArray(normalizedOptions.strategyList) ? normalizedOptions.strategyList : []; + const getStructureKey = typeof normalizedOptions.getStructureKey === 'function' + ? normalizedOptions.getStructureKey + : () => ''; + const getExpressKey = typeof normalizedOptions.getExpressKey === 'function' + ? normalizedOptions.getExpressKey + : () => ''; + const isOrderMatched = typeof normalizedOptions.isOrderMatched === 'function' + ? normalizedOptions.isOrderMatched + : () => false; + const getMatchedStrategyIds = typeof normalizedOptions.getMatchedStrategyIds === 'function' + ? normalizedOptions.getMatchedStrategyIds + : null; + const onProgress = typeof normalizedOptions.onProgress === 'function' + ? normalizedOptions.onProgress + : null; + + const structureStoreSetMap = new Map(); + const structureOwnerCountMap = new Map(); + const structureExpressCountMap = new Map(); + + for (const order of normalizedOrders) { + const structureKey = String(getStructureKey(order) || '').trim(); + if (!structureKey) { + continue; + } + + const storeId = String(order && order.store_id || '').trim().toLowerCase(); + if (!structureStoreSetMap.has(structureKey)) { + structureStoreSetMap.set(structureKey, new Set()); + } + if (!structureOwnerCountMap.has(structureKey)) { + structureOwnerCountMap.set(structureKey, new Map()); + } + if (!structureExpressCountMap.has(structureKey)) { + structureExpressCountMap.set(structureKey, new Map()); + } + if (storeId) { + structureStoreSetMap.get(structureKey).add(storeId); + const ownerCountMap = structureOwnerCountMap.get(structureKey); + ownerCountMap.set(storeId, Number(ownerCountMap.get(storeId) || 0) + 1); + } + + const expressKey = String(getExpressKey(order) || '').trim().toLowerCase(); + if (expressKey) { + const expressCountMap = structureExpressCountMap.get(structureKey); + expressCountMap.set(expressKey, Number(expressCountMap.get(expressKey) || 0) + 1); + } + } + + const structurePrimaryOwnerMap = new Map(); + for (const [ structureKey, ownerCountMap ] of structureOwnerCountMap.entries()) { + if (!(ownerCountMap instanceof Map) || ownerCountMap.size === 0) { + continue; + } + + let primaryOwner = ''; + let maxCount = 0; + for (const [ storeId, count ] of ownerCountMap.entries()) { + const normalizedStoreId = String(storeId || '').trim().toLowerCase(); + const normalizedCount = Number(count || 0); + if (!normalizedStoreId || normalizedCount <= 0) { + continue; + } + + if ( + normalizedCount > maxCount + || (normalizedCount === maxCount && (!primaryOwner || normalizedStoreId < primaryOwner)) + ) { + maxCount = normalizedCount; + primaryOwner = normalizedStoreId; + } + } + + if (primaryOwner) { + structurePrimaryOwnerMap.set(structureKey, primaryOwner); + } + } + + const structurePrimaryExpressMap = new Map(); + for (const [ structureKey, expressCountMap ] of structureExpressCountMap.entries()) { + if (!(expressCountMap instanceof Map) || expressCountMap.size === 0) { + continue; + } + + let primaryExpressKey = ''; + let maxCount = 0; + for (const [ expressKey, count ] of expressCountMap.entries()) { + const normalizedExpressKey = String(expressKey || '').trim().toLowerCase(); + const normalizedCount = Number(count || 0); + if (!normalizedExpressKey || normalizedCount <= 0) { + continue; + } + + if ( + normalizedCount > maxCount + || (normalizedCount === maxCount && (!primaryExpressKey || normalizedExpressKey < primaryExpressKey)) + ) { + maxCount = normalizedCount; + primaryExpressKey = normalizedExpressKey; + } + } + + if (primaryExpressKey) { + structurePrimaryExpressMap.set(structureKey, primaryExpressKey); + } + } + + const matchedOrderIds = []; + const unmatchedOrderIds = []; + const matchedStrategyIdsByOrder = {}; + const totalOrderCount = normalizedOrders.length; + let processedOrderCount = 0; + + for (const order of normalizedOrders) { + const context = { + structureStoreSetMap, + structureOwnerCountMap, + structurePrimaryOwnerMap, + structureExpressCountMap, + structurePrimaryExpressMap, + }; + const orderId = Number(order && order.id || 0); + let matched = false; + + if (getMatchedStrategyIds) { + const rawMatchedStrategyIds = getMatchedStrategyIds(order, strategyList, context); + const matchedStrategyIds = [ ...new Set((Array.isArray(rawMatchedStrategyIds) ? rawMatchedStrategyIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + matched = matchedStrategyIds.length > 0; + + if (Number.isInteger(orderId) && orderId > 0) { + matchedStrategyIdsByOrder[orderId] = matchedStrategyIds; + } + } else { + matched = Boolean(isOrderMatched(order, strategyList, context)); + } + + if (Number.isInteger(orderId) && orderId > 0) { + if (matched) { + matchedOrderIds.push(orderId); + } else { + unmatchedOrderIds.push(orderId); + } + } + + processedOrderCount += 1; + if (onProgress && (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount)) { + await onProgress({ + totalOrderCount, + processedOrderCount, + matchedOrderCount: matchedOrderIds.length, + unmatchedOrderCount: unmatchedOrderIds.length, + }); + } + } + + if (onProgress && totalOrderCount === 0) { + await onProgress({ + totalOrderCount, + processedOrderCount, + matchedOrderCount: 0, + unmatchedOrderCount: 0, + }); + } + + return { + totalOrderCount, + processedOrderCount, + matchedOrderIds, + unmatchedOrderIds, + matchedStrategyIdsByOrder, + }; +} + +module.exports = runWaveStrategyQuickScanRunner; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index 2f1bba8..a94a799 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -43,6 +43,7 @@ module.exports = app => { Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), + Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }), Object.freeze({ code: 'store_warehouse_print_quantity_adjusted', name: '货主面单余额调整', diff --git a/app/model/order_delivery.js b/app/model/order_delivery.js index d692a2c..0bcca77 100644 --- a/app/model/order_delivery.js +++ b/app/model/order_delivery.js @@ -399,6 +399,18 @@ module.exports = app => { defaultValue: '', comment: '波次号,空字符串表示未分配', }, + wave_strategy_version: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '波次策略版本号', + }, + wave_scan_result: { + type: INTEGER(10), + allowNull: false, + defaultValue: 0, + comment: '波次扫描结果,0未扫描,1扫描符合,2扫描没有符合', + }, // 状态机字段 post_status: { type: ENUM(...StatusEnum.POST_STATUS), diff --git a/app/model/order_wave_strategy_match.js b/app/model/order_wave_strategy_match.js new file mode 100644 index 0000000..972dcc2 --- /dev/null +++ b/app/model/order_wave_strategy_match.js @@ -0,0 +1,53 @@ +// app/model/order_wave_strategy_match.js +'use strict'; + +module.exports = app => { + const { BIGINT, INTEGER, DATE } = app.Sequelize; + + const OrderWaveStrategyMatch = app.model.define('wms_order_wave_strategy_match', { + id: { + type: BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: INTEGER(10), + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: BIGINT, + allowNull: false, + comment: '订单ID,逻辑关联分仓主表,不做物理外键', + }, + strategy_id: { + type: INTEGER(10), + allowNull: false, + comment: '命中的波次策略ID', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '写入时间', + }, + }, { + tableName: 'wms_order_wave_strategy_match', + timestamps: false, + comment: '订单波次策略命中明细表,记录每个订单命中的全部策略', + indexes: [ + { + name: 'idx_warehouse_order', + fields: [ 'warehouse_id', 'order_id' ], + }, + { + name: 'idx_warehouse_strategy', + fields: [ 'warehouse_id', 'strategy_id' ], + }, + ], + }); + + return OrderWaveStrategyMatch; +}; diff --git a/app/model/picking_strategy.js b/app/model/picking_strategy.js index 34b7a2f..aa56ef4 100644 --- a/app/model/picking_strategy.js +++ b/app/model/picking_strategy.js @@ -1,10 +1,15 @@ // app/model/picking_strategy.js 'use strict'; +/** + * 波次策略模型定义。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 波次策略模型 + */ module.exports = app => { const { BIGINT, INTEGER, STRING, TINYINT, BOOLEAN, JSON, TEXT, DATE } = app.Sequelize; - const PickingStrategy = app.model.define('wms_picking_strategy', { + const WaveStrategy = app.model.define('wms_wave_strategy', { id: { type: INTEGER, primaryKey: true, @@ -147,10 +152,10 @@ module.exports = app => { comment: '更新时间', }, }, { - tableName: 'wms_picking_strategy', + tableName: 'wms_wave_strategy', timestamps: false, underscored: false, - comment: '拣货策略配置表', + comment: '波次策略配置表', indexes: [ { name: 'idx_warehouse_type', @@ -163,5 +168,5 @@ module.exports = app => { ], }); - return PickingStrategy; + return WaveStrategy; }; diff --git a/app/schedule/wave_strategy_quick_scan_fallback.js b/app/schedule/wave_strategy_quick_scan_fallback.js new file mode 100644 index 0000000..4a4bd10 --- /dev/null +++ b/app/schedule/wave_strategy_quick_scan_fallback.js @@ -0,0 +1,150 @@ +'use strict'; + +const FALLBACK_TASK_NAME = 'wave_strategy_quick_scan_fallback'; + +module.exports = { + schedule: { + interval: '10m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行波次策略快速扫描兜底任务。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._waveStrategyQuickScanFallbackRunning) { + ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务仍在运行中,跳过本轮调度`); + return; + } + + ctx.app._waveStrategyQuickScanFallbackRunning = true; + + let totalWarehouseCount = 0; + let submitSuccessCount = 0; + let reusedRunningTaskCount = 0; + let submitFailedCount = 0; + let cleanupDeletedCount = 0; + + try { + const storeRows = await ctx.model.Store.findAll({ + attributes: [ 'id' ], + where: { + status: 1, + project: 'warehouse', + }, + raw: true, + }); + + const warehouseIds = Array.isArray(storeRows) + ? storeRows.map(item => Number(item && item.id || 0)).filter(item => Number.isInteger(item) && item > 0) + : []; + totalWarehouseCount = warehouseIds.length; + + for (const warehouseId of warehouseIds) { + try { + const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId); + const submitMessage = String(submitPayload && submitPayload.message || '').trim(); + const submitState = String(submitPayload && submitPayload.state || '').trim(); + const isReusedRunningTask = submitMessage.includes('已有快速扫描任务在运行中') + || [ 'running', 'submitted' ].includes(submitState) && submitMessage.includes('运行中'); + + if (isReusedRunningTask) { + reusedRunningTaskCount += 1; + } else { + submitSuccessCount += 1; + } + } catch (error) { + submitFailedCount += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 仓库触发失败`, { + warehouseId, + error: errorMessage, + }); + + const noticeService = ctx.service + && ctx.service.systems + && ctx.service.systems.notice + && typeof ctx.service.systems.notice.send === 'function' + ? ctx.service.systems.notice + : (ctx.service + && ctx.service.systems + && ctx.service.systems.notice + && ctx.service.systems.notice.index + && typeof ctx.service.systems.notice.index.send === 'function' + ? ctx.service.systems.notice.index + : null); + + if (!noticeService) { + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 通知服务不可用,跳过失败通知`, { + warehouseId, + error: errorMessage, + }); + continue; + } + + try { + await noticeService.send({ + event: 'wave_strategy_quick_scan_failed', + businessName: 'order', + warehouseId, + subjectId: warehouseId, + subject: { + id: warehouseId, + type: 'warehouse', + }, + title: `波次策略兜底扫描触发失败(仓库 ${warehouseId})`, + content: `兜底扫描任务触发失败,仓库 ${warehouseId},错误:${errorMessage}`, + data: { + warehouse_id: warehouseId, + error: errorMessage, + task: FALLBACK_TASK_NAME, + }, + metadata: { + warehouse_id: warehouseId, + error: errorMessage, + task: FALLBACK_TASK_NAME, + }, + sender: { + id: 0, + name: 'system', + }, + }); + } catch (noticeError) { + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 发送失败通知异常`, { + warehouseId, + error: noticeError && noticeError.message ? noticeError.message : `${noticeError}`, + }); + } + } + } + + try { + cleanupDeletedCount = Number( + await ctx.service.systemMethods.order.wave.cleanupWaveStrategyQuickScanMatchedStrategies({ expireHours: 24 }) + ) || 0; + } catch (cleanupError) { + ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 命中副表清理失败`, { + error: cleanupError && cleanupError.message ? cleanupError.message : `${cleanupError}`, + }); + } + + ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务完成`, { + totalWarehouseCount, + submitSuccessCount, + reusedRunningTaskCount, + submitFailedCount, + cleanupDeletedCount, + }); + } catch (error) { + ctx.logger.error(`[${FALLBACK_TASK_NAME}] 任务执行失败: ${error && error.message ? error.message : error}`); + } finally { + ctx.app._waveStrategyQuickScanFallbackRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 0c2108c..d4e60b7 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -39,6 +39,8 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([ 'items', 'items_count', 'items_total', 'items_weight', 'wave_id', 'wave_no', + 'wave_strategy_version', + 'wave_scan_result', 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', @@ -93,6 +95,23 @@ const MODULE_CONFIGS = Object.freeze({ }, }, }, + waveStrategyFallbackOrder: { + modelType: 'current', + defaultWhere: { + step: { + operator: 'ne', + value: 0, + }, + wave_id: { + operator: 'eq', + value: 0, + }, + wave_scan_result: { + operator: 'eq', + value: 2, + }, + }, + }, outboundOrder: { modelType: 'current', defaultWhere: { @@ -467,6 +486,34 @@ class OrderBaseService extends MainService { return ORDER_WEIGHT_TYPE_LABELS[0]; } + /** + * 规范波次扫描结果,空值时默认返回 0(未扫描)。 + * @param {*} scanResult 扫描结果原始值。 + * @return {number|string} 规范化后的扫描结果。 + */ + normalizeWaveScanResult(scanResult) { + if (scanResult === null || scanResult === undefined || scanResult === '') { + return 0; + } + + const numericResult = Number(scanResult); + return Number.isNaN(numericResult) ? scanResult : numericResult; + } + + /** + * 规范波次策略版本,空值时默认返回 0。 + * @param {*} strategyVersion 波次策略版本原始值。 + * @return {number|string} 规范化后的波次策略版本。 + */ + normalizeWaveStrategyVersion(strategyVersion) { + if (strategyVersion === null || strategyVersion === undefined || strategyVersion === '') { + return 0; + } + + const numericVersion = Number(strategyVersion); + return Number.isNaN(numericVersion) ? strategyVersion : numericVersion; + } + /** * 规范订单列表单行输出,保证重量类型直接返回中文。 * @param {Object} order 订单列表行数据。 @@ -482,6 +529,8 @@ class OrderBaseService extends MainService { name: this.maskListSensitiveValue(order.name), tel: this.maskListSensitiveValue(order.tel), weight_type: this.formatWeightTypeLabel(order.weight_type), + wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version), + wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), }; } @@ -689,6 +738,8 @@ class OrderBaseService extends MainService { name: this.maskListSensitiveValue(orderRow.name), tel: this.maskListSensitiveValue(orderRow.tel), mobile: this.maskListSensitiveValue(orderRow.mobile), + wave_strategy_version: this.normalizeWaveStrategyVersion(orderRow.wave_strategy_version), + wave_scan_result: this.normalizeWaveScanResult(orderRow.wave_scan_result), sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name') ? (orderRow.sys_platform_name ?? null) : null, diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 9ef750c..0a14c4d 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2,6 +2,7 @@ const { Op } = require('sequelize'); const OrderBaseService = require('./base'); +const runWaveStrategyQuickScanRunner = require('../../../lib/wave_strategy_quick_scan_runner'); const DEFAULT_PAGE = 1; const DEFAULT_PAGE_SIZE = 20; @@ -9,7 +10,6 @@ const MAX_PAGE_SIZE = 200; const BATCH_LIST_MAX_PAGE_SIZE = 500; const DEFAULT_MAX_WAVE_QUANTITY = 500; const DEFAULT_MIN_GROUP_ORDER_FETCH_QUANTITY = 13; -const SINGLE_FETCH_BY_IDS_WAVE_PREFIX = 'S'; const WAVE_MANUAL_FETCH_FLAG = 'wave_manual_fetch'; const FETCH_TASK_CACHE_KEY_PREFIX = 'wave:fetch:task:'; const FETCH_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2; @@ -21,9 +21,33 @@ const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-expres const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:'; const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:'; +const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24; +const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:'; +const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2; +const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:'; +const WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS = 60 * 30; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1; const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ]; const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map(); +const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ + id: 'id', + delivery_no: 'delivery_order_code', + deliveryNo: 'delivery_order_code', + tracking_no: 'express_numbers', + trackingNo: 'express_numbers', + items_count: 'items_count', + items_count_min: 'items_count', + items_count_max: 'items_count', + items_total: 'items_total', + items_total_min: 'items_total', + items_total_max: 'items_total', + sys_logistics_name: 'logistics_name', + store_name: 'shop_nick', + owner_name: 'shop_nick', + province: 'province', + sys_platform_name: 'sys_platform_name', +}); class WaveService extends OrderBaseService { /** @@ -34,9 +58,9 @@ class WaveService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; - const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; - const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds'; + const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -345,6 +369,34 @@ class WaveService extends OrderBaseService { } } + /** + * 读取散单波次编号前缀(缓存优先,缓存 miss 再读库)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 散单波次编号前缀。 + */ + async getSingleFetchByIdsWavePrefix(warehouseId) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return 'A'; + } + + try { + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const singleFetchByIdsWavePrefix = String( + this.getWarehouseSubjectConfigValue(subjectConfig, 'delete_order_wave_prefix') || '' + ).trim(); + if (!singleFetchByIdsWavePrefix) { + return 'A'; + } + + return singleFetchByIdsWavePrefix.slice(0, 5); + } catch (error) { + this.ctx.logger.warn('[wave.getSingleFetchByIdsWavePrefix] 获取仓库散单波次前缀失败: %s', error.message); + return 'A'; + } + } + /** * 统一读取仓库主体配置(缓存优先,缓存 miss 回源数据库)。 * @@ -609,7 +661,9 @@ class WaveService extends OrderBaseService { * @param {string} params.logisticsName 快递名称。 * @param {string} params.itemSnapshotKey 机器明细快照。 * @param {string} [params.wavePrefix] 波次编号前缀。 - * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @param {string} [params.waveNo] 波次编号(传入则直接使用)。 + * @param {number|string} [params.waveType=1] 波次类型,仅允许 1(团购)或 2(散单),非法值回退 1。 + * @param {number|string} [params.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @param {Object} params.transaction Sequelize 事务。 * @return {Promise<{waveId: number, waveNo: string}>} 创建结果。 */ @@ -624,6 +678,8 @@ class WaveService extends OrderBaseService { itemSnapshotKey, wavePrefix, waveNo, + waveType, + source, transaction, } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); @@ -636,6 +692,9 @@ class WaveService extends OrderBaseService { const normalizedItemSnapshotKey = String(itemSnapshotKey || '').trim(); const normalizedWavePrefix = String(wavePrefix || '').trim() || 'B'; const normalizedWaveNoInput = String(waveNo || '').trim(); + const normalizedWaveType = Number(waveType) === 2 ? 2 : 1; + const normalizedSourceInput = Number(source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; let normalizedWaveNo = normalizedWaveNoInput; if (!normalizedWaveNo) { const datePart = this.getCurrentDatePart(); @@ -660,13 +719,14 @@ class WaveService extends OrderBaseService { item_snapshot_key, warehouse_id, creator, + source, create_time, update_time ) VALUES ( :waveNo, - 1, + :waveType, 1, :totalOrders, 0, @@ -678,6 +738,7 @@ class WaveService extends OrderBaseService { :itemSnapshotKey, :warehouseId, :creator, + :source, NOW(), NOW() ) @@ -686,6 +747,7 @@ class WaveService extends OrderBaseService { const createResult = await this.ctx.model.query(sql, { replacements: { waveNo: normalizedWaveNo, + waveType: normalizedWaveType, totalOrders: normalizedTotalOrders, itemDetailMachine: normalizedItemDetailMachine, itemPartType: normalizedItemPartType, @@ -695,6 +757,7 @@ class WaveService extends OrderBaseService { itemSnapshotKey: normalizedItemSnapshotKey, warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, creator, + source: normalizedSource, }, transaction, }); @@ -756,6 +819,7 @@ class WaveService extends OrderBaseService { * @param {number} [minGroupOrderFetchQuantity=13] 最小团购抓取数量。 * @param {Object} [options={}] 额外抓取选项。 * @param {number} [options.maxFetchQuantity=0] 本结构最大抓取订单数上限,0 表示不限制。 + * @param {number|string} [options.source=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 * @return {Promise} 单结构抓取结果。 */ async fetchSingleStructure( @@ -774,6 +838,8 @@ class WaveService extends OrderBaseService { && Number(normalizedOptions.maxFetchQuantity) > 0 ? Number(normalizedOptions.maxFetchQuantity) : 0; + const normalizedSourceInput = Number(normalizedOptions.source); + const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0; const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity)) && Number(minGroupOrderFetchQuantity) > 0 ? Number(minGroupOrderFetchQuantity) @@ -832,6 +898,7 @@ class WaveService extends OrderBaseService { logisticsName: structure.logistics_name, itemSnapshotKey: structure.item_snapshot_key, wavePrefix, + source: normalizedSource, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE @@ -922,6 +989,10 @@ class WaveService extends OrderBaseService { }); const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, mergedOrderIds, { + triggerScan: false, + source: 'fetchSingleStructure', + }); let reason = stopReason; if (!reason && totalFetchedQuantity > 0 && totalFetchedQuantity < requestedQuantity) { reason = '可抓取订单不足'; @@ -1037,19 +1108,25 @@ class WaveService extends OrderBaseService { /** * 规范化分页参数。 * - * @param {Object} data 请求参数。 + * @param {Object} data 请求参数;兼容直接传入 pagination 对象。 * @param {Object} data.pagination 分页参数对象。 * @param {number|string} data.pagination.page 页码。 * @param {number|string} data.pagination.pageSize 每页数量(驼峰写法,可用)。 * @param {number|string} data.pagination.page_size 每页数量(下划线写法,可用)。 * @param {number|string} data.pagination.limit 每页数量(limit 写法,可用)。 * @param {number|string} data.pagination.size 每页数量(size 写法,可用)。 + * @param {number|string} data.page 页码(直接分页对象写法)。 + * @param {number|string} data.pageSize 每页数量(直接分页对象驼峰写法)。 + * @param {number|string} data.page_size 每页数量(直接分页对象下划线写法)。 + * @param {number|string} data.limit 每页数量(直接分页对象 limit 写法)。 + * @param {number|string} data.size 每页数量(直接分页对象 size 写法)。 * @param {Object} options 规范化选项。 * @param {number|string} options.maxPageSize 每页数量上限。 * @return {{ page: number, pageSize: number }} 规范化后的分页信息。 */ normalizePagination(data = {}, options = {}) { - const pagination = this.isPlainObject(data && data.pagination) ? data.pagination : {}; + const normalizedData = this.isPlainObject(data) ? data : {}; + const pagination = this.isPlainObject(normalizedData.pagination) ? normalizedData.pagination : normalizedData; const pageSource = pagination.page; const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.limit ?? pagination.size; const maxPageSizeSource = Number(options.maxPageSize || MAX_PAGE_SIZE); @@ -1228,6 +1305,7 @@ class WaveService extends OrderBaseService { 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', + 'source', 'total_orders_min', 'total_orders_max', 'processed_orders_min', @@ -1308,6 +1386,7 @@ class WaveService extends OrderBaseService { appendLikeCondition('wave_no', 'wave_no', 'whereWaveNo'); appendIntegerEqualCondition('wave_type', 'wave_type', 'whereWaveType'); appendIntegerEqualCondition('wave_status', 'wave_status', 'whereWaveStatus'); + appendIntegerEqualCondition('source', 'source', 'whereSource', true); appendLikeCondition('creator', 'creator', 'whereCreator'); appendLikeCondition('logistics_name', 'logistics_name', 'whereLogisticsName'); appendLikeCondition('item_part', 'item_part', 'whereItemPart'); @@ -1367,6 +1446,218 @@ class WaveService extends OrderBaseService { }; } + /** + * 解析拣货任务列表分页参数。 + * + * 兼容 current/size 写法,并复用通用分页归一化能力。 + * + * @param {Object} data 请求参数。 + * @return {{ page: number, pageSize: number }} 归一化分页。 + */ + normalizeWavePickTaskListPagination(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const pagination = this.isPlainObject(normalizedData.pagination) + ? normalizedData.pagination + : normalizedData; + + const pageSource = pagination.page ?? pagination.page_no ?? pagination.pageNo ?? pagination.current; + const pageSizeSource = pagination.pageSize ?? pagination.page_size ?? pagination.size; + + return this.normalizePagination({ + page: pageSource, + pageSize: pageSizeSource, + }); + } + + /** + * 归一化拣货任务列表请求参数。 + * + * 兼容顶层筛选参数与 where 结构并保持旧调用可用: + * - 顶层支持 warehouse_id/status/source/keyword/task_no + * - 同名字段优先使用顶层值覆盖 where + * - warehouse_id 未传时回退当前仓库上下文 + * + * @param {Object} data 请求参数。 + * @return {{ warehouseId: number, where: Object }} 归一化仓库与查询条件。 + */ + normalizeWavePickTaskListRequest(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const baseWhere = this.isPlainObject(requestData.where) ? { ...requestData.where } : {}; + + const mergeFieldFromTopLevel = fieldName => { + if (Object.prototype.hasOwnProperty.call(requestData, fieldName)) { + baseWhere[fieldName] = requestData[fieldName]; + } + }; + + [ + 'status', + 'source', + 'keyword', + 'task_no', + 'pick_mode', + 'review_status', + 'pick_user_id', + 'review_user_id', + 'cart_id', + 'start_time_start', + 'start_time_end', + ].forEach(mergeFieldFromTopLevel); + + const contextWarehouseId = Number(this.getWarehouseId() || 0); + const inputWarehouseId = requestData.warehouse_id ?? requestData.warehouseId; + const warehouseId = inputWarehouseId !== undefined && inputWarehouseId !== null && inputWarehouseId !== '' + ? Number(inputWarehouseId) + : contextWarehouseId; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('warehouse_id 参数不合法'); + } + + if (Number.isInteger(contextWarehouseId) + && contextWarehouseId > 0 + && inputWarehouseId !== undefined + && inputWarehouseId !== null + && inputWarehouseId !== '' + && warehouseId !== contextWarehouseId) { + throw new Error('warehouse_id 与当前仓库上下文不一致'); + } + + return { + warehouseId, + where: baseWhere, + }; + } + + /** + * 构建拣货任务列表 where 条件(白名单字段)。 + * + * 注意:当前 wms_wave_pick_task 主表未落 strategy_id 字段, + * 因此 strategy_id 过滤入参会被忽略,不参与 SQL 条件拼接。 + * + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 + */ + buildWavePickTaskListWhereClause(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + const allowedFields = [ + 'status', + 'review_status', + 'pick_mode', + 'source', + 'strategy_id', + 'pick_user_id', + 'review_user_id', + 'task_no', + 'cart_id', + 'keyword', + 'start_time_start', + 'start_time_end', + ]; + + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const conditions = []; + const replacements = {}; + + const appendIntegerEqualCondition = (fieldKey, columnName, replacementKey, allowZero = true) => { + const value = normalizedWhere[fieldKey]; + if (value === undefined || value === null || value === '') { + return; + } + + const numberValue = Number(value); + const isValid = Number.isInteger(numberValue) && (allowZero ? numberValue >= 0 : numberValue > 0); + if (!isValid) { + throw new Error(`${fieldKey} 参数不合法`); + } + + conditions.push(`${columnName} = :${replacementKey}`); + replacements[replacementKey] = numberValue; + }; + + const status = normalizedWhere.status; + if (Array.isArray(status)) { + const normalizedStatusList = [ ...new Set(status + .map(value => Number(value)) + .filter(value => Number.isInteger(value) && value >= 0)) ]; + if (normalizedStatusList.length <= 0) { + throw new Error('status 参数不合法'); + } + + conditions.push('t.status IN (:whereStatusList)'); + replacements.whereStatusList = normalizedStatusList; + } else { + appendIntegerEqualCondition('status', 't.status', 'whereStatus'); + } + appendIntegerEqualCondition('review_status', 't.review_status', 'whereReviewStatus'); + appendIntegerEqualCondition('pick_mode', 't.pick_mode', 'wherePickMode', false); + appendIntegerEqualCondition('source', 't.source', 'whereSource', false); + appendIntegerEqualCondition('pick_user_id', 't.pick_user_id', 'wherePickUserId'); + appendIntegerEqualCondition('review_user_id', 't.review_user_id', 'whereReviewUserId'); + appendIntegerEqualCondition('cart_id', 't.current_cart_id', 'whereCartId', false); + + const taskNo = normalizedWhere.task_no; + if (taskNo !== undefined && taskNo !== null && taskNo !== '') { + const normalizedTaskNo = String(taskNo).trim(); + if (!normalizedTaskNo) { + throw new Error('task_no 参数不合法'); + } + + conditions.push('t.task_no LIKE :whereTaskNo'); + replacements.whereTaskNo = `%${normalizedTaskNo}%`; + } + + const keyword = normalizedWhere.keyword; + if (keyword !== undefined && keyword !== null && keyword !== '') { + const normalizedKeyword = String(keyword).trim(); + if (!normalizedKeyword) { + throw new Error('keyword 参数不合法'); + } + + conditions.push(`( + t.task_no LIKE :whereKeyword + OR t.pick_user_name LIKE :whereKeyword + OR t.review_user_name LIKE :whereKeyword + OR t.batch_no LIKE :whereKeyword + )`); + replacements.whereKeyword = `%${normalizedKeyword}%`; + } + + const startTimeStart = normalizedWhere.start_time_start; + if (startTimeStart !== undefined && startTimeStart !== null && startTimeStart !== '') { + const normalizedStartTimeStart = String(startTimeStart).trim(); + const startDate = new Date(normalizedStartTimeStart); + if (!normalizedStartTimeStart || Number.isNaN(startDate.getTime())) { + throw new Error('start_time_start 参数不合法'); + } + + conditions.push('t.create_time >= :whereCreateTimeStart'); + replacements.whereCreateTimeStart = normalizedStartTimeStart; + } + + const startTimeEnd = normalizedWhere.start_time_end; + if (startTimeEnd !== undefined && startTimeEnd !== null && startTimeEnd !== '') { + const normalizedStartTimeEnd = String(startTimeEnd).trim(); + const endDate = new Date(normalizedStartTimeEnd); + if (!normalizedStartTimeEnd || Number.isNaN(endDate.getTime())) { + throw new Error('start_time_end 参数不合法'); + } + + conditions.push('t.create_time <= :whereCreateTimeEnd'); + replacements.whereCreateTimeEnd = normalizedStartTimeEnd; + } + + return { + sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', + replacements, + }; + } + /** * 解析分配状态。 * @@ -1504,6 +1795,34 @@ class WaveService extends OrderBaseService { .join(' | '); } + /** + * 构建订单商品快照字符串。 + * + * 输出格式:商品名称1*数量|商品名称2*数量。 + * + * @param {Array} itemDetails 商品明细列表。 + * @return {string} 商品快照字符串。 + */ + buildOrderItemSnapshot(itemDetails = []) { + if (!Array.isArray(itemDetails) || itemDetails.length === 0) { + return ''; + } + + const segments = itemDetails + .map(item => { + const itemName = String(item && (item.item_name || item.item_code) || '').trim(); + const quantity = Number(item && item.quantity || 0); + if (!itemName || !Number.isFinite(quantity) || quantity <= 0) { + return ''; + } + + return `${itemName}*${quantity}`; + }) + .filter(Boolean); + + return segments.join('|'); + } + buildItemSnapshotKey(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; @@ -2048,6 +2367,1221 @@ class WaveService extends OrderBaseService { }); } + /** + * 查询当前仓库波次策略列表。 + * + * 仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} 波次策略列表及分页信息。 + */ + async waveStrategyList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const rawType = requestData.strategy_type ?? requestData?.where?.strategy_type; + let normalizedStrategyType; + if (rawType !== undefined && rawType !== null && `${rawType}` !== '') { + normalizedStrategyType = Number(rawType); + if (![ 1, 2 ].includes(normalizedStrategyType)) { + throw new Error('strategy_type 仅支持 1(散单) 或 2(团购)'); + } + } + const calculateNextFetchOrderCount = Number( + requestData.calculate_next_fetch_order_count ?? requestData.calculateNextFetchOrderCount ?? 0 + ) === 1; + const { page, pageSize } = this.normalizePagination(requestData); + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.findAndCountAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const offset = (page - 1) * pageSize; + const where = { + warehouse_id: contextWarehouseId, + }; + if (normalizedStrategyType !== undefined) { + where.strategy_type = normalizedStrategyType; + } + + const queryResult = await strategyModel.findAndCountAll({ + where, + order: [ + [ 'status', 'DESC' ], + [ 'id', 'DESC' ], + ], + offset, + limit: pageSize, + raw: true, + }); + + const list = Array.isArray(queryResult && queryResult.rows) ? queryResult.rows : []; + const strategyIds = [ ...new Set(list + .map(item => Number(item && item.id || 0)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + const matchedOrderCountMap = await this.getWaveStrategyMatchedOrderCountFilteredMap( + contextWarehouseId, + strategyIds + ); + const nextFetchOrderCountMap = calculateNextFetchOrderCount + ? await this.getWaveStrategyNextFetchOrderCountMap(contextWarehouseId, list) + : new Map(); + const mergedList = list.map(item => { + const strategyId = Number(item && item.id || 0); + return { + ...item, + matched_order_count_filtered: Number( + matchedOrderCountMap.get(strategyId) || 0 + ), + next_fetch_order_count: calculateNextFetchOrderCount + ? Number(nextFetchOrderCountMap.get(strategyId) || 0) + : 0, + }; + }); + const total = Number(queryResult && queryResult.count || 0); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + + return this.success('ok', { + list: mergedList, + pagination: { + page, + pageSize, + total, + totalPages, + hasPrevious: page > 1, + hasNext: page < totalPages, + }, + }); + } + + /** + * 批量预演当前页策略“下一个抓取订单数”。 + * + * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} [strategyRows=[]] 策略行数组。 + * @return {Promise>} strategy_id 到预演订单数映射。 + */ + async getWaveStrategyNextFetchOrderCountMap(warehouseId, strategyRows = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const rows = Array.isArray(strategyRows) ? strategyRows : []; + const countMap = new Map(); + + await Promise.all(rows.map(async row => { + const strategyId = Number(row && row.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + try { + const nextFetchOrderCount = await this.previewWaveStrategyNextFetchOrderCount({ + warehouseId: normalizedWarehouseId, + strategyRow: row, + }); + countMap.set(strategyId, Number(nextFetchOrderCount || 0)); + } catch (error) { + this.ctx.logger.warn('[wave.getWaveStrategyNextFetchOrderCountMap] 预演策略抓取数量失败,降级为 0', { + warehouse_id: normalizedWarehouseId, + strategy_id: strategyId, + error: error && error.message ? error.message : `${error}`, + }); + countMap.set(strategyId, 0); + } + })); + + return countMap; + } + + /** + * 预演单个策略“下一个抓取订单数”。 + * + * 口径复用自动分流逻辑,但仅计算最终会选中的订单数量,不执行写操作。 + * + * @param {Object} [params={}] 预演参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} params.strategyRow 策略行。 + * @return {Promise} 预演可抓取订单数。 + */ + async previewWaveStrategyNextFetchOrderCount(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const strategyId = Number(strategyRow.id || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return 0; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + if (![ 1, 2 ].includes(strategyType)) { + return 0; + } + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + }); + if (candidateRows.length <= 0) { + return 0; + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + return 0; + } + + if (strategyType === 2) { + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows.slice(0, groupLimit); + const selectedOrderIds = [ ...new Set(selectedGroups + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ]; + return selectedOrderIds.length; + } + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData: {}, + strategyRow, + }); + const mergedOrderIds = [ ...new Set(groupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length <= 0) { + return 0; + } + + let selectedOrderIds = []; + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 2 || pickMode === 4) { + selectedOrderIds = mergedOrderIds; + } else { + return 0; + } + + const orderLimitRaw = Number(strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + + return limitedOrderIds.length; + } + + /** + * 按策略统计过滤后命中订单数。 + * + * 过滤口径: + * 1) 仅统计未在波次订单(wave_id = 0); + * 2) 仅统计 step != 0 的订单; + * 3) 仅统计状态有效订单(status != cancel 且 outbound_status != padding); + * 4) 同结构数量需落在策略 min_same_structure/max_same_structure 区间内。 + * + * 同结构定义沿用快速扫描口径:优先 items_hash,空时回退 items。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array} strategyIds 当前页策略ID列表。 + * @return {Promise>} strategy_id 到过滤后命中订单数的映射。 + */ + async getWaveStrategyMatchedOrderCountFilteredMap(warehouseId, strategyIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const normalizedStrategyIds = [ ...new Set((Array.isArray(strategyIds) ? strategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + if (normalizedStrategyIds.length === 0) { + return new Map(); + } + + const orderModel = await this.getOrderModel('pendingOrder', normalizedWarehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const querySql = ` + SELECT + m.strategy_id, + COUNT(DISTINCT m.order_id) AS matched_order_count_filtered + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + INNER JOIN ( + SELECT + COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE src.warehouse_id = :warehouseId + AND src.wave_id = 0 + AND src.step != 0 + AND src.post_status = 'fin' + AND src.storage_status = 'fin' + AND src.status != 'cancel' + AND src.outbound_status != 'padding' + 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, ''))) + INNER JOIN wms_wave_strategy s + ON s.id = m.strategy_id + AND s.warehouse_id = :warehouseId + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id IN (:strategyIds) + AND same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0) + AND (s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure) + GROUP BY m.strategy_id + `; + + const queryRows = await this.ctx.model.query(querySql, { + replacements: { + warehouseId: normalizedWarehouseId, + strategyIds: normalizedStrategyIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + const matchedMap = new Map(); + (Array.isArray(queryRows) ? queryRows : []).forEach(row => { + const strategyId = Number(row && row.strategy_id || 0); + const matchedCount = Number(row && row.matched_order_count_filtered || 0); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + matchedMap.set(strategyId, matchedCount); + }); + + return matchedMap; + } + + /** + * 新增波次策略。 + * + * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 新增结果。 + */ + async waveStrategyCreate(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.create !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { + warehouseId, + mode: 'create', + }); + const operator = this.getOrderLogOperator(); + const transaction = await this.ctx.model.transaction(); + let created; + try { + created = await strategyModel.create({ + ...payload, + warehouse_id: warehouseId, + creator_name: String(operator && operator.name || 'system').trim() || 'system', + }, { + transaction, + }); + + await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + const createdData = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; + + return this.success('ok', { data: createdData, code: 200 }); + } + + /** + * 修改波次策略。 + * + * warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 修改结果。 + */ + async waveStrategyUpdate(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const warehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const strategyModel = this.getWaveStrategyModel(); + if (!strategyModel || typeof strategyModel.findOne !== 'function' || typeof strategyModel.update !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyId = this.normalizeWaveStrategyId(requestData); + const payload = await this.normalizeWaveStrategyUpsertPayload(requestData, { + warehouseId, + mode: 'update', + }); + if (Object.keys(payload).length === 0) { + throw new Error('缺少可更新字段'); + } + + const operator = this.getOrderLogOperator(); + const transaction = await this.ctx.model.transaction(); + let updated; + try { + const exists = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + raw: true, + transaction, + }); + if (!exists) { + throw new Error(`波次策略不存在: ${strategyId}`); + } + + await strategyModel.update({ + ...payload, + creator_name: String(operator && operator.name || 'system').trim() || 'system', + update_time: new Date(), + }, { + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await this.bumpWaveStrategyVersionAndInvalidateCache(warehouseId, { transaction }); + + updated = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + }, + raw: true, + transaction, + }); + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return this.success('ok', { data: updated || null, code: 200 }); + } + + /** + * 递增仓库波次策略版本并失效相关缓存。 + * + * 数据更新在事务内执行;当传入事务时,缓存失效动作会在事务提交后执行。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Object} [options={}] 处理选项。 + * @param {Object} [options.transaction] Sequelize 事务对象。 + * @return {Promise} 自增后的版本号。 + */ + async bumpWaveStrategyVersionAndInvalidateCache(warehouseId, options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const { transaction } = this.isPlainObject(options) ? options : {}; + const settingWarehouseService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.setting + && this.ctx.service.systems.setting.warehouse; + const modelContainer = this.ctx.model || this.app.model || {}; + const storeModel = modelContainer.Store; + + if (!storeModel || typeof storeModel.findByPk !== 'function') { + throw new Error('Store model 不可用'); + } + + const storeQueryOptions = { + attributes: [ 'id', 'subject_config' ], + }; + if (transaction) { + storeQueryOptions.transaction = transaction; + if (transaction.LOCK && transaction.LOCK.UPDATE) { + storeQueryOptions.lock = transaction.LOCK.UPDATE; + } + } + + const store = await storeModel.findByPk(normalizedWarehouseId, storeQueryOptions); + if (!store) { + throw new Error(`仓库不存在: ${normalizedWarehouseId}`); + } + + const currentSubjectConfig = store.subject_config && typeof store.subject_config === 'object' && !Array.isArray(store.subject_config) + ? { ...store.subject_config } + : {}; + const normalizedSubjectConfig = settingWarehouseService + && typeof settingWarehouseService.normalizeSubjectConfigInternalFields === 'function' + ? settingWarehouseService.normalizeSubjectConfigInternalFields(currentSubjectConfig) + : currentSubjectConfig; + const currentVersion = settingWarehouseService + && typeof settingWarehouseService.normalizeWaveStrategyVersion === 'function' + ? settingWarehouseService.normalizeWaveStrategyVersion(normalizedSubjectConfig.wave_strategy_version, { useDefaultWhenEmpty: true }) + : Number(normalizedSubjectConfig.wave_strategy_version || 1); + + if (!Number.isSafeInteger(currentVersion) || currentVersion < 0) { + throw new Error('subject_config.wave_strategy_version 必须是非负整数'); + } + if (currentVersion >= Number.MAX_SAFE_INTEGER) { + throw new Error('subject_config.wave_strategy_version 超出安全整数范围'); + } + + const nextVersion = currentVersion + 1; + normalizedSubjectConfig.wave_strategy_version = nextVersion; + + const subjectConfigForUpdate = typeof storeModel.normalizeSubjectConfig === 'function' + ? storeModel.normalizeSubjectConfig(normalizedSubjectConfig) + : normalizedSubjectConfig; + + await store.update({ + subject_config: subjectConfigForUpdate, + }, { + ...(transaction ? { transaction } : {}), + }); + + const invalidateCache = async () => { + if (settingWarehouseService && typeof settingWarehouseService.clearWarehouseSettingCache === 'function') { + await settingWarehouseService.clearWarehouseSettingCache(normalizedWarehouseId); + } + + const deliveryOrderService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.deliveryOrder; + const subjectConfigCacheKey = deliveryOrderService + && typeof deliveryOrderService.getStoreSubjectConfigCacheKey === 'function' + ? deliveryOrderService.getStoreSubjectConfigCacheKey(normalizedWarehouseId) + : `delivery_order:store:${normalizedWarehouseId}:subject_config`; + + if (subjectConfigCacheKey) { + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(subjectConfigCacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(subjectConfigCacheKey, null, 0); + } + } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; + if (this.app && typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(strategyCacheKey); + } else if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, null, 0); + } + + setImmediate(() => { + this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId) + .then(scanPayload => { + this.ctx.logger.info('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描成功', { + warehouseId: normalizedWarehouseId, + taskId: String(scanPayload && scanPayload.task_id || '').trim(), + state: String(scanPayload && scanPayload.state || '').trim(), + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.bumpWaveStrategyVersionAndInvalidateCache] 异步触发全量扫描失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); + }; + + if (transaction && typeof transaction.afterCommit === 'function') { + transaction.afterCommit(async () => { + await invalidateCache(); + }); + } else { + await invalidateCache(); + } + + return nextVersion; + } + + /** + * 获取波次策略模型。 + * + * @return {Object|null} 模型对象。 + */ + getWaveStrategyModel() { + return this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + } + + /** + * 归一化波次策略主键。 + * + * @param {Object} data 请求参数。 + * @return {number} 策略主键。 + */ + normalizeWaveStrategyId(data = {}) { + const rawId = data && (data.id ?? data.strategy_id ?? data.strategyId); + return this.normalizeRequiredPositiveInteger(rawId, 'id'); + } + + /** + * 归一化波次策略新增/修改入参并执行统一校验。 + * + * @param {Object} data 请求参数。 + * @param {Object} options 处理选项。 + * @param {number} options.warehouseId 当前仓库ID。 + * @param {string} options.mode 模式:create/update。 + * @return {Promise} 可直接写库的载荷。 + */ + async normalizeWaveStrategyUpsertPayload(data = {}, options = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const mode = String(options && options.mode || '').trim().toLowerCase(); + const warehouseId = Number(options && options.warehouseId || 0); + const payload = {}; + + if (mode === 'create') { + const strategyName = String(requestData.strategy_name || '').trim(); + if (!strategyName) { + throw new Error('strategy_name 参数不能为空'); + } + payload.strategy_name = strategyName; + payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; + } else { + throw new Error('batch_mode 参数不能为空'); + } + } else { + if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_name')) { + const strategyName = String(requestData.strategy_name || '').trim(); + if (!strategyName) { + throw new Error('strategy_name 参数不能为空'); + } + payload.strategy_name = strategyName; + } + if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_type')) { + payload.strategy_type = this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type'); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_mode')) { + payload.batch_mode = this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode'); + } else if (payload.strategy_type === 2) { + payload.batch_mode = 0; + } + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'status')) { + const normalizedStatus = Number(requestData.status); + if (![ 0, 1 ].includes(normalizedStatus)) { + throw new Error('status 参数不合法,仅支持 0 或 1'); + } + payload.status = normalizedStatus; + } + + this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_sku'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_sku'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_min_qty'); + this.patchWaveStrategyIntegerField(payload, requestData, 'order_max_qty'); + this.patchWaveStrategyIntegerField(payload, requestData, 'min_same_structure'); + this.patchWaveStrategyIntegerField(payload, requestData, 'max_same_structure'); + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_orders')) { + const rawBatchMaxOrders = requestData.batch_max_orders; + if (rawBatchMaxOrders === null || rawBatchMaxOrders === '') { + payload.batch_max_orders = null; + } else { + payload.batch_max_orders = this.normalizePositiveInteger(rawBatchMaxOrders, 'batch_max_orders'); + } + } + const resolvedStrategyType = Object.prototype.hasOwnProperty.call(payload, 'strategy_type') + ? payload.strategy_type + : Object.prototype.hasOwnProperty.call(requestData, 'strategy_type') + ? this.normalizeRequiredPositiveInteger(requestData.strategy_type, 'strategy_type') + : null; + if (resolvedStrategyType === 2) { + payload.batch_max_orders = 0; + } + const resolvedBatchMode = Object.prototype.hasOwnProperty.call(payload, 'batch_mode') + ? payload.batch_mode + : Object.prototype.hasOwnProperty.call(requestData, 'batch_mode') + ? this.normalizePositiveInteger(requestData.batch_mode, 'batch_mode') + : null; + if (resolvedBatchMode === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'batch_max_skus')) { + const rawBatchMaxSkus = requestData.batch_max_skus; + if (rawBatchMaxSkus === null || rawBatchMaxSkus === '') { + payload.batch_max_skus = null; + } else { + payload.batch_max_skus = this.normalizePositiveInteger(rawBatchMaxSkus, 'batch_max_skus'); + } + } + } else { + payload.batch_max_skus = 0; + } + if (resolvedStrategyType !== null && resolvedStrategyType !== 2) { + payload.group_batch_max_orders = 0; + } else if (resolvedStrategyType === 2) { + if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } + } else if (Object.prototype.hasOwnProperty.call(requestData, 'group_batch_max_orders')) { + const rawGroupBatchMaxOrders = requestData.group_batch_max_orders; + if (rawGroupBatchMaxOrders === null || rawGroupBatchMaxOrders === '') { + payload.group_batch_max_orders = null; + } else { + payload.group_batch_max_orders = this.normalizePositiveInteger(rawGroupBatchMaxOrders, 'group_batch_max_orders'); + } + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'require_same_express')) { + payload.require_same_express = this.normalizeBoolean(requestData.require_same_express, false); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allow_cross_owner')) { + payload.allow_cross_owner = this.normalizeBoolean(requestData.allow_cross_owner, true); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'description')) { + payload.description = String(requestData.description || '').trim(); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { + payload.allowed_provinces = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); + } + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_platforms')) { + payload.allowed_platforms = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_platforms); + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_owners')) { + const allowedOwners = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_owners); + await this.validateWaveStrategyAllowedOwners(allowedOwners, warehouseId); + payload.allowed_owners = allowedOwners; + } + + if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_expresses')) { + const allowedExpresses = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_expresses); + await this.validateWaveStrategyAllowedExpresses(allowedExpresses); + payload.allowed_expresses = allowedExpresses; + } + + await this.applyWaveStrategyMaxSameStructureConstraint(payload, warehouseId); + + delete payload.warehouse_id; + delete payload.creator; + delete payload.creator_name; + + return payload; + } + + /** + * 按字段补丁方式归一化波次策略正整数参数。 + * + * @param {Object} payload 输出载荷。 + * @param {Object} requestData 原始请求。 + * @param {string} fieldName 字段名。 + */ + patchWaveStrategyIntegerField(payload = {}, requestData = {}, fieldName = '') { + if (!Object.prototype.hasOwnProperty.call(requestData, fieldName)) { + return; + } + + const rawValue = requestData[fieldName]; + if (rawValue === null || rawValue === '') { + payload[fieldName] = null; + return; + } + + payload[fieldName] = this.normalizeRequiredPositiveInteger(rawValue, fieldName); + } + + /** + * 校验 allowed_owners 是否在系统可用货主范围内。 + * + * @param {Array} ownerList 货主列表。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 无返回值。 + */ + async validateWaveStrategyAllowedOwners(ownerList = [], warehouseId = 0) { + const normalizedOwners = Array.isArray(ownerList) + ? ownerList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) + : []; + if (normalizedOwners.length === 0) { + return; + } + + const availableOwnerSet = await this.getWaveStrategyAvailableOwnerSet(warehouseId); + const illegalOwners = normalizedOwners.filter(item => !availableOwnerSet.has(item)); + + if (illegalOwners.length > 0) { + throw new Error(`allowed_owners 存在非法值: ${illegalOwners.join(', ')}`); + } + } + + /** + * 校验 allowed_expresses 是否在系统可用快递范围内。 + * + * @param {Array} expressList 快递编码列表。 + * @return {Promise} 无返回值。 + */ + async validateWaveStrategyAllowedExpresses(expressList = []) { + const normalizedExpresses = Array.isArray(expressList) + ? expressList.map(item => String(item || '').trim().toLowerCase()).filter(Boolean) + : []; + if (normalizedExpresses.length === 0) { + return; + } + + const availableExpressSet = await this.getWaveStrategyAvailableExpressSet(); + const illegalExpresses = normalizedExpresses.filter(item => !availableExpressSet.has(item)); + + if (illegalExpresses.length > 0) { + throw new Error(`allowed_expresses 存在非法值: ${illegalExpresses.join(', ')}`); + } + } + + /** + * 获取当前仓库可用货主集合。 + * + * 优先复用 systems.store.loadStores,若不可用则回退查询签约表。 + * + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise>} 货主集合(小写字符串)。 + */ + async getWaveStrategyAvailableOwnerSet(warehouseId = 0) { + const availableSet = new Set(); + const storeService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.store; + + if (storeService && typeof storeService.loadStores === 'function') { + const rows = await storeService.loadStores(); + for (const row of Array.isArray(rows) ? rows : []) { + const ownerId = String(row && (row.value ?? row.store_id) || '').trim().toLowerCase(); + if (ownerId) { + availableSet.add(ownerId); + } + } + } + + if (availableSet.size > 0) { + return availableSet; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function') { + return availableSet; + } + + const rows = await storeWarehouseModel.findAll({ + attributes: [ 'store_id' ], + where: { + warehouse_id: normalizedWarehouseId, + use_status: 1, + }, + raw: true, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const ownerId = String(row && row.store_id || '').trim().toLowerCase(); + if (ownerId) { + availableSet.add(ownerId); + } + } + + return availableSet; + } + + /** + * 获取当前仓库可用快递编码集合。 + * + * 优先复用 systems.express.getExpressList,若不可用则回退系统快递表。 + * + * @return {Promise>} 快递编码集合(小写字符串)。 + */ + async getWaveStrategyAvailableExpressSet() { + const availableSet = new Set(); + const expressService = this.ctx.service + && this.ctx.service.systems + && this.ctx.service.systems.express; + + if (expressService && typeof expressService.getExpressList === 'function') { + const rows = await expressService.getExpressList(); + for (const row of Array.isArray(rows) ? rows : []) { + const code = String(row && (row.code || row.value) || '').trim().toLowerCase(); + if (code) { + availableSet.add(code); + } + } + } + + if (availableSet.size > 0) { + return availableSet; + } + + const expressModel = this.ctx.model && this.ctx.model.Express; + if (!expressModel || typeof expressModel.findAll !== 'function') { + return availableSet; + } + + const rows = await expressModel.findAll({ + attributes: [ 'code' ], + order: [[ 'code', 'ASC' ]], + raw: true, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const code = String(row && row.code || '').trim().toLowerCase(); + if (code) { + availableSet.add(code); + } + } + + return availableSet; + } + + /** + * 按仓库最小团购抓取量约束 max_same_structure。 + * + * 当 min_group_order_fetch_quantity 为有效正整数且 + * max_same_structure >= min_group_order_fetch_quantity 时, + * 自动下调为 min_group_order_fetch_quantity - 1,且最小保持为 1。 + * + * @param {Object} payload 目标写库载荷。 + * @param {number} warehouseId 当前仓库ID。 + * @return {Promise} 无返回值。 + */ + async applyWaveStrategyMaxSameStructureConstraint(payload = {}, warehouseId = 0) { + if (!Object.prototype.hasOwnProperty.call(payload, 'max_same_structure')) { + return; + } + + const maxSameStructure = payload.max_same_structure; + if (maxSameStructure === null || maxSameStructure === undefined || maxSameStructure === '') { + return; + } + + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return; + } + + const subjectConfig = await this.getWarehouseSubjectConfig(normalizedWarehouseId); + const minGroupOrderFetchQuantity = Number( + this.getWarehouseSubjectConfigValue(subjectConfig, 'min_group_order_fetch_quantity') + ); + if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) { + return; + } + + const normalizedMaxSameStructure = Number(maxSameStructure); + if (!Number.isInteger(normalizedMaxSameStructure) || normalizedMaxSameStructure <= 0) { + throw new Error('max_same_structure 参数必须为正整数'); + } + + if (normalizedMaxSameStructure >= minGroupOrderFetchQuantity) { + payload.max_same_structure = Math.max(minGroupOrderFetchQuantity - 1, 1); + } + } + + /** + * 校验并标准化兜底订单列表 where 白名单字段。 + * + * 仅允许与波次策略过滤直接相关的字段;对兼容别名做统一映射, + * 例如 delivery_no -> delivery_order_code、tracking_no -> express_numbers。 + * + * @param {Object} whereData 原始 where 入参。 + * @return {Object} 标准化后的 where 条件。 + */ + normalizeWaveStrategyFallbackOrderListWhere(whereData = {}) { + const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; + const whereKeys = Object.keys(normalizedWhere); + + if (whereKeys.includes('warehouse_id') || whereKeys.includes('warehouseId')) { + throw new Error('where 中禁止传入 warehouse_id 或 warehouseId'); + } + + const allowedFields = Object.keys(WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP); + const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); + if (invalidFields.length > 0) { + throw new Error(`where 存在不支持的字段: ${invalidFields.join(',')}`); + } + + const hasStoreName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'store_name'); + const hasOwnerName = Object.prototype.hasOwnProperty.call(normalizedWhere, 'owner_name'); + if (hasStoreName && hasOwnerName) { + throw new Error('store_name 与 owner_name 不能同时传入,请保留一个货主名称字段'); + } + + const rangeOperatorMap = Object.freeze({ + items_count_min: 'ge', + items_count_max: 'le', + items_total_min: 'ge', + items_total_max: 'le', + }); + const mappedWhere = {}; + for (const field of allowedFields) { + if (!Object.prototype.hasOwnProperty.call(normalizedWhere, field)) { + continue; + } + + if (Object.prototype.hasOwnProperty.call(rangeOperatorMap, field)) { + const rawValue = normalizedWhere[field]; + const value = this.isPlainObject(rawValue) && Object.prototype.hasOwnProperty.call(rawValue, 'value') + ? rawValue.value + : rawValue; + mappedWhere[field] = { + operator: rangeOperatorMap[field], + field: WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field], + value, + }; + continue; + } + + mappedWhere[WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP[field]] = normalizedWhere[field]; + } + + return mappedWhere; + } + + /** + * 解析兜底订单列表中的快递号展示值。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 快递号。 + */ + resolveWaveStrategyFallbackTrackingNo(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const directTrackingNo = String(orderRow.tracking_no || '').trim(); + if (directTrackingNo) { + return directTrackingNo; + } + + const expressNumbers = Array.isArray(orderRow.express_numbers) + ? orderRow.express_numbers + : Array.isArray(orderRow.waybill_codes) + ? orderRow.waybill_codes + : []; + const normalizedExpressNumbers = expressNumbers + .map(item => String(item || '').trim()) + .filter(Boolean); + + if (normalizedExpressNumbers.length > 0) { + return normalizedExpressNumbers[0]; + } + + const expressNumbersText = String(orderRow.express_numbers || '').trim(); + if (expressNumbersText) { + return expressNumbersText.split(',').map(item => item.trim()).filter(Boolean)[0] || null; + } + + return null; + } + + /** + * 解析兜底订单列表中的货主名称展示值。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 货主名称。 + */ + resolveWaveStrategyFallbackStoreName(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const candidateList = [ + orderRow.store_name, + orderRow.owner_name, + orderRow.shop_nick, + orderRow.seller_nick, + ]; + + for (const candidate of candidateList) { + const normalizedValue = String(candidate || '').trim(); + if (normalizedValue) { + return normalizedValue; + } + } + + return null; + } + + /** + * 解析兜底订单列表中的系统快递名称。 + * + * @param {Object} orderRow 订单行。 + * @return {string|null} 系统快递名称。 + */ + resolveWaveStrategyFallbackSysLogisticsName(orderRow = {}) { + if (!this.isPlainObject(orderRow)) { + return null; + } + + const candidateList = [ orderRow.sys_logistics_name, orderRow.logistics_name ]; + for (const candidate of candidateList) { + const normalizedValue = String(candidate || '').trim(); + if (normalizedValue) { + return normalizedValue; + } + } + + return null; + } + + /** + * 构建兜底订单列表单行输出,仅保留波次策略相关字段。 + * + * @param {Object} orderRow 原始订单行。 + * @param {string} itemSnapshot 商品快照文本。 + * @return {Object} 裁剪后的订单行。 + */ + buildWaveStrategyFallbackOrderListItem(orderRow = {}, itemSnapshot = '') { + const normalizedOrderRow = this.isPlainObject(orderRow) ? orderRow : {}; + + return { + id: normalizedOrderRow.id ?? null, + delivery_no: normalizedOrderRow.delivery_no ?? normalizedOrderRow.delivery_order_code ?? null, + tracking_no: this.resolveWaveStrategyFallbackTrackingNo(normalizedOrderRow), + items_count: normalizedOrderRow.items_count ?? null, + items_total: normalizedOrderRow.items_total ?? null, + sys_logistics_name: this.resolveWaveStrategyFallbackSysLogisticsName(normalizedOrderRow), + store_name: this.resolveWaveStrategyFallbackStoreName(normalizedOrderRow), + province: normalizedOrderRow.province ?? null, + sys_platform_name: normalizedOrderRow.sys_platform_name ?? null, + item_snapshot: String(itemSnapshot || ''), + }; + } + + /** + * 查询兜底不符合波次策略的订单列表。 + * + * 直接复用订单通用列表能力,返回标准 list/pagination 结构。 + * 在当前页订单上增补 item_snapshot(格式:商品名称1*数量|商品名称2*数量)。 + * + * @param {Object} data 请求参数。 + * @param {Object} data.pagination 分页参数。 + * @param {Object} data.where 查询条件。 + * @param {Object} data.sort 排序参数。 + * @return {Promise} 列表查询结果。 + */ + async waveStrategyFallbackOrderList(data = {}) { + const requestData = this.isPlainObject(data) ? data : {}; + const { pagination, where, sort } = requestData; + const normalizedPagination = this.normalizePagination(pagination || {}); + const normalizedWhere = this.normalizeWaveStrategyFallbackOrderListWhere(where); + const listResult = await this.listByModule('waveStrategyFallbackOrder', { + ...requestData, + pagination: normalizedPagination, + where: normalizedWhere, + sort, + }); + const normalizedResult = this.isPlainObject(listResult) ? listResult : {}; + const sourceList = Array.isArray(normalizedResult.list) ? normalizedResult.list : []; + const orderIds = sourceList + .map(item => Number(item && item.id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + const warehouseId = Number(this.getWarehouseId() || 0); + const itemSnapshotMap = new Map(); + + if (orderIds.length > 0 && Number.isInteger(warehouseId) && warehouseId > 0) { + try { + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + const hasValidModel = orderItemsModel && typeof orderItemsModel.findAll === 'function'; + const hasOpIn = Op && Object.prototype.hasOwnProperty.call(Op, 'in'); + + if (hasValidModel && hasOpIn) { + const orderItemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const orderItemsMap = new Map(); + for (const row of orderItemRows || []) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!orderItemsMap.has(orderId)) { + orderItemsMap.set(orderId, []); + } + orderItemsMap.get(orderId).push(row); + } + + for (const orderId of orderIds) { + const itemRows = orderItemsMap.get(orderId) || []; + const itemDetails = this.mergeOrderItemDetails(itemRows); + itemSnapshotMap.set(orderId, this.buildOrderItemSnapshot(itemDetails)); + } + } + } catch (error) { + this.ctx.logger && this.ctx.logger.warn && this.ctx.logger.warn('[wave.waveStrategyFallbackOrderList] 回填 item_snapshot 失败,已降级为空字符串', { + warehouseId, + orderCount: orderIds.length, + error: error && error.message ? error.message : `${error}`, + }); + } + } + + const list = sourceList.map(item => { + const orderId = Number(item && item.id || 0); + return this.buildWaveStrategyFallbackOrderListItem(item, itemSnapshotMap.get(orderId) || ''); + }); + + return this.success('ok', { + ...normalizedResult, + list, + }); + } + /** * 波次列表查询。 * @@ -2089,6 +3623,7 @@ class WaveService extends OrderBaseService { total_orders, processed_orders, distinguish_express, + source, logistics_name, item_snapshot_key, warehouse_id, @@ -2126,6 +3661,7 @@ class WaveService extends OrderBaseService { wb.total_orders, wb.processed_orders, wb.distinguish_express, + wb.source, wb.logistics_name, wb.item_snapshot_key, wb.warehouse_id, @@ -2270,6 +3806,7 @@ class WaveService extends OrderBaseService { item_part_type: String(batch && batch.item_part_type || '').trim(), item_part: String(batch && batch.item_part || '').trim(), distinguish_express: Number(batch && batch.distinguish_express || 0), + source: Number(batch && batch.source || 0), logistics_name: String(batch && batch.logistics_name || '').trim(), item_snapshot_key: String(batch && batch.item_snapshot_key || '').trim(), warehouse_id: Number(batch && batch.warehouse_id || 0), @@ -2300,6 +3837,133 @@ class WaveService extends OrderBaseService { }); } + /** + * 拣货任务列表查询。 + * + * 基于 wms_wave_pick_task 主表按当前仓库维度分页查询,默认按 create_time 倒序。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} [data.page] 页码(兼容 current)。 + * @param {number|string} [data.pageSize] 每页数量(兼容 size/page_size)。 + * @param {Object} [data.where] 查询过滤。 + * @return {Promise} 列表与分页结果。 + */ + async wavePickTaskList(data = {}) { + try { + const requestData = this.isPlainObject(data) ? data : {}; + const { page, pageSize } = this.normalizeWavePickTaskListPagination(requestData); + const normalizedRequest = this.normalizeWavePickTaskListRequest(requestData); + const warehouseId = normalizedRequest.warehouseId; + const whereClause = this.buildWavePickTaskListWhereClause(normalizedRequest.where); + const offset = (page - 1) * pageSize; + + const listSql = ` + SELECT + t.id, + t.task_no, + t.warehouse_id, + t.pick_mode, + t.status, + t.review_status, + t.source, + t.wave_count, + t.order_count, + t.box_count, + t.pick_user_id, + t.pick_user_name, + t.review_user_id, + t.review_user_name, + t.current_cart_id, + t.current_cart_code_snapshot, + t.batch_no, + t.device_id, + t.start_time, + t.finish_time, + t.review_start_time, + t.review_finish_time, + t.create_time, + t.update_time + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + ORDER BY t.create_time DESC + LIMIT :limit OFFSET :offset + `; + + const countSql = ` + SELECT COUNT(1) AS total + FROM wms_wave_pick_task t + WHERE t.warehouse_id = :warehouseId + ${whereClause.sql} + `; + + const replacements = { + warehouseId, + ...whereClause.replacements, + }; + + const [ listRows, countRows ] = await Promise.all([ + this.ctx.model.query(listSql, { + replacements: { + ...replacements, + limit: pageSize, + offset, + }, + }), + this.ctx.model.query(countSql, { + replacements, + }), + ]); + + const sourceList = Array.isArray(listRows && listRows[0]) ? listRows[0] : []; + const totalRowList = Array.isArray(countRows && countRows[0]) ? countRows[0] : []; + const total = Number(totalRowList[0] && totalRowList[0].total || 0); + + const list = sourceList.map(item => ({ + task_id: Number(item && item.id || 0), + task_no: String(item && item.task_no || '').trim(), + warehouse_id: Number(item && item.warehouse_id || 0), + pick_mode: Number(item && item.pick_mode || 0), + status: Number(item && item.status || 0), + review_status: Number(item && item.review_status || 0), + source: Number(item && item.source || 0), + wave_count: Number(item && item.wave_count || 0), + order_count: Number(item && item.order_count || 0), + box_count: Number(item && item.box_count || 0), + pick_user_id: Number(item && item.pick_user_id || 0), + pick_user_name: String(item && item.pick_user_name || '').trim(), + operator_id: Number(item && item.pick_user_id || 0), + operator_name: String(item && item.pick_user_name || '').trim(), + review_user_id: Number(item && item.review_user_id || 0), + review_user_name: String(item && item.review_user_name || '').trim(), + current_cart_id: Number(item && item.current_cart_id || 0), + current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(), + batch_no: String(item && item.batch_no || '').trim(), + device_id: String(item && item.device_id || '').trim(), + start_time: item && item.start_time || null, + start_at: item && item.start_time || null, + finish_time: item && item.finish_time || null, + finish_at: item && item.finish_time || null, + review_start_time: item && item.review_start_time || null, + review_finish_time: item && item.review_finish_time || null, + create_time: item && item.create_time || null, + created_at: item && item.create_time || null, + update_time: item && item.update_time || null, + })); + + return this.success('ok', { + list, + total, + page, + page_size: pageSize, + }); + } catch (error) { + const errorMessage = String(error && error.message || '').trim(); + const isBadRequest = /参数|上下文/.test(errorMessage); + return this.fail(`查询拣货任务列表失败: ${errorMessage || '未知错误'}`, isBadRequest ? 400 : 500); + } + } + /** * 批量解除波次任务提交接口。 * @@ -2335,6 +3999,22 @@ class WaveService extends OrderBaseService { throw new Error('wave_ids 参数不能为空或格式错误'); } + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1, 2) + LIMIT 1`, + { + replacements: { waveIds: normalizedWaveIds }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + const requestedTaskId = this.normalizeBatchCancelTaskId(data); const taskId = requestedTaskId || this.generateBatchCancelTaskId(warehouseId); const existingTask = await this.getBatchCancelTaskProgress(taskId); @@ -2345,7 +4025,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -2391,7 +4071,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', + message: '批量解除波次任务已提交。', accepted_at: acceptedAt, }); } @@ -2542,7 +4222,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -2596,7 +4276,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', + message: '批量分配快递任务已提交。', accepted_at: acceptedAt, }); } catch (error) { @@ -2722,7 +4402,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -2773,7 +4453,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', + message: '批量分配储位任务已提交。', accepted_at: acceptedAt, }); } @@ -2882,6 +4562,1245 @@ class WaveService extends OrderBaseService { return this.success('ok', payload); } + /** + * 按仓库提交波次策略快速扫描异步任务。 + * + * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接复用已有任务。 + * + * @param {number|string} [warehouseId=0] 仓库ID,未传时优先使用上下文仓库ID。 + * @param {Object} [options={}] 提交选项。 + * @param {Array|number|string} [options.orderIds] 可选订单ID数组。 + * @return {Promise} 任务受理结果(plain object)。 + */ + async submitWaveStrategyQuickScanForWarehouse(warehouseId = 0, options = {}) { + const normalizedWarehouseId = Number(warehouseId || this.getWarehouseId() || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + + const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId); + if (runningTask && runningTask.task_id) { + const existingTaskId = String(runningTask.task_id || '').trim(); + const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); + const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; + + if (![ 'success', 'failed' ].includes(existingState)) { + return { + task_id: existingTaskId, + warehouse_id: normalizedWarehouseId, + state: existingState, + message: '已有快速扫描任务在运行中。请稍后重试或查询现有任务进度。', + accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), + }; + } + + await this.clearWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, existingTaskId); + } + + const taskId = this.generateWaveStrategyQuickScanTaskId(normalizedWarehouseId); + const acceptedAt = new Date().toISOString(); + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { + warehouse_id: normalizedWarehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + start_time: null, + end_time: null, + ...(orderIds.length > 0 ? { order_ids: orderIds } : {}), + error: '', + error_code: '', + result: null, + }); + + await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, { + state: 'submitted', + accepted_at: acceptedAt, + }); + + setImmediate(() => { + this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId: normalizedWarehouseId, + ...(orderIds.length > 0 ? { orderIds } : {}), + }).catch(error => { + this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { + taskId, + warehouseId: normalizedWarehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); + + return { + task_id: taskId, + warehouse_id: normalizedWarehouseId, + state: 'submitted', + message: '快速扫描任务已提交。', + accepted_at: acceptedAt, + }; + } + + /** + * 提交波次策略快速扫描异步任务。 + * + * 同一仓库同一时刻仅允许一个任务运行,若命中运行中任务则直接返回已有 task_id。 + * + * @return {Promise} 任务受理结果。 + */ + async waveStrategyQuickScan() { + const contextWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); + + return this.success('ok', { + status: 'success', + ...submitPayload, + }); + } + + /** + * 查询波次策略快速扫描任务进度。 + * + * @param {Object} [data={}] 请求参数。 + * @param {string} data.task_id 任务ID(下划线写法)。 + * @param {string} data.taskId 任务ID(驼峰写法)。 + * @return {Promise} 任务进度信息。 + */ + async waveStrategyQuickScanTaskProgress(data = {}) { + const taskId = this.normalizeWaveStrategyQuickScanTaskId(data); + if (!taskId) { + return this.fail('task_id 参数不能为空', 400); + } + + const cachedProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId); + if (!cachedProgress) { + return this.success('ok', { + task_id: taskId, + state: 'not_found', + }); + } + + return this.success('ok', { + task_id: taskId, + state: String(cachedProgress.state || 'submitted').trim() || 'submitted', + warehouse_id: Number(cachedProgress.warehouse_id || 0), + total_order_count: Number(cachedProgress.total_order_count || 0), + processed_order_count: Number(cachedProgress.processed_order_count || 0), + matched_order_count: Number(cachedProgress.matched_order_count || 0), + unmatched_order_count: Number(cachedProgress.unmatched_order_count || 0), + progress_percent: Number(cachedProgress.progress_percent || 0), + submitted_at: cachedProgress.submitted_at || null, + start_time: cachedProgress.start_time || null, + end_time: cachedProgress.end_time || null, + error_message: String(cachedProgress.error || '').trim(), + error_code: String(cachedProgress.error_code || '').trim(), + duration_ms: Number(cachedProgress.duration_ms || 0), + }); + } + + /** + * 构建快速扫描订单查询条件。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} strategyVersion 当前策略版本号。 + * @param {Array} [orderIds=[]] 限定扫描订单ID数组。 + * @return {Object} 订单查询 where 条件。 + */ + buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = []) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + const where = { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: strategyVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }; + + if (normalizedOrderIds.length > 0) { + where.id = { + [Op.in]: normalizedOrderIds, + }; + } + + return where; + } + + /** + * 获取快速扫描可用策略行(带缓存)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 策略原始行数组。 + */ + async getWaveStrategyQuickScanStrategyRows(warehouseId) { + const strategyModel = this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + if (!strategyModel || typeof strategyModel.findAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyCacheKey = `${WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX}${warehouseId}`; + const cachedStrategyRows = this.app && typeof this.app.getCacheAsync === 'function' + ? await this.app.getCacheAsync(strategyCacheKey) + : null; + if (Array.isArray(cachedStrategyRows)) { + return cachedStrategyRows; + } + + const strategyRows = await strategyModel.findAll({ + where: { + warehouse_id: warehouseId, + status: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + if (this.app && typeof this.app.setCacheAsync === 'function') { + await this.app.setCacheAsync(strategyCacheKey, strategyRows, WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS); + } + + return strategyRows; + } + + /** + * 获取波次策略快速扫描命中副表模型。 + * + * @return {Object|null} 命中副表模型;若不可用返回 null。 + */ + getWaveStrategyQuickScanMatchModel() { + const modelContext = this.ctx && this.ctx.model; + if (!modelContext || typeof modelContext !== 'object') { + return null; + } + + return modelContext.wms_order_wave_strategy_match + || modelContext.OrderWaveStrategyMatch + || modelContext.WmsOrderWaveStrategyMatch + || null; + } + + /** + * 同步快速扫描命中策略到副表(先删后写)。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 扫描范围订单ID。 + * @param {Object} [matchedStrategyIdsByOrder={}] 订单命中策略映射。 + * @return {Promise} 无返回值。 + */ + async syncWaveStrategyQuickScanMatchedStrategies(warehouseId, orderIds = [], matchedStrategyIdsByOrder = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function' || typeof matchModel.bulkCreate !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + } + + const normalizedMatchedMap = this.isPlainObject(matchedStrategyIdsByOrder) + ? matchedStrategyIdsByOrder + : {}; + const orderScopeSet = new Set(normalizedOrderIds); + const dedupeSet = new Set(); + const createTime = this.getCurrentDateTime ? this.getCurrentDateTime() : new Date(); + const rows = []; + + Object.keys(normalizedMatchedMap).forEach(orderKey => { + const orderId = Number(orderKey); + if (!Number.isInteger(orderId) || orderId <= 0 || !orderScopeSet.has(orderId)) { + return; + } + + const strategyIds = Array.isArray(normalizedMatchedMap[orderKey]) + ? normalizedMatchedMap[orderKey] + : []; + strategyIds.forEach(strategyIdItem => { + const strategyId = Number(strategyIdItem); + if (!Number.isInteger(strategyId) || strategyId <= 0) { + return; + } + + const dedupeKey = `${orderId}:${strategyId}`; + if (dedupeSet.has(dedupeKey)) { + return; + } + dedupeSet.add(dedupeKey); + + rows.push({ + warehouse_id: normalizedWarehouseId, + order_id: orderId, + strategy_id: strategyId, + create_time: createTime, + }); + }); + }); + + for (let i = 0; i < rows.length; i += 500) { + const rowChunk = rows.slice(i, i + 500); + await matchModel.bulkCreate(rowChunk); + } + } + + /** + * 清理波次策略快速扫描命中副表过期数据。 + * + * @param {Object} [options={}] 清理参数。 + * @param {number|string} [options.expireHours=24] 过期小时数。 + * @param {number|string} [options.warehouseId] 可选仓库ID。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategies(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const expireHoursRaw = Number(normalizedOptions.expireHours); + const expireHours = Number.isFinite(expireHoursRaw) && expireHoursRaw > 0 ? expireHoursRaw : 24; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const expireAt = new Date(Date.now() - Math.floor(expireHours * 60 * 60 * 1000)); + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + const where = { + create_time: { + [Op.lt]: expireAt, + }, + }; + + if (Number.isInteger(warehouseId) && warehouseId > 0) { + where.warehouse_id = warehouseId; + } + + const deletedCount = await matchModel.destroy({ where }); + return Number(deletedCount || 0); + } + + /** + * 按仓库 + 订单ID集合清理波次策略快速扫描命中副表数据。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @return {Promise} 删除条数。 + */ + async cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds(warehouseId = 0, orderIds = []) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return 0; + } + + const matchModel = this.getWaveStrategyQuickScanMatchModel(); + if (!matchModel || typeof matchModel.destroy !== 'function') { + throw new Error('波次策略命中副表模型不可用'); + } + + let totalDeletedCount = 0; + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const orderChunk = normalizedOrderIds.slice(i, i + 500); + if (orderChunk.length === 0) { + continue; + } + + const deletedCount = await matchModel.destroy({ + where: { + warehouse_id: normalizedWarehouseId, + order_id: { [Op.in]: orderChunk }, + }, + }); + totalDeletedCount += Number(deletedCount || 0); + } + + return totalDeletedCount; + } + + /** + * 异步处理订单变更后的波次策略快速扫描副表清理与触发。 + * + * @param {number|string} [warehouseId=0] 仓库ID。 + * @param {Array|number|string} [orderIds=[]] 订单ID集合。 + * @param {Object} [options={}] 处理选项。 + * @param {boolean} [options.triggerScan=false] 是否触发快速扫描。 + * @param {string} [options.source=''] 调用来源。 + * @return {void} 无返回值。 + */ + enqueueWaveStrategyQuickScanPostOrderChange(warehouseId = 0, orderIds = [], options = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const triggerScan = this.normalizeBoolean(normalizedOptions.triggerScan, false); + const source = String(normalizedOptions.source || '').trim(); + + setImmediate(() => { + Promise.resolve() + .then(async () => { + const deletedCount = await this.cleanupWaveStrategyQuickScanMatchedStrategiesByOrderIds( + normalizedWarehouseId, + normalizedOrderIds + ); + + if (triggerScan) { + await this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId, { + orderIds: normalizedOrderIds, + }); + } + + this.ctx.logger.info('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理完成', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + deletedCount, + triggerScan, + source, + }); + }) + .catch(error => { + this.ctx.logger.warn('[wave.enqueueWaveStrategyQuickScanPostOrderChange] 异步处理失败,不影响主流程', { + warehouseId: normalizedWarehouseId, + orderCount: normalizedOrderIds.length, + triggerScan, + source, + error: error && error.message ? error.message : `${error}`, + }); + }); + }); + } + + /** + * 执行快速扫描核心流程。 + * + * @param {Object} [options={}] 执行参数。 + * @param {number} options.warehouseId 仓库ID。 + * @param {number} options.strategyVersion 当前策略版本。 + * @param {Array} [options.orderIds] 可选订单ID数组。 + * @param {string} [options.taskId] 任务ID。 + * @return {Promise} 扫描执行结果。 + */ + async executeWaveStrategyQuickScan(options = {}) { + const normalizedOptions = this.isPlainObject(options) ? options : {}; + const warehouseId = Number(normalizedOptions.warehouseId || 0); + const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion); + const taskId = String(normalizedOptions.taskId || '').trim(); + const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds); + + const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ + 'id', + 'store_id', + 'items_count', + 'items_total', + 'items_hash', + 'items', + 'logistics_code', + 'sys_logistics_code', + 'logistics_name', + 'province', + 'sys_platform_code', + 'source_platform_code', + ], + where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds), + raw: true, + }); + + const scanResult = await runWaveStrategyQuickScanRunner({ + orders: orderRows, + strategyList, + getStructureKey: order => this.getWaveStrategyQuickScanStructureKey(order), + getExpressKey: order => this.getWaveStrategyQuickScanExpressKey(order), + getMatchedStrategyIds: (order, normalizedStrategyList, context) => this.getWaveStrategyQuickScanMatchedStrategyIds( + order, + normalizedStrategyList, + context + ), + isOrderMatched: (order, normalizedStrategyList, context) => this.isWaveStrategyQuickScanOrderMatched( + order, + normalizedStrategyList, + context + ), + onProgress: taskId + ? async payload => { + const totalOrderCount = Number(payload && payload.totalOrderCount || 0); + const processedOrderCount = Number(payload && payload.processedOrderCount || 0); + const matchedOrderCount = Number(payload && payload.matchedOrderCount || 0); + const unmatchedOrderCount = Number(payload && payload.unmatchedOrderCount || 0); + + const progressPercent = totalOrderCount > 0 + ? Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)) + : 0; + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + matched_order_count: matchedOrderCount, + unmatched_order_count: unmatchedOrderCount, + progress_percent: progressPercent, + }); + } + : null, + }); + + const matchedOrderIds = this.normalizeIdsInput(scanResult.matchedOrderIds); + const unmatchedOrderIds = this.normalizeIdsInput(scanResult.unmatchedOrderIds); + const matchedStrategyIdsByOrder = this.isPlainObject(scanResult.matchedStrategyIdsByOrder) + ? Object.keys(scanResult.matchedStrategyIdsByOrder).reduce((acc, key) => { + const orderId = Number(key); + if (!Number.isInteger(orderId) || orderId <= 0) { + return acc; + } + + const rawStrategyIds = scanResult.matchedStrategyIdsByOrder[key]; + const normalizedStrategyIds = [ ...new Set((Array.isArray(rawStrategyIds) ? rawStrategyIds : []) + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0)) ]; + acc[orderId] = normalizedStrategyIds; + return acc; + }, {}) + : {}; + const scanScopeOrderIds = orderIds.length > 0 + ? orderIds + : [ ...new Set([ ...matchedOrderIds, ...unmatchedOrderIds ]) ]; + + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 1, + }); + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 2, + }); + await this.syncWaveStrategyQuickScanMatchedStrategies( + warehouseId, + scanScopeOrderIds, + matchedStrategyIdsByOrder + ); + + return { + strategyVersion, + totalOrderCount: Number(scanResult.totalOrderCount || 0), + processedOrderCount: Number(scanResult.processedOrderCount || 0), + matchedOrderCount: matchedOrderIds.length, + unmatchedOrderCount: unmatchedOrderIds.length, + matchedOrderIds, + unmatchedOrderIds, + matchedStrategyIdsByOrder, + }; + } + + /** + * 执行波次策略快速扫描后台任务。 + * + * 扫描范围:当前仓库 + step != 0 + wave_id = 0 + wave_strategy_version != 当前策略版本。 + * + * @param {Object} [params={}] 任务参数。 + * @param {string} params.taskId 任务ID。 + * @param {number|string} [params.warehouseId] 仓库ID。 + * @param {Array} [params.orderIds] 订单ID数组(驼峰写法)。 + * @param {Array} [params.order_ids] 订单ID数组(下划线写法)。 + * @param {Array} [params.ids] 订单ID数组(兼容写法)。 + * @return {Promise} 无返回值。 + */ + async runWaveStrategyQuickScanTask(params = {}) { + const normalizedTaskId = String(params && params.taskId || '').trim(); + if (!normalizedTaskId) { + throw new Error('taskId 不能为空'); + } + + const cachedTask = await this.getWaveStrategyQuickScanTaskProgress(normalizedTaskId); + const warehouseId = Number( + cachedTask && cachedTask.warehouse_id !== undefined + ? cachedTask.warehouse_id + : params && params.warehouseId + ); + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { + end_time: Date.now(), + error: 'warehouse_id 参数不合法', + error_code: 'INVALID_WAREHOUSE_ID', + }); + return; + } + + const startTime = Date.now(); + await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId, { + state: 'running', + }); + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + start_time: startTime, + end_time: null, + error: '', + error_code: '', + result: null, + }); + + try { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const rawOrderIds = normalizedParams.orderIds !== undefined + ? normalizedParams.orderIds + : normalizedParams.order_ids !== undefined + ? normalizedParams.order_ids + : normalizedParams.ids; + const orderIds = this.normalizeIdsInput(rawOrderIds); + + const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId); + const strategyVersion = this.normalizeWaveStrategyQuickScanVersion( + this.getWarehouseSubjectConfigValue(subjectConfig, 'wave_strategy_version') + ); + + const scanResult = await this.executeWaveStrategyQuickScan({ + warehouseId, + strategyVersion, + orderIds, + taskId: normalizedTaskId, + }); + + if (scanResult.totalOrderCount === 0) { + const durationMs = Date.now() - startTime; + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + strategy_version: strategyVersion, + duration_ms: durationMs, + message: '未找到需要扫描的订单', + }, + }); + return; + } + + const durationMs = Date.now() - startTime; + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { + warehouse_id: warehouseId, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, + progress_percent: 100, + end_time: Date.now(), + duration_ms: durationMs, + result: { + strategy_version: strategyVersion, + total_order_count: scanResult.totalOrderCount, + processed_order_count: scanResult.processedOrderCount, + matched_order_count: scanResult.matchedOrderCount, + unmatched_order_count: scanResult.unmatchedOrderCount, + matched_order_ids: scanResult.matchedOrderIds, + unmatched_order_ids: scanResult.unmatchedOrderIds, + duration_ms: durationMs, + message: '波次策略快速扫描完成', + }, + }); + } catch (error) { + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'failed', { + warehouse_id: warehouseId, + progress_percent: 0, + end_time: Date.now(), + duration_ms: Date.now() - startTime, + error: error && error.message ? error.message : `${error}`, + error_code: 'WAVE_STRATEGY_QUICK_SCAN_FAILED', + }); + } finally { + await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, normalizedTaskId); + } + } + + /** + * 批量更新快速扫描结果。 + * + * @param {Object} orderModel 订单模型。 + * @param {Array} orderIds 订单ID数组。 + * @param {Object} updatePayload 更新字段。 + * @return {Promise} 无返回值。 + */ + async batchUpdateWaveStrategyQuickScanOrders(orderModel, orderIds = [], updatePayload = {}) { + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (normalizedOrderIds.length === 0) { + return; + } + + for (let i = 0; i < normalizedOrderIds.length; i += 500) { + const chunkIds = normalizedOrderIds.slice(i, i + 500); + if (chunkIds.length === 0) { + continue; + } + + await orderModel.update(updatePayload, { + where: { + id: { + [Op.in]: chunkIds, + }, + }, + }); + } + } + + /** + * 生成波次策略快速扫描任务ID。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 任务ID。 + */ + generateWaveStrategyQuickScanTaskId(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + const safeWarehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0 + ? normalizedWarehouseId + : 0; + const timestamp = Math.floor(Date.now() / 1000); + const randomPart = Math.random().toString(36).slice(2, 6); + return `wave_quick_scan_${safeWarehouseId}_${timestamp}_${randomPart}`; + } + + /** + * 归一化波次策略快速扫描任务ID。 + * + * @param {Object} [data={}] 请求参数。 + * @return {string} 归一化后的任务ID。 + */ + normalizeWaveStrategyQuickScanTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取波次策略快速扫描任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getWaveStrategyQuickScanTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入波次策略快速扫描任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {string} state 任务状态。 + * @param {Object} payload 进度数据。 + * @return {Promise} 无返回值。 + */ + async setWaveStrategyQuickScanTaskProgress(taskId = '', state = 'submitted', payload = {}) { + const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); + if (!cacheKey) { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const mergedPayload = { + ...(await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}), + ...safePayload, + task_id: String(taskId || '').trim(), + state: String(state || '').trim() || 'submitted', + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, mergedPayload, WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入任务进度缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取波次策略快速扫描任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 缓存对象。 + */ + async getWaveStrategyQuickScanTaskProgress(taskId = '') { + const cacheKey = this.getWaveStrategyQuickScanTaskCacheKey(taskId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取任务进度缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 获取波次策略快速扫描仓库锁缓存键。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {string} 缓存键。 + */ + getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId = 0) { + const normalizedWarehouseId = Number(warehouseId || 0); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + return ''; + } + + return `${WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX}${normalizedWarehouseId}`; + } + + /** + * 写入波次策略快速扫描仓库锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} taskId 任务ID。 + * @param {Object} [extra={}] 附加字段。 + * @return {Promise} 无返回值。 + */ + async setWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '', extra = {}) { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + const normalizedTaskId = String(taskId || '').trim(); + if (!cacheKey || !normalizedTaskId) { + return; + } + + const extraPayload = this.isPlainObject(extra) ? extra : {}; + const lockPayload = { + warehouse_id: Number(warehouseId || 0), + task_id: normalizedTaskId, + state: String(extraPayload.state || 'running').trim() || 'running', + accepted_at: extraPayload.accepted_at || undefined, + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, lockPayload, WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 写入仓库锁缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取波次策略快速扫描仓库锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @return {Promise} 锁信息。 + */ + async getWaveStrategyQuickScanWarehouseLock(warehouseId = 0) { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + if (!cacheKey) { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + + return cached; + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 读取仓库锁缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } + + /** + * 清理波次策略快速扫描仓库锁。 + * + * 仅当当前锁 owner 与传入 taskId 一致时才删除,防止误删并发任务锁。 + * + * @param {number|string} warehouseId 仓库ID。 + * @param {string} [taskId=''] 当前任务ID。 + * @return {Promise} 无返回值。 + */ + async clearWaveStrategyQuickScanWarehouseLock(warehouseId = 0, taskId = '') { + const cacheKey = this.getWaveStrategyQuickScanWarehouseLockCacheKey(warehouseId); + if (!cacheKey) { + return; + } + + try { + const cachedLock = await this.app.getCacheAsync(cacheKey); + const lockTaskId = String(cachedLock && cachedLock.task_id || '').trim(); + const currentTaskId = String(taskId || '').trim(); + if (lockTaskId && currentTaskId && lockTaskId !== currentTaskId) { + return; + } + + if (typeof this.app.delCacheAsync === 'function') { + await this.app.delCacheAsync(cacheKey); + } else { + await this.app.setCacheAsync(cacheKey, null, 0); + } + } catch (error) { + this.ctx.logger.warn('[wave.waveStrategyQuickScan] 清理仓库锁缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 将仓库策略版本号归一化为非负整数。 + * + * @param {*} value 原始版本号。 + * @return {number} 归一化版本号。 + */ + normalizeWaveStrategyQuickScanVersion(value) { + const versionNumber = Number(value); + if (!Number.isFinite(versionNumber)) { + return 0; + } + + const safeVersion = Math.floor(versionNumber); + return Number.isInteger(safeVersion) && safeVersion >= 0 ? safeVersion : 0; + } + + /** + * 归一化快速扫描策略列表。 + * + * @param {*} strategyRows 策略行数组。 + * @return {Array} 标准化策略列表。 + */ + normalizeWaveStrategyQuickScanList(strategyRows) { + const list = Array.isArray(strategyRows) ? strategyRows : []; + return list.map(row => { + const normalizedRow = this.isPlainObject(row) ? row : {}; + const strategyId = Number(normalizedRow.strategy_id || normalizedRow.strategyId || normalizedRow.id || 0); + return { + strategy_id: Number.isInteger(strategyId) && strategyId > 0 ? strategyId : null, + order_min_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_sku), + order_max_sku: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_sku), + order_min_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_min_qty), + order_max_qty: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.order_max_qty), + min_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.min_same_structure), + max_same_structure: this.normalizeWaveStrategyQuickScanNumberOrNull(normalizedRow.max_same_structure), + allowed_owners: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_owners), + allowed_expresses: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_expresses), + allowed_provinces: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_provinces), + allowed_platforms: this.normalizeWaveStrategyQuickScanStringList(normalizedRow.allowed_platforms), + require_same_express: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.require_same_express, false), + allow_cross_owner: this.normalizeWaveStrategyQuickScanBoolean(normalizedRow.allow_cross_owner, true), + }; + }); + } + + /** + * 归一化为可为空的数值。 + * + * @param {*} value 原始数值。 + * @return {number|null} 数值或 null。 + */ + normalizeWaveStrategyQuickScanNumberOrNull(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return null; + } + + return normalizedValue; + } + + /** + * 归一化快速扫描布尔值。 + * + * @param {*} value 原始值。 + * @param {boolean} [defaultValue=false] 默认值。 + * @return {boolean} 布尔值。 + */ + normalizeWaveStrategyQuickScanBoolean(value, defaultValue = false) { + if (typeof value === 'boolean') { + return value; + } + + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalizedValue = String(value).trim().toLowerCase(); + if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalizedValue)) { + return true; + } + if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalizedValue)) { + return false; + } + + return defaultValue; + } + + /** + * 归一化快速扫描字符串数组。 + * + * 支持数组、JSON 字符串、逗号分隔字符串。 + * + * @param {*} value 原始值。 + * @return {Array} 归一化字符串数组(小写去重)。 + */ + normalizeWaveStrategyQuickScanStringList(value) { + let rawList = []; + + if (Array.isArray(value)) { + rawList = value; + } else if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + rawList = []; + } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) { + try { + const parsed = JSON.parse(trimmed); + rawList = Array.isArray(parsed) ? parsed : []; + } catch (error) { + rawList = trimmed.split(/[,,;|\n\r]+/); + } + } else { + rawList = trimmed.split(/[,,;|\n\r]+/); + } + } else if (value !== undefined && value !== null) { + rawList = [ value ]; + } + + return [ ...new Set(rawList + .map(item => String(item || '').trim().toLowerCase()) + .filter(Boolean)) ]; + } + + /** + * 计算订单结构 key(items_hash 优先,其次 items)。 + * + * @param {Object} order 订单记录。 + * @return {string} 结构 key。 + */ + getWaveStrategyQuickScanStructureKey(order = {}) { + const itemsHash = String(order && order.items_hash || '').trim(); + if (itemsHash) { + return itemsHash; + } + + return String(order && order.items || '').trim(); + } + + /** + * 计算订单快递 key(同快递判定仅使用 sys_logistics_code)。 + * + * @param {Object} order 订单记录。 + * @return {string} 快递 key(sys_logistics_code 去首尾空格后结果,空值返回空字符串)。 + */ + getWaveStrategyQuickScanExpressKey(order = {}) { + return String(order && order.sys_logistics_code || '').trim(); + } + + /** + * 判断订单是否命中任一快速扫描策略。 + * + * @param {Object} order 订单记录。 + * @param {Array} strategyList 策略列表。 + * @param {Object} context 统计上下文。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanOrderMatched(order = {}, strategyList = [], context = {}) { + const matchedStrategyIds = this.getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context); + return matchedStrategyIds.length > 0; + } + + /** + * 获取订单命中的快速扫描策略ID列表。 + * + * 全量遍历 strategyList,不提前返回,收集所有命中策略的 strategy_id。 + * + * @param {Object} order 订单记录。 + * @param {Array} strategyList 策略列表。 + * @param {Object} [context={}] 统计上下文。 + * @return {Array} 去重后的正整数策略ID列表。 + */ + getWaveStrategyQuickScanMatchedStrategyIds(order, strategyList, context = {}) { + const list = Array.isArray(strategyList) ? strategyList : []; + if (list.length === 0) { + return []; + } + + const matchedStrategyIds = []; + for (const strategy of list) { + if (!this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { + continue; + } + + const strategyId = Number(strategy && strategy.strategy_id || 0); + if (Number.isInteger(strategyId) && strategyId > 0) { + matchedStrategyIds.push(strategyId); + } + } + + return [ ...new Set(matchedStrategyIds) ]; + } + + /** + * 判断订单是否命中单条快速扫描策略。 + * + * @param {Object} order 订单记录。 + * @param {Object} strategy 策略配置。 + * @param {Object} context 统计上下文。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanOrderMatchedSingleStrategy(order = {}, strategy = {}, context = {}) { + const normalizedOrder = this.isPlainObject(order) ? order : {}; + const normalizedStrategy = this.isPlainObject(strategy) ? strategy : {}; + const structureStoreSetMap = context && context.structureStoreSetMap instanceof Map ? context.structureStoreSetMap : new Map(); + const structurePrimaryExpressMap = context && context.structurePrimaryExpressMap instanceof Map + ? context.structurePrimaryExpressMap + : null; + const structurePrimaryOwnerMap = context && context.structurePrimaryOwnerMap instanceof Map + ? context.structurePrimaryOwnerMap + : null; + + const structureKey = this.getWaveStrategyQuickScanStructureKey(normalizedOrder); + if (!structureKey) { + return false; + } + + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); + + if (normalizedStrategy.allow_cross_owner === false) { + if (structurePrimaryOwnerMap instanceof Map) { + const primaryOwnerStoreId = String(structurePrimaryOwnerMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryOwnerStoreId || storeId !== primaryOwnerStoreId) { + return false; + } + } else { + const ownerSet = structureStoreSetMap.get(structureKey); + if (ownerSet instanceof Set && ownerSet.size > 1) { + return false; + } + } + } + + if (normalizedStrategy.require_same_express === true && structurePrimaryExpressMap instanceof Map) { + const primaryExpressKey = String(structurePrimaryExpressMap.get(structureKey) || '').trim().toLowerCase(); + if (!primaryExpressKey) { + return false; + } + + const currentExpressKey = String(this.getWaveStrategyQuickScanExpressKey(normalizedOrder) || '').trim().toLowerCase(); + if (currentExpressKey !== primaryExpressKey) { + return false; + } + } + + const itemsCount = Number(normalizedOrder.items_count || 0); + const itemsTotal = Number(normalizedOrder.items_total || 0); + + if (!this.isWaveStrategyQuickScanValueInRange(itemsCount, normalizedStrategy.order_min_sku, normalizedStrategy.order_max_sku)) { + return false; + } + if (!this.isWaveStrategyQuickScanValueInRange(itemsTotal, normalizedStrategy.order_min_qty, normalizedStrategy.order_max_qty)) { + return false; + } + + if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { + return false; + } + + const expressCandidates = [ + String(normalizedOrder.sys_logistics_code || '').trim().toLowerCase(), + String(normalizedOrder.logistics_code || '').trim().toLowerCase(), + String(normalizedOrder.logistics_name || '').trim().toLowerCase(), + ].filter(Boolean); + if (normalizedStrategy.allowed_expresses.length > 0) { + const hitExpress = expressCandidates.some(code => normalizedStrategy.allowed_expresses.includes(code)); + if (!hitExpress) { + return false; + } + } + + const province = String(normalizedOrder.province || '').trim().toLowerCase(); + if (normalizedStrategy.allowed_provinces.length > 0 && !normalizedStrategy.allowed_provinces.includes(province)) { + return false; + } + + const platformCandidates = [ + String(normalizedOrder.sys_platform_code || '').trim().toLowerCase(), + String(normalizedOrder.source_platform_code || '').trim().toLowerCase(), + ].filter(Boolean); + if (normalizedStrategy.allowed_platforms.length > 0) { + const hitPlatform = platformCandidates.some(code => normalizedStrategy.allowed_platforms.includes(code)); + if (!hitPlatform) { + return false; + } + } + + return true; + } + + /** + * 判断值是否命中区间。 + * + * @param {number} value 待判断值。 + * @param {number|null} min 最小值。 + * @param {number|null} max 最大值。 + * @return {boolean} 是否命中。 + */ + isWaveStrategyQuickScanValueInRange(value, min, max) { + const normalizedValue = Number(value); + if (!Number.isFinite(normalizedValue)) { + return false; + } + + const hasMin = Number.isFinite(Number(min)); + const hasMax = Number.isFinite(Number(max)); + if (hasMin && normalizedValue < Number(min)) { + return false; + } + if (hasMax && normalizedValue > Number(max)) { + return false; + } + + return true; + } + /** * 过滤 singleFetchByIds 中属于团购候选结构的订单。 * @@ -2990,7 +5909,7 @@ class WaveService extends OrderBaseService { * 1. 仅处理当前仓库上下文订单; * 2. 传入 ids 中已存在波次(wave_id>0)的订单会被排除; * 3. 不区分快递,所有可抓取订单统一写入同一个新波次; - * 4. 仅抓取待处理订单(step in [1,2,3])且未取消、未进入出库中的订单; + * 4. 除已在波次中的订单外,其余传入且存在的订单均可抓取; * 5. 成功抓取后批量写入订单操作日志。 * * @param {Object} data 请求参数。 @@ -3019,6 +5938,7 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const transaction = await this.ctx.model.transaction(); try { @@ -3046,9 +5966,6 @@ class WaveService extends OrderBaseService { const fetchableRows = normalizedOrderRows.filter(row => { const orderId = Number(row && row.id || 0); const waveId = Number(row && row.wave_id || 0); - const step = Number(row && row.step || 0); - const status = String(row && row.status || '').trim(); - const outboundStatus = String(row && row.outbound_status || '').trim(); if (!Number.isInteger(orderId) || orderId <= 0) { return false; @@ -3058,32 +5975,10 @@ class WaveService extends OrderBaseService { return false; } - if (![ 1, 2, 3 ].includes(step)) { - return false; - } - - if (status === 'cancel') { - return false; - } - - if (outboundStatus === 'padding') { - return false; - } - return true; }); - const groupCandidateOrderIds = await this.resolveGroupCandidateOrderIdsForSingleFetch( - orderModel, - warehouseId, - fetchableRows - ); - const fetchableRowsAfterGroupFilter = fetchableRows.filter(row => { - const orderId = Number(row && row.id || 0); - return !groupCandidateOrderIds.includes(orderId); - }); - - const fetchableOrderIds = [ ...new Set(fetchableRowsAfterGroupFilter + const fetchableOrderIds = [ ...new Set(fetchableRows .map(row => Number(row && row.id || 0)) .filter(id => Number.isInteger(id) && id > 0)) ] .sort((a, b) => a - b); @@ -3099,22 +5994,24 @@ class WaveService extends OrderBaseService { fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, - excluded_group_order_ids: groupCandidateOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); } + const singleFetchByIdsWavePrefix = await this.getSingleFetchByIdsWavePrefix(warehouseId); + const { waveId, waveNo } = await this.createWaveBatchReady({ warehouseId, totalOrders: fetchableOrderIds.length, itemDetailMachine: `manual_single_ids_${Date.now()}`, itemPartType: 'manual_ids', itemPart: `ids_${fetchableOrderIds.length}`, + waveType: 2, distinguishExpress: false, logisticsName: '', itemSnapshotKey: 'manual_single_ids', - wavePrefix: SINGLE_FETCH_BY_IDS_WAVE_PREFIX, + wavePrefix: singleFetchByIdsWavePrefix, transaction, }); @@ -3167,7 +6064,6 @@ class WaveService extends OrderBaseService { fetched_order_ids: [], fetched_order_count: 0, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, - excluded_group_order_ids: groupCandidateOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -3198,6 +6094,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'singleFetchByIds', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { + triggerScan: false, + source: 'singleFetchByIds', + }); return this.success('ok', { ids: normalizedIds, @@ -3206,7 +6106,6 @@ class WaveService extends OrderBaseService { fetched_order_ids: grabbedOrderIds, fetched_order_count: grabbedOrderIds.length, excluded_existing_wave_order_ids: excludedExistingWaveOrderIds, - excluded_group_order_ids: groupCandidateOrderIds, skipped_order_ids: skippedOrderIds, not_found_order_ids: notFoundOrderIds, }); @@ -3252,6 +6151,37 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + + const removableRowsForCheck = await orderModel.findAll({ + attributes: [ 'wave_id' ], + where: { + id: { [Op.in]: normalizedIds }, + step: { [Op.in]: [ 1, 2, 3 ] }, + wave_id: { [Op.gt]: 0 }, + }, + raw: true, + }); + const affectedWaveIdsForCheck = [ ...new Set((Array.isArray(removableRowsForCheck) ? removableRowsForCheck : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + if (affectedWaveIdsForCheck.length > 0) { + const activeTaskWaves = await this.ctx.model.query( + `SELECT ptw.wave_id + FROM wms_wave_pick_task_wave ptw + INNER JOIN wms_wave_pick_task pt ON pt.id = ptw.task_id + WHERE ptw.wave_id IN (:waveIds) + AND pt.status IN (0, 1, 2) + LIMIT 1`, + { + replacements: { waveIds: affectedWaveIdsForCheck }, + type: this.ctx.model.QueryTypes.SELECT, + } + ); + if (activeTaskWaves.length > 0) { + throw new Error('波次属于活动拣货任务,请通过任务取消接口处理'); + } + } + const transaction = await this.ctx.model.transaction(); try { @@ -3399,6 +6329,10 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'batchRemoveOrders', }); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchRemoveOrders', + }); return this.success('ok', { ids: normalizedIds, @@ -3461,7 +6395,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已存在,请勿重复提交。', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -3510,7 +6444,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', + message: '批量移除异常订单任务已提交。', accepted_at: acceptedAt, }); } @@ -4150,6 +7084,7 @@ class WaveService extends OrderBaseService { let affectedOrderCount = 0; let canceledWaveCount = 0; const affectedWaveIds = []; + const removedOrderIdSet = new Set(); for (const wave of targetWaves) { const waveId = Number(wave.wave_id || 0); @@ -4221,6 +7156,13 @@ class WaveService extends OrderBaseService { scene: 'batchCancel', }); + const currentRemovedOrderIds = (Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0); + for (const orderId of currentRemovedOrderIds) { + removedOrderIdSet.add(orderId); + } + processedWaveCount += 1; affectedOrderCount += Number.isInteger(currentAffectedOrderCount) && currentAffectedOrderCount > 0 ? currentAffectedOrderCount @@ -4264,6 +7206,12 @@ class WaveService extends OrderBaseService { } } + const removedOrderIds = [ ...removedOrderIdSet ].sort((a, b) => a - b); + this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { + triggerScan: true, + source: 'batchCancel', + }); + const durationMs = Date.now() - startTime; await this.setBatchCancelTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, @@ -5870,6 +8818,2581 @@ class WaveService extends OrderBaseService { return this.submitFetchTask(normalizedData, 'single', maxFetchQuantity); } + /** + * 按策略与策略类型推导本次抓取的拣货模式。 + * + * 优先使用显式入参 pick_mode/pickMode,其次回退到策略字段(strategy_type、batch_mode)。 + * + * @param {Object} options 推导参数。 + * @param {Object} [options.requestData={}] 请求参数。 + * @param {Object} [options.strategyRow={}] 策略行数据。 + * @return {number} 归一化后的拣货模式(1-5,异常时为 0)。 + */ + resolveWaveStrategyFetchPickMode(options = {}) { + const requestData = this.isPlainObject(options && options.requestData) + ? options.requestData + : {}; + const strategyRow = this.isPlainObject(options && options.strategyRow) + ? options.strategyRow + : {}; + + const explicitPickMode = Number(requestData.pick_mode ?? requestData.pickMode); + if (Number.isInteger(explicitPickMode) && explicitPickMode >= 1 && explicitPickMode <= 5) { + return explicitPickMode; + } + + const strategyType = Number(strategyRow.strategy_type || 0); + const batchMode = Number(strategyRow.batch_mode || 0); + const groupBatchMaxOrders = Number(strategyRow.group_batch_max_orders || 0); + + if (strategyType === 2) { + if (groupBatchMaxOrders > 1) { + return 1; + } + return 5; + } + + if (batchMode === 1) { + return 2; + } + if (batchMode === 2) { + return 3; + } + if ([ 3, 4, 5, 6 ].includes(batchMode)) { + return 4; + } + + return 0; + } + + /** + * 构建抓取策略的框分配规则(最小可执行结构)。 + * + * @param {Object} options 构建参数。 + * @param {number} options.pickMode 拣货模式。 + * @param {Array} [options.selectedWaveIds=[]] 预抓波次ID集合。 + * @param {number} [options.boxLimit=0] 最大可用框数。 + * @return {Array} 框分配规则列表。 + */ + buildWaveStrategyFetchBoxAssignments(options = {}) { + const pickMode = Number(options && options.pickMode || 0); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const boxLimit = Number(options && options.boxLimit || 0); + + if (pickMode === 1) { + return selectedWaveIds.map((waveId, index) => ({ + wave_id: waveId, + box_no: index + 1, + rule: 'one_wave_one_box', + })); + } + + if (selectedWaveIds.length > 0) { + return [{ + wave_id: selectedWaveIds[0], + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + }]; + } + + return [{ + wave_id: null, + box_no: 1, + rule: pickMode === 5 ? 'single_wave_dynamic_append' : 'single_wave_single_box', + box_limit: Number.isInteger(boxLimit) && boxLimit > 0 ? boxLimit : 1, + }]; + } + + /** + * 策略抓取前置预处理:统一输出标准化 plan。 + * + * 仅做策略与参数预处理,不执行任务写库。 + * + * @param {Object} params 预处理入参。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Object} [params.operator={}] 操作人信息。 + * @param {string} [params.source='unknown'] 来源标识(pda/admin)。 + * @param {Object} [params.data={}] 原始请求参数。 + * @return {Promise} 标准化抓取 plan。 + */ + async prepareWaveStrategyFetchPlan(params = {}) { + const strategyId = this.normalizeRequiredPositiveInteger(params && params.strategyId, 'strategy_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params && params.warehouseId, 'warehouse_id'); + const source = String(params && params.source || 'unknown').trim() || 'unknown'; + const operator = this.isPlainObject(params && params.operator) ? params.operator : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + + const plan = { + strategy_id: strategyId, + warehouse_id: warehouseId, + source, + operator, + pick_mode: 0, + wave_limit: 0, + order_limit: 0, + sku_limit: 0, + box_limit: 0, + selected_wave_ids: [], + box_assignments: [], + dynamic_append: false, + validation_errors: [], + }; + + let strategyRows = []; + try { + strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId); + } catch (error) { + strategyRows = []; + } + + let strategyRow = (Array.isArray(strategyRows) ? strategyRows : []).find(item => { + const currentId = Number(item && (item.id ?? item.strategy_id ?? item.strategyId) || 0); + return Number.isInteger(currentId) && currentId === strategyId; + }) || null; + + if (!strategyRow) { + const strategyModel = this.getWaveStrategyModel(); + if (strategyModel && typeof strategyModel.findOne === 'function') { + const strategyEntity = await strategyModel.findOne({ + where: { + id: strategyId, + warehouse_id: warehouseId, + status: 1, + }, + raw: true, + }); + if (strategyEntity && typeof strategyEntity.get === 'function') { + strategyRow = strategyEntity.get({ plain: true }); + } else { + strategyRow = strategyEntity || null; + } + } + } + + if (!strategyRow) { + plan.validation_errors.push(`策略不存在或已停用: ${strategyId}`); + return plan; + } + + plan.strategy_type = Number(strategyRow.strategy_type || 0); + plan.strategy_row = strategyRow; + + const selectedWaveIds = this.normalizeIdsInput( + requestData.selected_wave_ids !== undefined + ? requestData.selected_wave_ids + : requestData.selectedWaveIds !== undefined + ? requestData.selectedWaveIds + : requestData.wave_ids !== undefined + ? requestData.wave_ids + : requestData.waveIds !== undefined + ? requestData.waveIds + : requestData.wave_id !== undefined + ? requestData.wave_id + : requestData.waveId + ); + plan.selected_wave_ids = selectedWaveIds; + + const pickMode = this.resolveWaveStrategyFetchPickMode({ + requestData, + strategyRow, + }); + plan.pick_mode = pickMode; + + if (![ 1, 2, 3, 4, 5 ].includes(pickMode)) { + plan.validation_errors.push('无法从策略推导有效 pick_mode,请显式传入 pick_mode(1-5)'); + } + + const rawBoxLimit = requestData.box_limit ?? requestData.boxLimit ?? strategyRow.group_batch_max_orders; + const normalizedBoxLimit = Number(rawBoxLimit); + plan.box_limit = Number.isInteger(normalizedBoxLimit) && normalizedBoxLimit > 0 ? normalizedBoxLimit : 1; + + const rawOrderLimit = requestData.order_limit ?? requestData.orderLimit ?? strategyRow.batch_max_orders; + const normalizedOrderLimit = Number(rawOrderLimit); + plan.order_limit = Number.isInteger(normalizedOrderLimit) && normalizedOrderLimit > 0 ? normalizedOrderLimit : 0; + + const rawSkuLimit = requestData.sku_limit ?? requestData.skuLimit ?? strategyRow.batch_max_skus; + const normalizedSkuLimit = Number(rawSkuLimit); + plan.sku_limit = Number.isInteger(normalizedSkuLimit) && normalizedSkuLimit > 0 ? normalizedSkuLimit : 0; + + const rawWaveLimit = requestData.wave_limit ?? requestData.waveLimit; + const normalizedWaveLimit = Number(rawWaveLimit); + if (Number.isInteger(normalizedWaveLimit) && normalizedWaveLimit > 0) { + plan.wave_limit = normalizedWaveLimit; + } else { + plan.wave_limit = pickMode === 1 ? plan.box_limit : 1; + } + + if (pickMode === 1) { + if (plan.box_limit <= 0) { + plan.validation_errors.push('小团购模式 box_limit 必须大于 0'); + } + if (selectedWaveIds.length > plan.box_limit) { + plan.validation_errors.push(`小团购模式预抓波次数(${selectedWaveIds.length})超过 box_limit(${plan.box_limit})`); + } + } + + if ([ 1, 5 ].includes(pickMode) && hasExplicitWaveSelectionInput && selectedWaveIds.length === 0) { + plan.validation_errors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 1) { + plan.validation_errors.push('单品单件/先拣后分/边拣边分模式一次仅支持一个波次'); + } + + if (pickMode === 2 && plan.order_limit <= 0) { + plan.validation_errors.push('单品单件模式 order_limit 必须大于 0'); + } + + if (pickMode === 3 && plan.sku_limit <= 0) { + plan.validation_errors.push('先拣后分模式 sku_limit 必须大于 0'); + } + + if (pickMode === 5) { + plan.dynamic_append = true; + if (selectedWaveIds.length > 1) { + plan.validation_errors.push('大团购模式一次仅支持一个波次(后续追加采用动态扫描)'); + } + } + + plan.box_assignments = this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds, + boxLimit: plan.box_limit, + }); + + return plan; + } + + /** + * 校验当前操作用户是否存在未完成任务。 + * + * 未完成状态定义:status in (0,1,2)。 + * + * @param {Object} params 校验参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.operatorId 操作用户ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensureNoActiveWavePickTaskForOperator(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const operatorId = Number(params.operatorId || 0); + const transaction = params.transaction; + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return; + } + + const rows = await this.ctx.model.query(` + SELECT id, task_no + FROM wms_wave_pick_task + WHERE warehouse_id = :warehouseId + AND pick_user_id = :operatorId + AND status IN (0, 1, 2) + ORDER BY id DESC + LIMIT 1 + FOR UPDATE + `, { + replacements: { + warehouseId, + operatorId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const activeTask = Array.isArray(rows) ? rows[0] : null; + if (activeTask) { + const taskNo = String(activeTask.task_no || '').trim(); + const taskId = Number(activeTask.id || 0); + throw new Error(`当前用户存在未完成任务,请先完成后再创建(task_id=${taskId}${taskNo ? `,task_no=${taskNo}` : ''})`); + } + } + + /** + * 查询策略自动分流候选订单(命中策略且未分配波次)。 + * + * 过滤口径:step != 0、wave_id = 0、status != cancel、outbound_status != padding, + * 并按同结构数量命中 min_same_structure/max_same_structure。 + * + * @param {Object} params 查询参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.strategyId 策略ID。 + * @param {number|string|null} [params.minSameStructure=0] 最小同结构数量。 + * @param {number|string|null} [params.maxSameStructure=null] 最大同结构数量。 + * @return {Promise>} 候选订单数组(按 order_id 升序)。 + */ + async getWaveStrategyFetchCandidateOrders(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(params.strategyId, 'strategy_id'); + const minSameStructureRaw = Number(params.minSameStructure ?? 0); + const maxSameStructureRaw = Number(params.maxSameStructure); + const minSameStructure = Number.isFinite(minSameStructureRaw) && minSameStructureRaw > 0 + ? Math.floor(minSameStructureRaw) + : 0; + const maxSameStructure = Number.isFinite(maxSameStructureRaw) && maxSameStructureRaw > 0 + ? Math.floor(maxSameStructureRaw) + : null; + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderTableName = this.getModelTableSqlName(orderModel); + const rows = await this.ctx.model.query(` + SELECT + o.id, + o.items_hash, + o.items, + o.logistics_name, + o.items_count, + o.items_total + FROM wms_order_wave_strategy_match m + INNER JOIN ${orderTableName} o + ON o.id = m.order_id + AND o.warehouse_id = :warehouseId + AND o.wave_id = 0 + AND o.step != 0 + AND o.post_status = 'fin' + AND o.storage_status = 'fin' + AND o.status != 'cancel' + AND o.outbound_status != 'padding' + INNER JOIN ( + SELECT + COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, '')), ''), TRIM(COALESCE(src.items, ''))) AS structure_key, + COUNT(1) AS same_structure_count + FROM ${orderTableName} src + WHERE src.warehouse_id = :warehouseId + AND src.wave_id = 0 + AND src.step != 0 + AND src.post_status = 'fin' + AND src.storage_status = 'fin' + AND src.status != 'cancel' + AND src.outbound_status != 'padding' + 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, ''))) + WHERE m.warehouse_id = :warehouseId + AND m.strategy_id = :strategyId + AND same_structure.same_structure_count >= :minSameStructure + AND (:maxSameStructure IS NULL OR same_structure.same_structure_count <= :maxSameStructure) + ORDER BY o.id ASC + `, { + replacements: { + warehouseId, + strategyId, + minSameStructure, + maxSameStructure, + }, + type: this.ctx.model.QueryTypes.SELECT, + }); + + return (Array.isArray(rows) ? rows : []) + .map(row => ({ + id: Number(row && row.id || 0), + items_hash: String(row && row.items_hash || '').trim(), + items: String(row && row.items || '').trim(), + logistics_name: String(row && row.logistics_name || '').trim(), + items_count: Number(row && row.items_count || 0), + items_total: Number(row && row.items_total || 0), + })) + .filter(row => Number.isInteger(row.id) && row.id > 0) + .sort((a, b) => a.id - b.id); + } + + /** + * 按订单结构对候选订单分组。 + * + * @param {Array} candidateRows 候选订单数组。 + * @return {Array} 分组结果(含 group_min_order_id)。 + */ + groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows = []) { + const groupedMap = new Map(); + const rows = Array.isArray(candidateRows) ? candidateRows : []; + + for (const row of rows) { + const structureKey = this.getWaveStrategyQuickScanStructureKey(row); + if (!structureKey) { + continue; + } + + if (!groupedMap.has(structureKey)) { + groupedMap.set(structureKey, []); + } + groupedMap.get(structureKey).push(row); + } + + return Array.from(groupedMap.entries()) + .map(([ structureKey, orders ]) => { + const sortedOrders = orders + .map(item => ({ ...item })) + .sort((a, b) => Number(a.id || 0) - Number(b.id || 0)); + const minOrderId = sortedOrders.length > 0 ? Number(sortedOrders[0].id || 0) : 0; + return { + structure_key: structureKey, + group_min_order_id: minOrderId, + orders: sortedOrders, + order_ids: sortedOrders.map(item => Number(item.id || 0)).filter(id => Number.isInteger(id) && id > 0), + }; + }) + .filter(group => group.order_ids.length > 0) + .sort((a, b) => a.group_min_order_id - b.group_min_order_id); + } + + /** + * 读取订单商品明细并构建每单 SKU 集合。 + * + * @param {Object} params 构建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @return {Promise>>} order_id 到 SKU 集合映射。 + */ + async buildWaveStrategyFetchOrderSkuMap(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + return new Map(); + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: orderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const rowMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + if (!rowMap.has(orderId)) { + rowMap.set(orderId, []); + } + rowMap.get(orderId).push(row); + } + + const skuMap = new Map(); + for (const orderId of orderIds) { + const detailRows = rowMap.get(orderId) || []; + const detailList = this.mergeOrderItemDetails(detailRows); + const skuSet = new Set(); + + detailList.forEach(item => { + const itemCode = String(item && item.item_code || '').trim(); + const stockId = Number(item && item.stock_id || 0); + if (itemCode) { + skuSet.add(itemCode); + return; + } + if (Number.isInteger(stockId) && stockId > 0) { + skuSet.add(`stock_${stockId}`); + } + }); + + skuMap.set(orderId, skuSet); + } + + return skuMap; + } + + /** + * 先拣后分模式按 SKU 上限筛选订单。 + * + * 当 SKU 种类超限时,循环剔除“出现频率最低”的 SKU, + * 每次剔除该 SKU 对应的全部订单,直到 SKU 种类满足上限。 + * + * @param {Object} params 筛选参数。 + * @param {Array} params.orderIds 候选订单ID(升序)。 + * @param {Map>} params.orderSkuMap 订单 SKU 映射。 + * @param {number|string} params.skuLimit SKU 上限。 + * @return {{ selectedOrderIds: Array, removedOrderIds: Array }} 筛选结果。 + */ + selectWaveStrategyFetchOrdersBySkuLimit(params = {}) { + const orderIds = this.normalizeIdsInput(params.orderIds || []); + const orderSkuMap = params.orderSkuMap instanceof Map ? params.orderSkuMap : new Map(); + const skuLimitRaw = Number(params.skuLimit || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + + if (orderIds.length === 0) { + return { + selectedOrderIds: [], + removedOrderIds: [], + }; + } + + if (skuLimit <= 0) { + return { + selectedOrderIds: [], + removedOrderIds: [ ...orderIds ], + }; + } + + const activeOrderSet = new Set(orderIds); + const removedOrderSet = new Set(); + + const buildSkuOrderMap = () => { + const skuOrderMap = new Map(); + for (const orderId of activeOrderSet) { + const skuSet = orderSkuMap.get(orderId) instanceof Set ? orderSkuMap.get(orderId) : new Set(); + for (const sku of skuSet) { + const skuKey = String(sku || '').trim(); + if (!skuKey) { + continue; + } + if (!skuOrderMap.has(skuKey)) { + skuOrderMap.set(skuKey, new Set()); + } + skuOrderMap.get(skuKey).add(orderId); + } + } + return skuOrderMap; + }; + + for (;;) { + const skuOrderMap = buildSkuOrderMap(); + if (skuOrderMap.size <= skuLimit) { + break; + } + + let targetSku = ''; + let minFrequency = Number.MAX_SAFE_INTEGER; + for (const [ sku, orderSet ] of skuOrderMap.entries()) { + const frequency = orderSet.size; + if (frequency < minFrequency) { + minFrequency = frequency; + targetSku = sku; + continue; + } + if (frequency === minFrequency && targetSku && String(sku).localeCompare(String(targetSku)) < 0) { + targetSku = sku; + } + } + + if (!targetSku) { + break; + } + + const targetOrderSet = skuOrderMap.get(targetSku) || new Set(); + for (const orderId of targetOrderSet) { + if (activeOrderSet.has(orderId)) { + activeOrderSet.delete(orderId); + removedOrderSet.add(orderId); + } + } + + if (activeOrderSet.size === 0) { + break; + } + } + + return { + selectedOrderIds: [ ...activeOrderSet ].sort((a, b) => a - b), + removedOrderIds: [ ...removedOrderSet ].sort((a, b) => a - b), + }; + } + + /** + * 在事务内按指定订单创建波次并更新订单波次字段。 + * + * @param {Object} params 创建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID数组。 + * @param {number|string} params.waveType 波次类型(1-团购,2-散单)。 + * @param {string} params.wavePrefix 波次前缀。 + * @param {number|string} [params.source=0] 波次来源。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise<{ waveId: number, waveNo: string, selectedOrderIds: Array }>} 创建结果。 + */ + async createWaveBatchByOrderIdsInTransaction(params = {}) { + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const waveType = Number(params.waveType || 0) === 2 ? 2 : 1; + const wavePrefix = String(params.wavePrefix || '').trim() || (waveType === 2 ? 'A' : 'B'); + const sourceInput = Number(params.source); + const source = [ 0, 1, 2 ].includes(sourceInput) ? sourceInput : 0; + const transaction = params.transaction; + const orderIds = this.normalizeIdsInput(params.orderIds || []); + if (orderIds.length === 0) { + throw new Error('创建波次失败:订单集合不能为空'); + } + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const lockRows = await orderModel.findAll({ + attributes: [ 'id', 'wave_id', 'items_hash', 'items' ], + where: { + id: { [Op.in]: orderIds }, + warehouse_id: warehouseId, + wave_id: 0, + step: { [Op.ne]: 0 }, + status: { [Op.ne]: 'cancel' }, + outbound_status: { [Op.ne]: 'padding' }, + }, + raw: true, + transaction, + lock: transaction.LOCK.UPDATE, + }); + + const fetchableOrderIds = [ ...new Set((Array.isArray(lockRows) ? lockRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (fetchableOrderIds.length === 0) { + throw new Error('创建波次失败:候选订单已被占用或状态变化'); + } + + const firstRow = Array.isArray(lockRows) ? lockRows[0] : null; + const itemPart = this.getOrderItemPart(firstRow || {}); + const itemSnapshotKey = `${itemPart.item_part_type}:${itemPart.item_part}`; + const itemDetailMachine = this.buildMachineStructureToken({ + item_part_type: itemPart.item_part_type, + item_part: itemPart.item_part, + distinguish_express: false, + logistics_name: '', + item_snapshot_key: itemSnapshotKey, + }); + + const { waveId, waveNo } = await this.createWaveBatchReady({ + warehouseId, + totalOrders: fetchableOrderIds.length, + itemDetailMachine, + itemPartType: itemPart.item_part_type, + itemPart: itemPart.item_part, + distinguishExpress: false, + logisticsName: '', + itemSnapshotKey, + wavePrefix, + waveType, + source, + transaction, + }); + + const orderFlagExpression = this.app.Sequelize.literal(`CASE + WHEN order_flag IS NULL OR order_flag = '' THEN '${WAVE_MANUAL_FETCH_FLAG}' + WHEN order_flag LIKE '%${WAVE_MANUAL_FETCH_FLAG}%' THEN order_flag + ELSE CONCAT(order_flag, ',${WAVE_MANUAL_FETCH_FLAG}') + END`); + + await orderModel.update({ + wave_id: waveId, + wave_no: waveNo, + order_flag: orderFlagExpression, + }, { + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: 0, + }, + transaction, + }); + + const grabbedRows = await orderModel.findAll({ + where: { + id: { [Op.in]: fetchableOrderIds }, + warehouse_id: warehouseId, + wave_id: waveId, + }, + attributes: [ 'id' ], + raw: true, + transaction, + }); + const grabbedOrderIds = [ ...new Set((Array.isArray(grabbedRows) ? grabbedRows : []) + .map(row => Number(row && row.id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ].sort((a, b) => a - b); + + if (grabbedOrderIds.length <= 0) { + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + }, + transaction, + }); + throw new Error('创建波次失败:未抓取到有效订单'); + } + + if (grabbedOrderIds.length !== fetchableOrderIds.length) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET total_orders = :totalOrders, + update_time = NOW() + WHERE wave_id = :waveId + `, { + replacements: { + waveId, + totalOrders: grabbedOrderIds.length, + }, + transaction, + }); + } + + return { + waveId, + waveNo, + selectedOrderIds: grabbedOrderIds, + }; + } + + /** + * 自动补齐按策略抓取的 selected_wave_ids / selected_order_ids。 + * + * 仅用于 PDA 按策略抓取场景,内部按 strategy_type + pick_mode 执行分流。 + * + * @param {Object} params 自动分流参数。 + * @param {Object} params.plan 抓取计划。 + * @param {Object} params.strategyRow 策略行。 + * @param {number|string} [params.waveBatchSource=0] 波次来源。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 自动补齐结果。 + */ + async autoPopulateWaveStrategyFetchSelections(params = {}) { + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; + const transaction = params.transaction; + const waveBatchSourceInput = Number(params.waveBatchSource); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); + const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {}; + const operatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0); + + await this.ensureNoActiveWavePickTaskForOperator({ + warehouseId, + operatorId, + transaction, + }); + + const candidateRows = await this.getWaveStrategyFetchCandidateOrders({ + warehouseId, + strategyId, + minSameStructure: strategyRow.min_same_structure, + maxSameStructure: strategyRow.max_same_structure, + }); + const candidateCount = candidateRows.length; + if (candidateCount <= 0) { + throw new Error('未找到符合策略且未分配波次的候选订单'); + } + + const groupedRows = this.groupWaveStrategyFetchCandidateOrdersByStructure(candidateRows); + if (groupedRows.length <= 0) { + throw new Error('候选订单缺少有效商品结构,无法创建波次'); + } + + const result = { + selected_wave_ids: [], + selected_order_ids: [], + removed_order_ids: [], + candidate_count: candidateCount, + grouped_count: groupedRows.length, + }; + + if (strategyType === 2) { + const groupLimitRaw = Number(strategyRow.group_batch_max_orders || plan.box_limit || 0); + const groupLimit = Number.isInteger(groupLimitRaw) && groupLimitRaw > 0 ? groupLimitRaw : 1; + const selectedGroups = groupedRows + .slice(0, groupLimit); + if (selectedGroups.length === 0) { + throw new Error('团购策略未找到可创建波次的同结构分组'); + } + + const groupWavePrefix = await this.getGroupWavePrefix(warehouseId); + for (const group of selectedGroups) { + const created = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: group.order_ids, + waveType: 1, + wavePrefix: groupWavePrefix, + source: waveBatchSource, + transaction, + }); + result.selected_wave_ids.push(created.waveId); + result.selected_order_ids.push(...created.selectedOrderIds); + } + + if (result.selected_wave_ids.length <= 0) { + throw new Error('团购策略创建波次失败:无有效波次生成'); + } + } else if (strategyType === 1) { + const mergedOrderIds = [ ...new Set(groupedRows + .flatMap(group => group.order_ids) + .map(id => Number(id || 0)) + .filter(id => Number.isInteger(id) && id > 0)) ] + .sort((a, b) => a - b); + if (mergedOrderIds.length === 0) { + throw new Error('散单策略无可用候选订单'); + } + + const orderLimitRaw = Number(plan.order_limit || strategyRow.batch_max_orders || 0); + const orderLimit = Number.isInteger(orderLimitRaw) && orderLimitRaw > 0 ? orderLimitRaw : 0; + let selectedOrderIds = []; + + if (pickMode === 3) { + const skuMap = await this.buildWaveStrategyFetchOrderSkuMap({ + warehouseId, + orderIds: mergedOrderIds, + }); + const skuLimitRaw = Number(plan.sku_limit || strategyRow.batch_max_skus || 0); + const skuLimit = Number.isInteger(skuLimitRaw) && skuLimitRaw > 0 ? skuLimitRaw : 0; + const skuResult = this.selectWaveStrategyFetchOrdersBySkuLimit({ + orderIds: mergedOrderIds, + orderSkuMap: skuMap, + skuLimit, + }); + result.removed_order_ids = skuResult.removedOrderIds; + selectedOrderIds = skuResult.selectedOrderIds; + } else if (pickMode === 4 || pickMode === 2) { + selectedOrderIds = mergedOrderIds; + } else { + throw new Error(`散单策略不支持的 pick_mode: ${pickMode}`); + } + + if (selectedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(候选可能已被剔除)'); + } + + const limitedOrderIds = orderLimit > 0 + ? selectedOrderIds.slice(0, orderLimit) + : selectedOrderIds; + if (limitedOrderIds.length <= 0) { + throw new Error('散单策略筛选后无可用订单(batch_max_orders 限制导致为空)'); + } + + const singleWavePrefix = await this.getSingleFetchByIdsWavePrefix(warehouseId); + const createdWave = await this.createWaveBatchByOrderIdsInTransaction({ + warehouseId, + orderIds: limitedOrderIds, + waveType: 2, + wavePrefix: singleWavePrefix, + source: waveBatchSource, + transaction, + }); + + result.selected_wave_ids.push(createdWave.waveId); + result.selected_order_ids.push(...createdWave.selectedOrderIds); + if (result.selected_wave_ids.length <= 0) { + throw new Error('散单策略创建波次失败:无有效波次生成'); + } + } else { + throw new Error(`不支持的策略类型: ${strategyType}`); + } + + result.selected_wave_ids = [ ...new Set(result.selected_wave_ids) ].sort((a, b) => a - b); + result.selected_order_ids = [ ...new Set(result.selected_order_ids) ].sort((a, b) => a - b); + + this.ctx.logger.info('[wave.autoPopulateWaveStrategyFetchSelections] 自动分流完成', { + strategy_id: strategyId, + warehouse_id: warehouseId, + pick_mode: pickMode, + candidate_count: result.candidate_count, + removed_count: result.removed_order_ids.length, + selected_count: result.selected_order_ids.length, + selected_wave_count: result.selected_wave_ids.length, + }); + + return result; + } + + /** + * 执行按策略抓取任务创建主流程。 + * + * 该方法在一个事务内完成任务主表、明细表、断点与日志的初始化写入。 + * + * @param {Object} params 创建参数。 + * @param {Object} params.plan 预处理后的抓取计划。 + * @param {Object} [params.data={}] 原始请求数据。 + * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务。 + * @return {Promise} 创建结果。 + */ + async createWavePickTaskFromPlan(params = {}) { + const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; + const requestData = this.isPlainObject(params && params.data) ? params.data : {}; + const autoPopulateSelections = Boolean(params && params.autoPopulateSelections); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const waveBatchSourceInput = Number( + params && params.waveBatchSource !== undefined ? params.waveBatchSource : plan.wave_batch_source + ); + const waveBatchSource = [ 0, 1, 2 ].includes(waveBatchSourceInput) ? waveBatchSourceInput : 0; + let effectivePlan = { + ...plan, + }; + let effectiveRequestData = { + ...requestData, + }; + const hasExplicitWaveSelectionInput = [ + 'selected_wave_ids', + 'selectedWaveIds', + 'wave_ids', + 'waveIds', + 'wave_id', + 'waveId', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasExplicitOrderSelectionInput = [ + 'selected_order_ids', + 'selectedOrderIds', + 'order_ids', + 'orderIds', + ].some(fieldName => Object.prototype.hasOwnProperty.call(requestData, fieldName)); + const hasManualSelectionInput = this.normalizeIdsInput(plan.selected_wave_ids || []).length > 0 + || hasExplicitWaveSelectionInput + || hasExplicitOrderSelectionInput; + + const normalizedCartId = this.normalizePositiveInteger( + effectiveRequestData.cart_id ?? effectiveRequestData.cartId, + 'cart_id', + 0 + ); + const transaction = await this.ctx.model.transaction(); + + try { + if (autoPopulateSelections && !hasManualSelectionInput) { + const autoFilled = await this.autoPopulateWaveStrategyFetchSelections({ + plan: effectivePlan, + strategyRow: effectivePlan.strategy_row, + waveBatchSource, + transaction, + }); + + effectivePlan = { + ...effectivePlan, + selected_wave_ids: autoFilled.selected_wave_ids, + box_assignments: this.buildWaveStrategyFetchBoxAssignments({ + pickMode, + selectedWaveIds: autoFilled.selected_wave_ids, + boxLimit: Number(effectivePlan.box_limit || 0), + }), + }; + effectiveRequestData = { + ...effectiveRequestData, + selected_wave_ids: autoFilled.selected_wave_ids, + selected_order_ids: autoFilled.selected_order_ids, + }; + } + + const selectedWaveIds = this.normalizeIdsInput(effectivePlan.selected_wave_ids || []); + const selectedOrderIds = this.normalizeIdsInput( + effectiveRequestData.selected_order_ids !== undefined + ? effectiveRequestData.selected_order_ids + : effectiveRequestData.selectedOrderIds !== undefined + ? effectiveRequestData.selectedOrderIds + : effectiveRequestData.order_ids !== undefined + ? effectiveRequestData.order_ids + : effectiveRequestData.orderIds + ); + + const validationErrors = Array.isArray(effectivePlan.validation_errors) + ? [ ...effectivePlan.validation_errors ] + : []; + if ([ 1, 5 ].includes(pickMode) && selectedWaveIds.length === 0) { + validationErrors.push('当前模式依赖波次,selected_wave_ids 不能为空'); + } + if ([ 2, 3, 4 ].includes(pickMode) && selectedOrderIds.length === 0) { + validationErrors.push('当前模式至少需要一个订单,selected_order_ids 不能为空'); + } + if (validationErrors.length > 0) { + throw new Error(`按策略抓取任务创建校验失败: ${validationErrors.join(';')}`); + } + + if (normalizedCartId > 0) { + await this.ensurePickCartAvailable({ + cartId: normalizedCartId, + warehouseId, + transaction, + }); + } + + // 散单模式:从波次表读取 wave_no 并写入任务 batch_no + let resolvedBatchNo = null; + if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0) { + const batchRows = await this.ctx.model.query( + 'SELECT wave_no FROM wms_wave_batch WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1', + { + replacements: { waveId: selectedWaveIds[0], warehouseId }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + } + ); + resolvedBatchNo = (batchRows.length > 0 && batchRows[0].wave_no) ? String(batchRows[0].wave_no).trim() : null; + } + + const taskPayload = this.buildTaskCreatePayload({ + plan: effectivePlan, + data: effectiveRequestData, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + if (resolvedBatchNo !== null) { + taskPayload.batch_no = resolvedBatchNo; + } + + if (selectedWaveIds.length > 0 && [ 1, 2 ].includes(waveBatchSource)) { + await this.ctx.model.query(` + UPDATE wms_wave_batch + SET source = :source, + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + source: waveBatchSource, + warehouseId, + waveIds: selectedWaveIds, + }, + transaction, + }); + } + + const taskCreateResult = await this.createWavePickTaskWithRetry(taskPayload, transaction); + const taskId = Number(taskCreateResult.task_id || 0); + const taskNo = String(taskCreateResult.task_no || '').trim(); + + const taskWaveRows = this.buildTaskWaveRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + }); + const taskOrderRows = this.buildTaskOrderRows({ + taskId, + plan: effectivePlan, + selectedWaveIds, + selectedOrderIds, + cartId: normalizedCartId, + }); + const taskSkuRows = await this.buildTaskSkuRows({ + plan: effectivePlan, + selectedOrderIds, + }); + const taskBoxRows = this.buildTaskBoxRows({ + taskId, + taskNo, + plan: effectivePlan, + taskWaveRows, + taskOrderRows, + taskSkuRows, + }); + + if (taskWaveRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_wave', taskWaveRows, transaction); + } + if (taskOrderRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_order', taskOrderRows, transaction); + } + if (taskBoxRows.length > 0) { + await this.bulkInsertRows('wms_wave_pick_task_box', taskBoxRows, transaction); + } + + if (normalizedCartId > 0) { + await this.bindPickCartForTask({ + taskId, + cartId: normalizedCartId, + warehouseId, + operatorId: taskPayload.pick_user_id, + transaction, + }); + } + + await this.initTaskCheckpointAndLogs({ + taskId, + taskNo, + plan: effectivePlan, + data: effectiveRequestData, + selectedOrderIds, + cartId: normalizedCartId, + operatorId: taskPayload.pick_user_id, + operatorName: taskPayload.pick_user_name, + transaction, + }); + + await transaction.commit(); + + return { + task_id: taskId, + task_no: taskNo, + state: 'created', + plan_summary: { + pick_mode: pickMode, + wave_count: taskWaveRows.length, + order_count: taskOrderRows.length, + box_count: taskBoxRows.length, + cart_id: normalizedCartId > 0 ? normalizedCartId : null, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 构建任务主表写入载荷。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Object} options.data 原始请求数据。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 拣货车ID。 + * @return {Object} 主表写入载荷。 + */ + buildTaskCreatePayload(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const data = this.isPlainObject(options && options.data) ? options.data : {}; + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const pickMode = this.normalizeRequiredPositiveInteger(plan.pick_mode, 'pick_mode'); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const source = String(plan.source || 'unknown').trim(); + const sourceCode = source === 'admin' ? 2 : 1; + + const operator = this.isPlainObject(plan.operator) ? plan.operator : {}; + const rawOperatorId = operator.operator_id ?? operator.id; + const normalizedOperatorId = Number(rawOperatorId); + const pickUserId = Number.isInteger(normalizedOperatorId) && normalizedOperatorId >= 0 + ? normalizedOperatorId + : 0; + const pickUserName = String(operator.operator_name || operator.name || this.getOrderLogOperator().name || 'system').trim() || 'system'; + const taskNo = String(data.task_no || '').trim() || this.generateWavePickTaskNo(warehouseId, sourceCode); + + return { + task_no: taskNo, + warehouse_id: warehouseId, + wave_id: selectedWaveIds.length > 0 ? selectedWaveIds[0] : null, + pick_mode: pickMode, + status: 0, + source: sourceCode, + wave_count: selectedWaveIds.length, + order_count: selectedOrderIds.length, + box_count: 0, + batch_no: null, + pick_user_id: pickUserId, + pick_user_name: pickUserName, + current_cart_id: Number(options && options.cartId || 0) > 0 ? Number(options.cartId) : null, + current_cart_code_snapshot: null, + review_status: 0, + review_version: 0, + device_id: String(data.device_id || data.deviceId || '').trim() || `wave_${source}_${warehouseId}`, + ext_json: JSON.stringify({ + strategy_id: plan.strategy_id, + wave_limit: Number(plan.wave_limit || 0), + order_limit: Number(plan.order_limit || 0), + sku_limit: Number(plan.sku_limit || 0), + box_limit: Number(plan.box_limit || 0), + dynamic_append: Boolean(plan.dynamic_append), + }), + }; + } + + /** + * 构建任务与波次关联写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @return {Array} 任务波次行。 + */ + buildTaskWaveRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + + return selectedWaveIds.map((waveId, index) => ({ + task_id: taskId, + wave_id: waveId, + wave_no: null, + box_no: index + 1, + status: 0, + bind_time: null, + pick_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 构建任务订单明细写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedWaveIds 已选波次ID。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @param {number} options.cartId 绑定车ID。 + * @return {Array} 任务订单行。 + */ + buildTaskOrderRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedWaveIds = Array.isArray(options && options.selectedWaveIds) + ? options.selectedWaveIds + : []; + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? options.selectedOrderIds + : []; + const cartId = Number(options && options.cartId || 0); + + if (![ 2, 3, 4 ].includes(pickMode)) { + return []; + } + + const defaultWaveId = selectedWaveIds.length > 0 ? selectedWaveIds[0] : null; + return selectedOrderIds.map((orderId, index) => ({ + task_id: taskId, + wave_id: defaultWaveId, + order_id: orderId, + order_no: null, + box_no: index + 1, + cart_id: cartId > 0 ? cartId : null, + cart_code_snapshot: null, + warehouse_id: warehouseId, + pick_status: 0, + review_status: 0, + review_user_id: null, + review_result: null, + review_remark: null, + exception_reason: null, + picked_time: null, + review_time: null, + })); + } + + /** + * 构建任务 SKU 明细写入行(仅先拣后分模式使用)。 + * + * @param {Object} options 构建参数。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.selectedOrderIds 已选订单ID。 + * @return {Promise>} 任务 SKU 行。 + */ + async buildTaskSkuRows(options = {}) { + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const selectedOrderIds = Array.isArray(options && options.selectedOrderIds) + ? this.normalizeIdsInput(options.selectedOrderIds) + : []; + + if (pickMode !== 3 || selectedOrderIds.length <= 0) { + return []; + } + + const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId); + if (!orderItemsModel || typeof orderItemsModel.findAll !== 'function') { + throw new Error('订单明细模型不可用'); + } + + const itemRows = await orderItemsModel.findAll({ + where: { + order_id: { [Op.in]: selectedOrderIds }, + }, + attributes: [ 'order_id', 'plan_qty', 'stock_id', 'item_code', 'item_name', 'item_snapshot' ], + raw: true, + }); + + const skuMap = new Map(); + for (const row of (Array.isArray(itemRows) ? itemRows : [])) { + const normalized = this.normalizeOrderItemRow(row); + if (normalized.quantity <= 0) { + continue; + } + + const skuId = Number(normalized.stock_id || 0); + const itemCode = String(normalized.item_code || '').trim(); + const itemName = String(normalized.item_name || '').trim(); + if (!(Number.isInteger(skuId) && skuId > 0) && !itemCode) { + continue; + } + + const key = Number.isInteger(skuId) && skuId > 0 ? `stock_${skuId}` : `code_${itemCode}`; + if (!skuMap.has(key)) { + skuMap.set(key, { + sku_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_id: Number.isInteger(skuId) && skuId > 0 ? skuId : null, + ref_label: itemName || itemCode || null, + required_qty: 0, + }); + } + + const aggregated = skuMap.get(key); + aggregated.required_qty += normalized.quantity; + if (!aggregated.ref_label && (itemName || itemCode)) { + aggregated.ref_label = itemName || itemCode; + } + } + + return Array.from(skuMap.values()) + .sort((a, b) => { + const leftSkuId = Number(a.sku_id || 0); + const rightSkuId = Number(b.sku_id || 0); + if (leftSkuId !== rightSkuId) { + return leftSkuId - rightSkuId; + } + return String(a.ref_label || '').localeCompare(String(b.ref_label || '')); + }) + .map((row, index) => ({ + box_no: index + 1, + sku_id: row.sku_id, + ref_id: row.ref_id, + ref_label: row.ref_label, + required_qty: Number(row.required_qty || 0), + })); + } + + /** + * 构建任务框明细写入行。 + * + * @param {Object} options 构建参数。 + * @param {number} options.taskId 任务ID。 + * @param {string} options.taskNo 任务编号。 + * @param {Object} options.plan 预处理计划。 + * @param {Array} options.taskWaveRows 任务波次行。 + * @param {Array} options.taskOrderRows 任务订单行。 + * @param {Array} options.taskSkuRows 任务 SKU 行。 + * @return {Array} 任务框行。 + */ + buildTaskBoxRows(options = {}) { + const taskId = Number(options && options.taskId || 0); + const taskNo = String(options && options.taskNo || '').trim(); + const plan = this.isPlainObject(options && options.plan) ? options.plan : {}; + const pickMode = Number(plan.pick_mode || 0); + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const taskWaveRows = Array.isArray(options && options.taskWaveRows) + ? options.taskWaveRows + : []; + const taskOrderRows = Array.isArray(options && options.taskOrderRows) + ? options.taskOrderRows + : []; + const taskSkuRows = Array.isArray(options && options.taskSkuRows) + ? options.taskSkuRows + : []; + + if ([ 1, 5 ].includes(pickMode)) { + return taskWaveRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-W${row.box_no}`, + box_no: row.box_no, + box_type: 3, + ref_id: row.wave_id, + ref_label: row.wave_no, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + if (pickMode === 3 && taskSkuRows.length > 0) { + return taskSkuRows.map(row => ({ + task_id: taskId, + order_id: null, + box_code: `${taskNo || taskId}-S${row.box_no}`, + box_no: row.box_no, + box_type: 1, + ref_id: Number(row.ref_id || row.sku_id || 0) || null, + ref_label: String(row.ref_label || '').trim() || null, + required_qty: Number(row.required_qty || 0), + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + return taskOrderRows.map(row => ({ + task_id: taskId, + order_id: row.order_id, + box_code: `${taskNo || taskId}-O${row.box_no}`, + box_no: row.box_no, + box_type: 2, + ref_id: row.order_id, + ref_label: null, + required_qty: 0, + picked_qty: 0, + box_status: 0, + review_result: null, + review_user_id: null, + review_time: null, + warehouse_id: warehouseId, + })); + } + + /** + * 领单时绑定拣货车并更新车辆主表。 + * + * @param {Object} params 绑定参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async bindPickCartForTask(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + + const cartRows = await this.ctx.model.query(` + SELECT id, cart_code, current_task_id + FROM wms_pick_cart + WHERE id = :cartId + AND warehouse_id = :warehouseId + AND status = 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const cartRow = Array.isArray(cartRows) ? cartRows[0] : null; + if (!cartRow) { + throw new Error(`拣货车不存在或已停用: ${cartId}`); + } + + const activeTaskId = Number(cartRow.current_task_id || 0); + if (activeTaskId > 0 && activeTaskId !== taskId) { + throw new Error(`拣货车已被任务占用: ${cartId}`); + } + + await this.bulkInsertRows('wms_pick_task_cart_binding', [{ + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: String(cartRow.cart_code || '').trim() || null, + warehouse_id: warehouseId, + bind_user_id: operatorId, + bind_type: 1, + unbind_user_id: null, + is_active: 1, + bind_time: new Date(), + unbind_time: null, + }], transaction); + + await this.ctx.model.query(` + UPDATE wms_pick_cart + SET + current_task_id = :taskId, + bind_user_id = :operatorId, + last_bind_time = NOW(), + last_seen_time = NOW() + WHERE id = :cartId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + operatorId, + cartId, + warehouseId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + current_cart_id = :cartId, + current_cart_code_snapshot = :cartCode + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + cartId, + cartCode: String(cartRow.cart_code || '').trim() || null, + warehouseId, + }, + transaction, + }); + } + + /** + * 初始化任务断点、动作日志与轨迹。 + * + * @param {Object} params 初始化参数。 + * @param {number} params.taskId 任务ID。 + * @param {string} params.taskNo 任务编号。 + * @param {Object} params.plan 预处理计划。 + * @param {Object} params.data 原始请求数据。 + * @param {Array} params.selectedOrderIds 已选订单ID。 + * @param {number} params.cartId 绑定车ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人姓名。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async initTaskCheckpointAndLogs(params = {}) { + const taskId = this.normalizeRequiredPositiveInteger(params.taskId, 'task_id'); + const taskNo = String(params.taskNo || '').trim(); + const plan = this.isPlainObject(params.plan) ? params.plan : {}; + const data = this.isPlainObject(params.data) ? params.data : {}; + const transaction = params.transaction; + const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id'); + const operatorId = Number.isInteger(Number(params.operatorId)) + ? Number(params.operatorId) + : 0; + const operatorName = String(params.operatorName || 'system').trim() || 'system'; + const cartId = Number(params.cartId || 0) > 0 ? Number(params.cartId) : null; + const selectedOrderIds = Array.isArray(params.selectedOrderIds) && params.selectedOrderIds.length > 0 + ? params.selectedOrderIds + : [ 0 ]; + const deviceId = String(data.device_id || data.deviceId || '').trim() || `device_${warehouseId}`; + const requestId = String(data.request_id || data.requestId || `${taskNo || taskId}_init`).trim(); + + await this.bulkInsertRows('wms_wave_pick_checkpoint', [{ + task_id: taskId, + warehouse_id: warehouseId, + pick_user_id: operatorId, + device_id: deviceId, + current_location_id: null, + current_sku_id: null, + current_box_no: null, + picked_count: 0, + remaining_count: Math.max(selectedOrderIds.length, 0), + last_event_id: null, + last_seq_no: null, + checkpoint_json: JSON.stringify({ + state: 'created', + task_no: taskNo, + }), + version: 0, + }], transaction); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(plan.selected_wave_ids) && plan.selected_wave_ids.length > 0 + ? Number(plan.selected_wave_ids[0]) + : null, + order_id: selectedOrderIds[0], + sku_id: null, + location_id: null, + box_no: null, + cart_id: cartId, + qty_delta: 0, + action_type: 'init', + request_id: `${requestId}_${taskId}`, + operator_id: operatorId, + device_id: deviceId, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + state: 'created', + }), + }], transaction); + + const traceRows = selectedOrderIds.map(orderId => ({ + warehouse_id: warehouseId, + order_id: Number(orderId), + task_id: taskId, + cart_id: cartId, + cart_code_snapshot: null, + pick_user_id: operatorId, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_created', + event_desc: `任务创建: ${taskNo || taskId}`, + operator_id: operatorId, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + pick_mode: Number(plan.pick_mode || 0), + }), + })); + await this.bulkInsertRows('wms_order_pick_trace', traceRows, transaction); + } + + /** + * 校验拣货车是否可占用。 + * + * @param {Object} params 校验参数。 + * @param {number} params.cartId 拣货车ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Object} params.transaction 事务对象。 + * @return {Promise} 无返回值。 + */ + async ensurePickCartAvailable(params = {}) { + const cartId = this.normalizeRequiredPositiveInteger(params.cartId, 'cart_id'); + const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); + const transaction = params.transaction; + + const rows = await this.ctx.model.query(` + SELECT b.task_id + FROM wms_pick_task_cart_binding b + INNER JOIN wms_wave_pick_task t ON t.id = b.task_id + WHERE b.cart_id = :cartId + AND b.warehouse_id = :warehouseId + AND b.is_active = 1 + AND t.status IN (0, 1, 2) + LIMIT 1 + FOR UPDATE + `, { + replacements: { + cartId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + if (Array.isArray(rows) && rows.length > 0) { + throw new Error(`拣货车已绑定活动任务: ${cartId}`); + } + } + + /** + * 生成任务编号。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} sourceCode 来源编码。 + * @return {string} 任务编号。 + */ + generateWavePickTaskNo(warehouseId, sourceCode) { + const now = Date.now(); + const rand = Math.random().toString(36).slice(2, 8) + .toUpperCase(); + return `WPT${warehouseId}${sourceCode}${now}${rand}`; + } + + /** + * 写入任务主表并在任务编号冲突时重试。 + * + * @param {Object} payload 主表载荷。 + * @param {Object} transaction 事务对象。 + * @return {Promise<{ task_id: number, task_no: string }>} 主表写入结果。 + */ + async createWavePickTaskWithRetry(payload = {}, transaction) { + const maxRetry = 5; + const warehouseId = this.normalizeRequiredPositiveInteger(payload.warehouse_id, 'warehouse_id'); + + for (let attempt = 1; attempt <= maxRetry; attempt += 1) { + const candidateTaskNo = attempt === 1 && String(payload.task_no || '').trim() + ? String(payload.task_no || '').trim() + : this.generateWavePickTaskNo(warehouseId, Number(payload.source || 1)); + + const insertPayload = { + ...payload, + task_no: candidateTaskNo, + }; + + try { + const createResult = await this.ctx.model.query(` + INSERT INTO wms_wave_pick_task + ( + task_no, + warehouse_id, + wave_id, + pick_mode, + status, + source, + wave_count, + order_count, + box_count, + batch_no, + pick_user_id, + pick_user_name, + current_cart_id, + current_cart_code_snapshot, + review_status, + review_version, + device_id, + ext_json, + create_time, + update_time + ) + VALUES + ( + :task_no, + :warehouse_id, + :wave_id, + :pick_mode, + :status, + :source, + :wave_count, + :order_count, + :box_count, + :batch_no, + :pick_user_id, + :pick_user_name, + :current_cart_id, + :current_cart_code_snapshot, + :review_status, + :review_version, + :device_id, + :ext_json, + NOW(), + NOW() + ) + `, { + replacements: insertPayload, + transaction, + }); + + let insertedTaskId = this.extractInsertId(createResult); + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + const fallbackResult = await this.ctx.model.query('SELECT LAST_INSERT_ID() AS insertId', { + transaction, + }); + insertedTaskId = this.extractLastInsertId(fallbackResult); + } + + if (!Number.isInteger(insertedTaskId) || insertedTaskId <= 0) { + throw new Error('创建任务失败,未获取到任务主键'); + } + + return { + task_id: insertedTaskId, + task_no: candidateTaskNo, + }; + } catch (error) { + const isDuplicateTaskNo = this.isTaskNoDuplicateError(error); + if (isDuplicateTaskNo && attempt < maxRetry) { + continue; + } + throw error; + } + } + + throw new Error('创建任务失败,任务编号重试次数已达上限'); + } + + /** + * 判断是否为 task_no 唯一键冲突。 + * + * @param {Error} error 数据库错误。 + * @return {boolean} 是否冲突。 + */ + isTaskNoDuplicateError(error) { + const message = String(error && error.message || '').toLowerCase(); + const parentErrno = Number(error && error.parent && error.parent.errno || 0); + return parentErrno === 1062 + || message.includes('duplicate entry') + || message.includes('uk_task_no'); + } + + /** + * 批量插入行数据。 + * + * @param {string} tableName 表名。 + * @param {Array} rows 行数据。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 实际写入行数。 + */ + async bulkInsertRows(tableName, rows = [], transaction) { + if (!Array.isArray(rows) || rows.length === 0) { + return 0; + } + + const columns = Object.keys(rows[0]); + if (columns.length === 0) { + return 0; + } + + const replacements = {}; + const valueSqlList = rows.map((row, rowIndex) => { + const placeholders = columns.map(column => { + const key = `${column}_${rowIndex}`; + replacements[key] = Object.prototype.hasOwnProperty.call(row, column) + ? row[column] + : null; + return `:${key}`; + }); + return `(${placeholders.join(', ')})`; + }); + + const columnSql = columns.map(column => `\`${column}\``).join(', '); + const sql = `INSERT INTO ${tableName} (${columnSql}) VALUES ${valueSqlList.join(', ')}`; + await this.ctx.model.query(sql, { + replacements, + transaction, + }); + + return rows.length; + } + + /** + * 解析“存在未完成任务”异常信息中的任务标识。 + * + * @param {string} message 异常消息文本。 + * @return {{ task_id: number|null, task_no: string|null }} 解析结果。 + */ + parseWaveStrategyExistingTaskInfo(message = '') { + const normalizedMessage = String(message || ''); + const match = normalizedMessage.match(/task_id=(\d+)(?:,task_no=([^\)\)\s]+))?/); + if (!match) { + return { + task_id: null, + task_no: null, + }; + } + + const parsedTaskId = Number(match[1] || 0); + const parsedTaskNo = String(match[2] || '').trim(); + + return { + task_id: Number.isInteger(parsedTaskId) && parsedTaskId > 0 ? parsedTaskId : null, + task_no: parsedTaskNo || null, + }; + } + + /** + * 按策略抓取任务壳子方法(仅 PDA 使用),仅受理请求并返回任务信息。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 受理结果。 + */ + async waveStrategyFetchPda(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'pda', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 400); + } + + try { + const createdTask = await this.createWavePickTaskFromPlan({ + plan, + data: normalizedData, + waveBatchSource: 2, + autoPopulateSelections: true, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchPda] 任务创建成功', { + taskId: createdTask.task_id, + taskNo: createdTask.task_no, + warehouseId, + strategyId, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '任务创建成功', + task_id: createdTask.task_id, + task_no: createdTask.task_no, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + state: createdTask.state, + plan, + plan_summary: createdTask.plan_summary, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + const errorMessage = String(error && error.message || ''); + if (errorMessage.includes('当前用户存在未完成任务')) { + const existingTaskInfo = this.parseWaveStrategyExistingTaskInfo(errorMessage); + return this.success('存在未完成任务', { + status: 'failed', + fetch_state: 3, + tip: '存在未完成任务,已返回任务ID,可继续拣货', + task_id: existingTaskInfo.task_id, + task_no: existingTaskInfo.task_no, + can_enter_pick_flow: true, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }); + } + + return this.fail(`按策略抓取任务创建失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'pda', + plan, + }, + }, 500); + } + } + + /** + * 公共拣货任务取消流程。 + * + * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @param {Object} [params={}] 取消参数。 + * @param {Array} params.taskIds 任务ID列表。 + * @param {number} params.warehouseId 仓库ID。 + * @param {number} params.operatorId 操作人ID。 + * @param {string} params.operatorName 操作人名称。 + * @param {number|null} [params.restrictCreatorId=null] 限制创建人ID。 + * @return {Promise} 取消结果。 + */ + async cancelWavePickTasksInternal(params = {}) { + const normalizedParams = this.isPlainObject(params) ? params : {}; + const sourceTaskIds = Array.isArray(normalizedParams.taskIds) ? normalizedParams.taskIds : []; + const normalizedTaskIds = [ ...new Set(sourceTaskIds + .map(item => Number(item)) + .filter(taskId => Number.isInteger(taskId) && taskId > 0)) ]; + const warehouseId = Number(normalizedParams.warehouseId || 0); + const operatorId = Number(normalizedParams.operatorId || 0); + const operatorName = String(normalizedParams.operatorName || 'system').trim() || 'system'; + const rawRestrictCreatorId = normalizedParams.restrictCreatorId; + const restrictCreatorId = rawRestrictCreatorId === null || rawRestrictCreatorId === undefined + ? null + : Number(rawRestrictCreatorId); + + if (normalizedTaskIds.length === 0) { + const error = new Error('task_ids 必须为非空数组'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + const error = new Error('未获取到仓库上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (!Number.isInteger(operatorId) || operatorId <= 0) { + const error = new Error('未获取到操作人上下文'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + if (restrictCreatorId !== null && (!Number.isInteger(restrictCreatorId) || restrictCreatorId <= 0)) { + const error = new Error('取消任务创建人限制参数不合法'); + error.statusCode = 400; + error.data = {}; + throw error; + } + + const transaction = await this.ctx.model.transaction(); + + try { + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const canceledAtColumnRows = await this.ctx.model.query(` + SHOW COLUMNS FROM wms_wave_pick_task LIKE 'cancelled_at' + `, { + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const hasCancelledAtColumn = Array.isArray(canceledAtColumnRows) && canceledAtColumnRows.length > 0; + const cancelledTaskNos = []; + + for (const taskId of normalizedTaskIds) { + const requestId = `wave_pick_task_cancel_${warehouseId}_${taskId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const taskRows = await this.ctx.model.query(` + SELECT id, task_no, warehouse_id, status, current_cart_id + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + ${restrictCreatorId !== null ? 'AND pick_user_id = :restrictCreatorId' : ''} + LIMIT 1 + FOR UPDATE + `, { + replacements: { + taskId, + warehouseId, + ...(restrictCreatorId !== null ? { restrictCreatorId } : {}), + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + const taskRow = Array.isArray(taskRows) ? taskRows[0] : null; + if (!taskRow) { + if (restrictCreatorId !== null) { + const taskRowsWithoutCreator = await this.ctx.model.query(` + SELECT id + FROM wms_wave_pick_task + WHERE id = :taskId + AND warehouse_id = :warehouseId + LIMIT 1 + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + if (Array.isArray(taskRowsWithoutCreator) && taskRowsWithoutCreator.length > 0) { + const error = new Error('仅允许取消本人创建的任务'); + error.statusCode = 403; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + operator_id: restrictCreatorId, + }; + throw error; + } + } + + const error = new Error('任务不存在'); + error.statusCode = 404; + error.data = { + task_id: taskId, + warehouse_id: warehouseId, + }; + throw error; + } + + const taskStatus = Number(taskRow.status || 0); + if (![ 0, 1, 2 ].includes(taskStatus)) { + const error = new Error('当前任务状态不允许取消'); + error.statusCode = 400; + error.data = { + task_id: taskId, + task_no: String(taskRow.task_no || '').trim(), + warehouse_id: warehouseId, + status: taskStatus, + }; + throw error; + } + + const taskNo = String(taskRow.task_no || '').trim(); + + const taskWaveRows = await this.ctx.model.query(` + SELECT wave_id + FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const waveIds = [ ...new Set((Array.isArray(taskWaveRows) ? taskWaveRows : []) + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]; + + const taskOrderRows = await this.ctx.model.query(` + SELECT order_id + FROM wms_wave_pick_task_order + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + const taskOrderIds = [ ...new Set((Array.isArray(taskOrderRows) ? taskOrderRows : []) + .map(row => Number(row && row.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + + let releasedWaveRows = []; + if (waveIds.length > 0) { + releasedWaveRows = await this.ctx.model.query(` + SELECT wave_id, wave_no + FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + FOR UPDATE + `, { + replacements: { + warehouseId, + waveIds, + }, + type: this.ctx.model.QueryTypes.SELECT, + transaction, + }); + + await orderModel.update({ + wave_id: 0, + wave_no: '', + }, { + where: { + warehouse_id: warehouseId, + wave_id: { [Op.in]: waveIds }, + }, + transaction, + }); + + await this.ctx.model.query(` + DELETE FROM wms_wave_batch + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `, { + replacements: { + warehouseId, + waveIds, + }, + transaction, + }); + + await this.ctx.model.query(` + DELETE FROM wms_wave_pick_task_wave + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + } + + await this.ctx.model.query(` + UPDATE wms_wave_pick_task + SET + status = 9, + current_cart_id = NULL, + current_cart_code_snapshot = NULL, + ${hasCancelledAtColumn ? 'cancelled_at = NOW(),' : ''} + update_time = NOW() + WHERE id = :taskId + AND warehouse_id = :warehouseId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_pick_task_cart_binding + SET + is_active = 0, + unbind_user_id = :operatorId, + unbind_time = NOW(), + update_time = NOW() + WHERE task_id = :taskId + AND warehouse_id = :warehouseId + AND is_active = 1 + `, { + replacements: { + taskId, + warehouseId, + operatorId, + }, + transaction, + }); + + await this.ctx.model.query(` + UPDATE wms_pick_cart + SET + current_task_id = NULL, + bind_user_id = NULL, + last_seen_time = NOW(), + update_time = NOW() + WHERE warehouse_id = :warehouseId + AND current_task_id = :taskId + `, { + replacements: { + taskId, + warehouseId, + }, + transaction, + }); + + await this.bulkInsertRows('wms_wave_pick_action_log', [{ + task_id: taskId, + warehouse_id: warehouseId, + wave_id: Array.isArray(releasedWaveRows) && releasedWaveRows.length > 0 + ? Number(releasedWaveRows[0].wave_id || 0) || null + : null, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : null, + sku_id: null, + location_id: null, + box_no: null, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + qty_delta: 0, + action_type: 'cancel', + request_id: requestId, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + device_id: null, + seq_no: 1, + snapshot: JSON.stringify({ + task_no: taskNo, + released_wave_ids: waveIds, + released_order_count: taskOrderIds.length, + }), + }], transaction); + + await this.bulkInsertRows('wms_order_pick_trace', [{ + warehouse_id: warehouseId, + order_id: taskOrderIds.length > 0 ? Number(taskOrderIds[0]) : 0, + task_id: taskId, + cart_id: Number(taskRow.current_cart_id || 0) > 0 ? Number(taskRow.current_cart_id) : null, + cart_code_snapshot: null, + pick_user_id: null, + pick_time: null, + review_user_id: null, + review_time: null, + review_result: null, + event_type: 'task_cancelled', + event_desc: `任务取消并释放波次: ${taskNo || taskId}`, + operator_id: Number.isInteger(operatorId) ? operatorId : 0, + operator_name: operatorName, + snapshot: JSON.stringify({ + task_no: taskNo, + released_wave_ids: waveIds, + released_order_count: taskOrderIds.length, + released_wave_nos: (Array.isArray(releasedWaveRows) ? releasedWaveRows : []) + .map(row => String(row && row.wave_no || '').trim()) + .filter(Boolean), + }), + }], transaction); + + cancelledTaskNos.push(taskNo); + } + + await transaction.commit(); + + return { + cancelled_count: normalizedTaskIds.length, + task_ids: normalizedTaskIds, + task_nos: cancelledTaskNos, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + /** + * 取消拣货任务并释放关联波次。 + * + * 仅允许取消状态为 0/1/2 的任务。取消后会回收拣货车绑定、 + * 删除任务关联波次并将订单 wave_id 清空,使订单可重新参与后续策略抓取。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Array} data.task_ids 任务ID数组。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancel(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const sourceTaskIds = Array.isArray(normalizedData.task_ids) ? normalizedData.task_ids : []; + if (sourceTaskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const normalizedTaskIds = []; + for (const item of sourceTaskIds) { + const taskId = Number(item); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_ids 必须为正整数数组', { + data: { + task_ids: sourceTaskIds, + }, + }, 400); + } + normalizedTaskIds.push(taskId); + } + const taskIds = [ ...new Set(normalizedTaskIds) ]; + if (taskIds.length === 0) { + return this.fail('task_ids 必须为非空数组', {}, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds, + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: null, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消拣货任务失败: ${error.message}`, { + data: { + task_ids: taskIds, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 取消本人创建的单个拣货任务并释放关联波次。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.task_id 任务ID。 + * @return {Promise} 取消结果。 + */ + async wavePickTaskCancelSelf(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + if (Object.prototype.hasOwnProperty.call(normalizedData, 'task_ids')) { + return this.fail('当前接口仅支持单个 task_id,请勿传 task_ids', { + data: { + task_ids: normalizedData.task_ids, + }, + }, 400); + } + + const taskId = Number(normalizedData.task_id); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必须为正整数', { + data: { + task_id: normalizedData.task_id, + }, + }, 400); + } + + const resolvedWarehouseId = Number(this.getWarehouseId() || 0); + if (!Number.isInteger(resolvedWarehouseId) || resolvedWarehouseId <= 0) { + return this.fail('未获取到仓库上下文', {}, 400); + } + + const operatorInfo = this.getOrderLogOperator(); + const operatorId = Number(operatorInfo.id || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 400); + } + const operatorName = String(operatorInfo.name || 'system').trim() || 'system'; + + try { + const result = await this.cancelWavePickTasksInternal({ + taskIds: [ taskId ], + warehouseId: resolvedWarehouseId, + operatorId, + operatorName, + restrictCreatorId: operatorId, + }); + + return this.success('ok', result); + } catch (error) { + if (Number.isInteger(error.statusCode) && error.statusCode >= 400 && error.statusCode < 500) { + return this.fail(error.message, { + data: this.isPlainObject(error.data) ? error.data : {}, + }, error.statusCode); + } + + return this.fail(`取消本人拣货任务失败: ${error.message}`, { + data: { + task_id: taskId, + warehouse_id: resolvedWarehouseId, + }, + }, 500); + } + } + + /** + * 按策略抓取任务壳子方法(仅后台管理使用),仅受理请求并返回任务信息。 + * + * @param {Object} [data={}] 请求参数。 + * @param {number|string} data.strategy_id 波次策略ID(支持 strategyId)。 + * @return {Promise} 受理结果。 + */ + async waveStrategyFetchAdmin(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + const strategyId = this.normalizeRequiredPositiveInteger( + normalizedData.strategy_id ?? normalizedData.strategyId, + 'strategy_id' + ); + + let warehouseId; + try { + warehouseId = Number(this.getWarehouseId()); + } catch (error) { + throw new Error('未识别到当前仓库上下文'); + } + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + throw new Error('未识别到当前仓库上下文'); + } + + const operatorInfo = this.getOrderLogOperator(); + const plan = await this.prepareWaveStrategyFetchPlan({ + strategyId, + warehouseId, + operator: { + operator_id: operatorInfo.id, + operator_name: operatorInfo.name, + }, + source: 'admin', + data: normalizedData, + }); + + if (Array.isArray(plan.validation_errors) && plan.validation_errors.length > 0) { + return this.fail('按策略抓取预处理校验失败', { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 400); + } + + try { + const createdTask = await this.createWavePickTaskFromPlan({ + plan, + data: normalizedData, + waveBatchSource: 1, + }); + + this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 任务创建成功', { + taskId: createdTask.task_id, + taskNo: createdTask.task_no, + warehouseId, + strategyId, + }); + + return this.success('ok', { + status: 'success', + fetch_state: 1, + tip: '任务创建成功', + task_id: createdTask.task_id, + task_no: createdTask.task_no, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + state: createdTask.state, + plan, + plan_summary: createdTask.plan_summary, + accepted_at: new Date().toISOString(), + }); + } catch (error) { + const errorMessage = String(error && error.message || ''); + if (errorMessage.includes('当前用户存在未完成任务')) { + const existingTaskInfo = this.parseWaveStrategyExistingTaskInfo(errorMessage); + return this.success('存在未完成任务', { + status: 'failed', + fetch_state: 3, + tip: '存在未完成任务,已返回任务ID,可继续拣货', + task_id: existingTaskInfo.task_id, + task_no: existingTaskInfo.task_no, + can_enter_pick_flow: true, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }); + } + + return this.fail(`按策略抓取任务创建失败: ${error.message}`, { + data: { + status: 'failed', + fetch_state: 2, + tip: '创建失败,请重试', + task_id: null, + can_enter_pick_flow: false, + warehouse_id: warehouseId, + strategy_id: strategyId, + source: 'admin', + plan, + }, + }, 500); + } + } + /** * 兼容旧方法名 fetch,内部转调 groupFetch。 * diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 1da0dfd..f5628ce 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -11,9 +11,9 @@ class PickService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'query'; + const _noNeedRight = 'query,wavePickTaskDetail'; const _noNeedLog = 'query'; - const _noNeedAuth = 'query'; + const _noNeedAuth = 'query,wavePickTaskDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -167,6 +167,55 @@ class PickService extends MainService { return this.fail('查询失败', {}, 500); } } + + /** + * 查询拣货任务详情。 + * + * 仅允许任务创建人查看任务详情,包含主任务、波次、订单与框信息。 + * + * @param {Object} data 请求参数。 + * @param {number|string} data.task_id 拣货任务ID。 + * @return {Promise} 统一 success/fail 包装结果。 + */ + async wavePickTaskDetail(data = {}) { + const { service, ctx } = this; + const requestData = this.isPlainObject(data) ? data : {}; + const { task_id } = requestData; + + const taskId = Number(task_id); + if (!Number.isInteger(taskId) || taskId <= 0) { + return this.fail('task_id 必填且必须为正整数', {}, 400); + } + + const stateUser = this.isPlainObject(ctx && ctx.state && ctx.state.user) ? ctx.state.user : null; + const ctxUser = this.isPlainObject(ctx && ctx.user) ? ctx.user : null; + const operatorSource = stateUser || ctxUser || {}; + const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id; + const operatorId = Number(rawOperatorId || 0); + if (!Number.isInteger(operatorId) || operatorId <= 0) { + return this.fail('未获取到操作人上下文', {}, 401); + } + + try { + const result = await service.systems.pick.wavePickTaskDetail({ + taskId, + operatorId, + }); + + return this.success('ok', { + data: result, + code: 200, + }); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || '查询失败', {}, code); + } + + ctx.logger.error('[PickService.wavePickTaskDetail] 查询拣货任务详情失败: %s', error && error.message ? error.message : error); + return this.fail('查询失败', {}, 500); + } + } } module.exports = PickService; diff --git a/app/service/systemMethods/setting/warehouse.js b/app/service/systemMethods/setting/warehouse.js index bb1d182..06061bc 100644 --- a/app/service/systemMethods/setting/warehouse.js +++ b/app/service/systemMethods/setting/warehouse.js @@ -47,7 +47,7 @@ class SettingWarehouseMethodsService extends MainService { } try { - const list = targetService.getFieldMeta(); + const list = await targetService.getFieldMeta(); return this.success('ok', { list }); } catch (error) { return this.fail(error.message || '获取仓库设置字段信息失败', { diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index 18c9fa7..f9e2e70 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -1834,6 +1834,26 @@ class DeliveryOrderService extends Service { await this.runAsyncProcessStep('autoGrouping', async () => { await this.runAutoGrouping(context); }); + + await this.runAsyncProcessStep('waveStrategyQuickScan', async () => { + await this.withPatchedCtxUser({ + store_id: context.warehouseId, + warehouse_id: context.warehouseId, + }, async () => { + const result = await this.ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse( + context.warehouseId + ); + const taskId = result && typeof result === 'object' + ? (result.taskId || result.task_id || result.id || null) + : result; + + this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] wave strategy quick scan triggered', { + warehouseId: context.warehouseId, + orderId: context.orderId, + taskId, + }); + }); + }); } } diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index b872f66..f623809 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -25,6 +25,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ '*', 'receiving_completed', 'order_cancel_intercepted', + 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', ]); const DRIVER_TYPE_ALIASES = Object.freeze({ diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index 788944a..704a5a3 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -3,6 +3,33 @@ const Service = require('egg').Service; const REVIEWED_INSPECTION_STATUS = 'fin'; +const PICK_MODE_VIEW_META_MAP = { + 1: { + mode_code: '1', + mode_name: '团购小波次', + require_box_allocations: true, + }, + 2: { + mode_code: '2', + mode_name: '散单单品单件', + require_box_allocations: false, + }, + 3: { + mode_code: '3', + mode_name: '散单先拣后分', + require_box_allocations: true, + }, + 4: { + mode_code: '4', + mode_name: '边拣边分', + require_box_allocations: true, + }, + 5: { + mode_code: '5', + mode_name: '团购大波次', + require_box_allocations: false, + }, +}; class PickSystemService extends Service { /** @@ -38,6 +65,436 @@ class PickSystemService extends Service { return error; } + /** + * 获取数据表列名集合。 + * + * 用于在不确定列是否存在时进行安全查询拼装,避免因列缺失导致 SQL 执行失败。 + * + * @param {string} tableName 数据表名。 + * @return {Promise>} 列名集合。 + */ + async getTableColumnSet(tableName) { + const { ctx } = this; + const normalizedTableName = String(tableName || '').trim(); + if (!normalizedTableName) { + return new Set(); + } + + const escapedTableName = normalizedTableName.replace(/`/g, '``'); + + try { + const rows = await ctx.model.query(`SHOW COLUMNS FROM \`${escapedTableName}\``, { + type: ctx.model.QueryTypes.SELECT, + }); + return new Set((Array.isArray(rows) ? rows : []) + .map(row => String(row && row.Field || '').trim()) + .filter(Boolean)); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 获取表字段失败,table=${normalizedTableName},将按兜底处理: ${error.message}`); + return new Set(); + } + } + + /** + * 读取订单商品分表数据并构建索引。 + * + * 优先使用 OrderItemsFactory 当前分表模型;若模型不可用或查询失败,返回空映射而不抛异常。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.orderItemIds 订单明细ID列表。 + * @return {Promise>} 订单明细映射。 + */ + async loadOrderItemMap(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const orderItemIds = Array.isArray(params && params.orderItemIds) + ? params.orderItemIds.filter(id => Number.isInteger(id) && id > 0) + : []; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderItemIds.length === 0) { + return new Map(); + } + + const factory = ctx.model && ctx.model.OrderItemsFactory; + if (!factory || typeof factory.getCurrentModel !== 'function') { + return new Map(); + } + + try { + const orderItemModel = await factory.getCurrentModel(warehouseId); + if (!orderItemModel || typeof orderItemModel.findAll !== 'function') { + return new Map(); + } + + const orderItemRows = await orderItemModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderItemIds, + }, + }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot' ], + raw: true, + }); + + return new Map((Array.isArray(orderItemRows) ? orderItemRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 订单商品分表查询失败,将按空字段降级: ${error.message}`); + return new Map(); + } + } + + /** + * 生成拣货明细汇总信息。 + * + * @param {Array} pickingDetails 拣货明细列表。 + * @return {{total_lines: number, total_qty: number, distinct_spaces: number, distinct_items: number}} 汇总结果。 + */ + buildPickingSummary(pickingDetails = []) { + const normalizedDetails = Array.isArray(pickingDetails) ? pickingDetails : []; + const distinctSpaceIds = new Set(); + const distinctItemKeys = new Set(); + + for (const detail of normalizedDetails) { + const spaceId = Number(detail && detail.space_id || 0); + if (spaceId > 0) { + distinctSpaceIds.add(spaceId); + } + + const itemCode = String(detail && detail.item_code || '').trim(); + const orderItemId = Number(detail && detail.order_item_id || 0); + if (itemCode) { + distinctItemKeys.add(`code:${itemCode}`); + } else if (orderItemId > 0) { + distinctItemKeys.add(`order_item_id:${orderItemId}`); + } + } + + return { + total_lines: normalizedDetails.length, + total_qty: normalizedDetails.reduce((sum, detail) => sum + Number(detail && detail.quantity || 0), 0), + distinct_spaces: distinctSpaceIds.size, + distinct_items: distinctItemKeys.size, + }; + } + + /** + * 获取拣货模式视图元信息。 + * + * @param {number} pickMode 拣货模式编码。 + * @return {{mode_code: number, mode_name: string, require_box_allocations: boolean}} 视图元信息。 + */ + getPickModeViewMeta(pickMode) { + const normalizedPickMode = Number(pickMode || 0); + const baseMeta = PICK_MODE_VIEW_META_MAP[normalizedPickMode] || { + mode_code: normalizedPickMode || 0, + mode_name: '未知模式', + require_box_allocations: false, + }; + + return { + mode_code: Number(baseMeta.mode_code || 0), + mode_name: String(baseMeta.mode_name || '').trim(), + require_box_allocations: Boolean(baseMeta.require_box_allocations), + }; + } + + /** + * 加载订单与波次映射关系。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.orderIds 订单ID列表。 + * @return {Promise>} 订单ID到wave_id映射。 + */ + async loadOrderWaveMap(params = {}) { + const { ctx } = this; + const warehouseId = Number(params && params.warehouseId || 0); + const orderIds = Array.isArray(params && params.orderIds) + ? params.orderIds.filter(id => Number.isInteger(id) && id > 0) + : []; + + if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { + return new Map(); + } + + try { + const orderModel = await this.getOrderModel(warehouseId); + const orderRows = await orderModel.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'wave_id' ], + raw: true, + }); + + return new Map((Array.isArray(orderRows) ? orderRows : []) + .map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ]) + .filter(([ orderId, waveId ]) => orderId > 0 && waveId > 0)); + } catch (error) { + ctx.logger.warn(`[pick.wavePickTaskDetail] 订单wave_id查询失败,将按空映射降级: ${error.message}`); + return new Map(); + } + } + + /** + * 构建按拣货模式区分的拣货形态视图。 + * + * @param {Object} params 构建参数。 + * @param {number} params.pickMode 拣货模式。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.pickingDetails 拣货明细。 + * @param {Array} params.boxRows 框明细。 + * @param {Array} params.taskOrderRows 任务订单关联明细。 + * @param {Map} params.boxMapByNo 框号到框信息映射。 + * @return {Promise} picking_view 结构。 + */ + async buildPickingView(params = {}) { + const { ctx } = this; + const pickMode = Number(params && params.pickMode || 0); + const taskId = Number(params && params.taskId || 0); + const warehouseId = Number(params && params.warehouseId || 0); + const pickingDetails = Array.isArray(params && params.pickingDetails) ? params.pickingDetails : []; + const boxRows = Array.isArray(params && params.boxRows) ? params.boxRows : []; + const taskOrderRows = Array.isArray(params && params.taskOrderRows) ? params.taskOrderRows : []; + const boxMapByNo = params && params.boxMapByNo instanceof Map ? params.boxMapByNo : new Map(); + const pickMeta = this.getPickModeViewMeta(pickMode); + + const groupMap = new Map(); + const buildGroupKey = detail => { + const spaceId = Number(detail && detail.space_id || 0); + const itemCode = String(detail && detail.item_code || '').trim(); + const stockId = Number(detail && detail.stock_id || 0); + if (itemCode) { + return `${spaceId}::${itemCode}`; + } + return `${spaceId}::stock_${stockId}`; + }; + + for (const detail of pickingDetails) { + const groupKey = buildGroupKey(detail); + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, { + space_id: Number(detail && detail.space_id || 0), + space_name: String(detail && detail.space_name || '').trim(), + location_space: detail && detail.location_space ? detail.location_space : null, + item_code: String(detail && detail.item_code || '').trim(), + item_name: String(detail && detail.item_name || '').trim(), + stock_id: Number(detail && detail.stock_id || 0), + total_qty: 0, + box_allocations: [], + details: [], + }); + } + const groupItem = groupMap.get(groupKey); + groupItem.total_qty += Number(detail && detail.quantity || 0); + groupItem.details.push(detail); + } + + const allocationMapByGroup = new Map(); + const appendAllocation = (groupKey, boxId, allocatedQty) => { + const normalizedBoxId = Number(boxId || 0); + const normalizedQty = Number(allocatedQty || 0); + if (normalizedBoxId <= 0 || normalizedQty <= 0) { + return; + } + if (!allocationMapByGroup.has(groupKey)) { + allocationMapByGroup.set(groupKey, new Map()); + } + const groupAllocationMap = allocationMapByGroup.get(groupKey); + groupAllocationMap.set( + normalizedBoxId, + Number(groupAllocationMap.get(normalizedBoxId) || 0) + normalizedQty + ); + }; + + if (pickMeta.require_box_allocations) { + if (pickMode === 4) { + const boxNosByOrderId = new Map(); + for (const row of taskOrderRows) { + const orderId = Number(row && row.order_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (orderId <= 0 || boxNo <= 0) { + continue; + } + if (!boxNosByOrderId.has(orderId)) { + boxNosByOrderId.set(orderId, new Set()); + } + boxNosByOrderId.get(orderId).add(boxNo); + } + + for (const [ groupKey, groupItem ] of groupMap) { + for (const detail of groupItem.details) { + const orderId = Number(detail && detail.order_id || 0); + const quantity = Number(detail && detail.quantity || 0); + const boxNos = boxNosByOrderId.get(orderId); + if (!boxNos || quantity <= 0) { + continue; + } + for (const boxNo of boxNos) { + const boxInfo = boxMapByNo.get(Number(boxNo || 0)); + const boxId = Number(boxInfo && boxInfo.box_id || 0); + appendAllocation(groupKey, boxId, quantity); + } + } + } + } else if (pickMode === 1) { + const taskWaveRows = await ctx.model.query(` + SELECT + ptw.wave_id, + ptw.box_no + FROM wms_wave_pick_task_wave ptw + WHERE ptw.task_id = :taskId + ORDER BY ptw.id ASC + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const waveToBoxNosMap = new Map(); + for (const row of Array.isArray(taskWaveRows) ? taskWaveRows : []) { + const waveId = Number(row && row.wave_id || 0); + const boxNo = Number(row && row.box_no || 0); + if (waveId <= 0 || boxNo <= 0) { + continue; + } + if (!waveToBoxNosMap.has(waveId)) { + waveToBoxNosMap.set(waveId, new Set()); + } + waveToBoxNosMap.get(waveId).add(boxNo); + } + + const orderIds = [ ...new Set(pickingDetails + .map(detail => Number(detail && detail.order_id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; + const orderWaveMap = await this.loadOrderWaveMap({ + warehouseId, + orderIds, + }); + + for (const [ groupKey, groupItem ] of groupMap) { + for (const detail of groupItem.details) { + const orderId = Number(detail && detail.order_id || 0); + const quantity = Number(detail && detail.quantity || 0); + const waveId = Number(orderWaveMap.get(orderId) || 0); + const boxNos = waveToBoxNosMap.get(waveId); + if (!boxNos || quantity <= 0) { + continue; + } + for (const boxNo of boxNos) { + const boxInfo = boxMapByNo.get(Number(boxNo || 0)); + const boxId = Number(boxInfo && boxInfo.box_id || 0); + appendAllocation(groupKey, boxId, quantity); + } + } + } + } else if (pickMode === 3) { + const boxMapByRefId = new Map(); + for (const row of boxRows) { + const refId = Number(row && row.ref_id || 0); + const boxId = Number(row && row.box_id || 0); + if (refId <= 0 || boxId <= 0) { + continue; + } + if (!boxMapByRefId.has(refId)) { + boxMapByRefId.set(refId, []); + } + boxMapByRefId.get(refId).push(row); + } + + for (const [ groupKey, groupItem ] of groupMap) { + const stockId = Number(groupItem && groupItem.stock_id || 0); + const targetBoxes = boxMapByRefId.get(stockId); + if (!Array.isArray(targetBoxes) || targetBoxes.length === 0) { + continue; + } + const groupQty = Number(groupItem && groupItem.total_qty || 0); + if (groupQty <= 0) { + continue; + } + for (const boxInfo of targetBoxes) { + appendAllocation(groupKey, Number(boxInfo && boxInfo.box_id || 0), groupQty); + } + } + } + } + + const itemList = Array.from(groupMap.entries()).map(([ groupKey, groupItem ]) => { + const groupAllocationMap = allocationMapByGroup.get(groupKey) || new Map(); + const boxAllocations = pickMeta.require_box_allocations + ? Array.from(groupAllocationMap.entries()) + .map(([ boxId, allocatedQty ]) => { + const boxInfo = boxRows.find(row => Number(row && row.box_id || 0) === Number(boxId || 0)) || {}; + return { + box_id: Number(boxInfo && boxInfo.box_id || 0), + box_no: Number(boxInfo && boxInfo.box_no || 0), + box_type: Number(boxInfo && boxInfo.box_type || 0), + required_qty: Number(boxInfo && boxInfo.required_qty || 0), + picked_qty: Number(boxInfo && boxInfo.picked_qty || 0), + allocated_qty: Number(allocatedQty || 0), + }; + }) + .sort((a, b) => { + const boxNoA = Number(a && a.box_no || 0); + const boxNoB = Number(b && b.box_no || 0); + if (boxNoA !== boxNoB) { + return boxNoA - boxNoB; + } + return Number(a && a.box_id || 0) - Number(b && b.box_id || 0); + }) + : []; + + return { + space_id: Number(groupItem && groupItem.space_id || 0), + space_name: String(groupItem && groupItem.space_name || '').trim(), + location_space: groupItem && groupItem.location_space ? groupItem.location_space : null, + item_code: String(groupItem && groupItem.item_code || '').trim(), + item_name: String(groupItem && groupItem.item_name || '').trim(), + stock_id: Number(groupItem && groupItem.stock_id || 0), + total_qty: Number(groupItem && groupItem.total_qty || 0), + box_allocations: boxAllocations, + }; + }); + + itemList.sort((a, b) => { + const sequenceA = Number(a && a.location_space && a.location_space.pick_sequence || 0); + const sequenceB = Number(b && b.location_space && b.location_space.pick_sequence || 0); + if (sequenceA !== sequenceB) { + return sequenceA - sequenceB; + } + + const priorityA = Number(a && a.location_space && a.location_space.pick_priority || 0); + const priorityB = Number(b && b.location_space && b.location_space.pick_priority || 0); + if (priorityA !== priorityB) { + return priorityA - priorityB; + } + + const spaceIdA = Number(a && a.space_id || 0); + const spaceIdB = Number(b && b.space_id || 0); + if (spaceIdA !== spaceIdB) { + return spaceIdA - spaceIdB; + } + + const itemCodeA = String(a && a.item_code || '').trim(); + const itemCodeB = String(b && b.item_code || '').trim(); + return itemCodeA.localeCompare(itemCodeB); + }); + + return { + mode_code: pickMeta.mode_code, + mode_name: pickMeta.mode_name, + require_box_allocations: pickMeta.require_box_allocations, + group_by: 'space+item', + sort_by: [ 'pick_sequence', 'pick_priority', 'space_id', 'item_code' ], + items: itemList, + }; + } + /** * 解析订单所属波次信息。 * @@ -324,6 +781,216 @@ class PickSystemService extends Service { fullDisplay, }); } + + /** + * 查询拣货任务详情。 + * + * 按 task_id 查询任务主信息,并返回与拣货直接相关的框明细与拣货明细; + * 仅允许任务创建人(pick_user_id)查看。 + * + * @param {Object} params 查询参数。 + * @param {number} params.taskId 任务ID。 + * @param {number} params.operatorId 当前操作人ID。 + * @return {Promise<{task: Object, boxes: Array, picking_details: Array, picking_summary: Object, picking_view: Object}>} 任务详情。 + */ + async wavePickTaskDetail(params = {}) { + const { ctx } = this; + const taskId = Number(params && params.taskId || 0); + const operatorId = Number(params && params.operatorId || 0); + + if (!Number.isInteger(taskId) || taskId <= 0) { + throw this.createBusinessError('task_id 必填且必须为正整数', 400); + } + if (!Number.isInteger(operatorId) || operatorId <= 0) { + throw this.createBusinessError('未获取到操作人上下文', 401); + } + + const taskRows = await ctx.model.query(` + SELECT + t.id AS task_id, + t.task_no, + t.status, + t.pick_mode, + t.pick_user_id, + t.start_time AS start_at, + t.finish_time AS finish_at, + t.batch_no, + t.warehouse_id + FROM wms_wave_pick_task t + WHERE t.id = :taskId + LIMIT 1 + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }); + + const taskRow = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null; + if (!taskRow) { + throw this.createBusinessError('拣货任务不存在', 404); + } + + const taskPickUserId = Number(taskRow.pick_user_id || 0); + if (!Number.isInteger(taskPickUserId) || taskPickUserId !== operatorId) { + throw this.createBusinessError('当前操作人与任务创建人不一致,无权查看', 403); + } + + const warehouseId = Number(taskRow.warehouse_id || 0); + const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box'); + const boxExtraSelect = []; + if (boxColumnSet.has('ref_label')) { + boxExtraSelect.push('b.ref_label'); + } + if (boxColumnSet.has('required_qty')) { + boxExtraSelect.push('b.required_qty'); + } + if (boxColumnSet.has('picked_qty')) { + boxExtraSelect.push('b.picked_qty'); + } + if (boxColumnSet.has('ref_id')) { + boxExtraSelect.push('b.ref_id'); + } + + const [ taskOrderRows, boxRows ] = await Promise.all([ + ctx.model.query(` + SELECT + pto.order_id, + pto.box_no + FROM wms_wave_pick_task_order pto + WHERE pto.task_id = :taskId + ORDER BY pto.id ASC + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }), + ctx.model.query(` + SELECT + b.id AS box_id, + b.box_no, + b.box_type, + b.box_status AS status${boxExtraSelect.length > 0 ? `,\n ${boxExtraSelect.join(',\n ')}` : ''} + FROM wms_wave_pick_task_box b + WHERE b.task_id = :taskId + ORDER BY b.id ASC + `, { + replacements: { taskId }, + type: ctx.model.QueryTypes.SELECT, + }), + ]); + + const normalizedTaskOrderRows = Array.isArray(taskOrderRows) ? taskOrderRows : []; + const orderIds = [ ...new Set(normalizedTaskOrderRows + .map(row => Number(row && row.order_id || 0)) + .filter(orderIdItem => Number.isInteger(orderIdItem) && orderIdItem > 0)) ]; + + const pickingRows = orderIds.length > 0 + ? await ctx.model.Picking.findAll({ + where: { + order_id: { + [this.app.Sequelize.Op.in]: orderIds, + }, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'storage_id', 'space_id', 'space_name' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }) + : []; + + const pickingSpaceIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : []) + .map(row => Number(row && row.space_id || 0)) + .filter(spaceId => Number.isInteger(spaceId) && spaceId > 0)) ]; + + const locationRows = pickingSpaceIds.length > 0 + ? await ctx.model.LocationSpace.findAll({ + where: { + id: { + [this.app.Sequelize.Op.in]: pickingSpaceIds, + }, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode', 'pick_sequence', 'pick_priority' ], + raw: true, + }) + : []; + + const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + + const orderItemIds = [ ...new Set((Array.isArray(pickingRows) ? pickingRows : []) + .map(row => Number(row && row.order_item_id || 0)) + .filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)) ]; + const orderItemMap = await this.loadOrderItemMap({ + warehouseId, + orderItemIds, + }); + const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : []; + const boxMapByNo = new Map(normalizedBoxRows + .map(row => [ Number(row && row.box_no || 0), row ]) + .filter(([ boxNo ]) => boxNo > 0)); + + const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => { + const orderItemId = Number(row && row.order_item_id || 0); + const currentSpaceId = Number(row && row.space_id || 0); + const locationRow = locationMap.get(currentSpaceId) || {}; + const orderItemRow = orderItemMap.get(orderItemId) || {}; + + return { + order_id: Number(row && row.order_id || 0), + order_item_id: orderItemId, + quantity: Number(row && row.quantity || 0), + storage_id: Number(row && row.storage_id || 0), + space_id: currentSpaceId, + space_name: String(row && row.space_name || '').trim(), + location_space: { + space_code: String(locationRow.space_code || '').trim(), + custom_name: String(locationRow.custom_name || '').trim(), + custom_barcode: String(locationRow.custom_barcode || '').trim(), + pick_sequence: Number(locationRow.pick_sequence || 0), + pick_priority: Number(locationRow.pick_priority || 0), + }, + item_code: String(orderItemRow.item_code || '').trim(), + item_name: String(orderItemRow.item_name || '').trim(), + stock_id: Number(orderItemRow.stock_id || 0), + plan_qty: Number(orderItemRow.plan_qty || 0), + item_snapshot: orderItemRow.item_snapshot || null, + }; + }); + + const pickingSummary = this.buildPickingSummary(pickingDetails); + const pickMode = Number(taskRow.pick_mode || 0); + const pickingView = await this.buildPickingView({ + pickMode, + taskId, + warehouseId, + pickingDetails, + boxRows: normalizedBoxRows, + taskOrderRows: normalizedTaskOrderRows, + boxMapByNo, + }); + + return { + task: { + task_id: Number(taskRow.task_id || 0), + task_no: String(taskRow.task_no || '').trim(), + status: Number(taskRow.status || 0), + pick_mode: pickMode, + start_at: taskRow.start_at || null, + finish_at: taskRow.finish_at || null, + batch_no: String(taskRow.batch_no || '').trim(), + }, + boxes: normalizedBoxRows.map(row => ({ + box_id: Number(row && row.box_id || 0), + box_no: Number(row && row.box_no || 0), + box_type: Number(row && row.box_type || 0), + status: Number(row && row.status || 0), + ref_id: Number(row && row.ref_id || 0), + ref_label: String(row && row.ref_label || '').trim() || null, + required_qty: Number(row && row.required_qty || 0), + picked_qty: Number(row && row.picked_qty || 0), + })), + picking_details: pickingDetails, + picking_summary: pickingSummary, + picking_view: pickingView, + }; + } } module.exports = PickSystemService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 82d0099..7104df9 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -2,6 +2,9 @@ const { Service } = require('egg'); +const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version'; +const DEFAULT_WAVE_STRATEGY_VERSION = 1; + // 仓库设置字段元信息(对应 wms_store.subject_config) const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ @@ -61,11 +64,11 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ }), Object.freeze({ key: 'delete_order_wave_prefix', - name: '删单波次前缀', + name: '散单波次前缀', type: 'string', default: 'A', required: false, - description: '删单波次编号前缀,最多 5 个字符,默认 A', + description: '散单波次编号前缀,最多 5 个字符,默认 A', maxLength: 5, }), Object.freeze({ @@ -88,9 +91,151 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ value: 'async', label: '异步回调' }), ], }), + Object.freeze({ + key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, + name: '仓库波次策略版本号', + type: 'integer', + default: DEFAULT_WAVE_STRATEGY_VERSION, + required: false, + description: '内部字段:仓库波次策略版本号', + min: 0, + hidden: true, + internal: true, + }), ]); class SettingWarehouseService extends Service { + /** + * 读取默认快递与平台编码选项,查询失败时自动降级为空列表。 + * + * @return {Promise} 返回字段 key 到 options 的映射。 + */ + async getDefaultCodeFieldOptionsMap() { + const modelContainer = this.ctx && this.ctx.model ? this.ctx.model : (this.app && this.app.model ? this.app.model : {}); + const expressModel = modelContainer && modelContainer.Express; + const platformModel = modelContainer && modelContainer.Platform; + + const fetchOptions = async model => { + if (!model || typeof model.findAll !== 'function') { + return []; + } + + try { + const rows = await model.findAll({ + attributes: [ 'code', 'name' ], + order: [[ 'code', 'ASC' ]], + }); + + if (!Array.isArray(rows)) { + return []; + } + + return rows + .map(item => { + const code = item && item.code !== undefined && item.code !== null ? String(item.code) : ''; + if (!code) { + return null; + } + + const name = item && item.name !== undefined && item.name !== null ? String(item.name) : ''; + return { + value: code, + label: name || code, + }; + }) + .filter(Boolean); + } catch (_error) { + return []; + } + }; + + const [ expressOptions, platformOptions ] = await Promise.all([ + fetchOptions(expressModel), + fetchOptions(platformModel), + ]); + + return { + default_express_code: expressOptions, + default_platform_code: platformOptions, + }; + } + + /** + * 规范化仓库波次策略版本号,返回数字。 + * + * @param {number|string|null|undefined} value 原始版本号。 + * @param {Object} [options={}] 额外选项。 + * @param {boolean} [options.useDefaultWhenEmpty=false] 空值时是否使用默认值。 + * @return {number} 规范化后的版本号数字。 + * @throws {Error} 输入不合法时抛出,状态码 400。 + */ + normalizeWaveStrategyVersion(value, options = {}) { + const { useDefaultWhenEmpty = false } = options; + if (value === undefined || value === null || value === '') { + if (useDefaultWhenEmpty) { + return DEFAULT_WAVE_STRATEGY_VERSION; + } + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + if (typeof value === 'number') { + if (!Number.isSafeInteger(value) || value < 0) { + throw this.createError('subject_config.wave_strategy_version 必须是非负整数', 400); + } + return value; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) { + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + const numericVersion = Number(trimmed); + if (!Number.isSafeInteger(numericVersion)) { + throw this.createError('subject_config.wave_strategy_version 超出安全整数范围', 400); + } + + return numericVersion; + } + + throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); + } + + /** + * 规范化 subject_config 内部字段,确保内部字段落库时为数字。 + * + * @param {Object} subjectConfig 原始配置对象。 + * @return {Object} 规范化后的配置对象。 + */ + normalizeSubjectConfigInternalFields(subjectConfig) { + const nextConfig = { + ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), + }; + + nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY] = this.normalizeWaveStrategyVersion( + nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY], + { useDefaultWhenEmpty: true } + ); + + return nextConfig; + } + + /** + * 对外响应时移除内部字段,避免暴露内部配置。 + * + * @param {Object} subjectConfig 配置对象。 + * @return {Object} 过滤后的配置对象。 + */ + sanitizeSubjectConfigForOutput(subjectConfig) { + const nextConfig = { + ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), + }; + + delete nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; + return nextConfig; + } + createError(message, code = 500) { const error = new Error(message); error.code = code; @@ -155,21 +300,31 @@ class SettingWarehouseService extends Service { /** * 获取仓库设置字段元信息列表。 * - * @return {Array} 字段元信息数组(浅拷贝,含 options 拷贝)。 + * @return {Promise} 字段元信息数组(浅拷贝,含 options 拷贝)。 */ - getFieldMeta() { - return WAREHOUSE_SETTING_FIELDS.map(field => ({ - key: field.key, - name: field.name, - type: field.type, - default: field.default, - required: field.required, - description: field.description, - ...(Array.isArray(field.options) ? { options: field.options.map(o => ({ ...o })) } : {}), - ...(field.min !== undefined ? { min: field.min } : {}), - ...(field.max !== undefined ? { max: field.max } : {}), - ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), - })); + async getFieldMeta() { + const dynamicOptionsMap = await this.getDefaultCodeFieldOptionsMap(); + + return WAREHOUSE_SETTING_FIELDS + .filter(field => !field.internal && field.key !== INTERNAL_WAVE_STRATEGY_VERSION_KEY) + .map(field => ({ + key: field.key, + name: field.name, + type: field.type, + default: field.default, + required: field.required, + description: field.description, + ...((Array.isArray(field.options) || Object.prototype.hasOwnProperty.call(dynamicOptionsMap, field.key)) + ? { + options: (Array.isArray(field.options) ? field.options.map(o => ({ ...o })) : (dynamicOptionsMap[field.key] || [])).map(o => ({ ...o })), + } + : {}), + ...(field.min !== undefined ? { min: field.min } : {}), + ...(field.max !== undefined ? { max: field.max } : {}), + ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), + ...(field.hidden !== undefined ? { hidden: field.hidden } : {}), + ...(field.internal !== undefined ? { internal: field.internal } : {}), + })); } /** @@ -189,9 +344,11 @@ class SettingWarehouseService extends Service { throw this.createError('仓库不存在', 404); } + const normalizedSubjectConfig = this.normalizeSubjectConfigInternalFields(store.subject_config); + return { warehouse_id: warehouseId, - subject_config: store.subject_config, + subject_config: this.sanitizeSubjectConfigForOutput(normalizedSubjectConfig), }; } @@ -224,16 +381,23 @@ class SettingWarehouseService extends Service { throw this.createError('subject_config 参数不能为空且必须是对象', 400); } - const mergedConfig = { - ...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}), + const nextPatchForMerge = { ...nextPatch, }; + delete nextPatchForMerge[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; + + const mergedConfig = { + ...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}), + ...nextPatchForMerge, + }; + + const mergedConfigWithInternalDefaults = this.normalizeSubjectConfigInternalFields(mergedConfig); let normalizedConfig; try { normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function' - ? storeModel.normalizeSubjectConfig(mergedConfig) - : mergedConfig; + ? storeModel.normalizeSubjectConfig(mergedConfigWithInternalDefaults) + : mergedConfigWithInternalDefaults; } catch (error) { throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400); } @@ -248,7 +412,7 @@ class SettingWarehouseService extends Service { return { warehouse_id: warehouseId, - subject_config: store.subject_config, + subject_config: this.sanitizeSubjectConfigForOutput(store.subject_config), cache_cleared_warehouse_id: cacheWarehouseId, }; } diff --git a/database/config.js b/database/config.js index c745540..312e2b4 100644 --- a/database/config.js +++ b/database/config.js @@ -69,7 +69,22 @@ if (process.env.DB_HOST) { const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); const appConfig = mergeDeep(defaultConfig, localConfig); const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; - mysqlClient = resolveMysqlClient(appConfig, clientName); + if (isProduction) { + const sequelizeConfig = appConfig && appConfig.sequelize; + if (sequelizeConfig && sequelizeConfig.host) { + mysqlClient = { + host: sequelizeConfig.host, + port: sequelizeConfig.port || 3306, + user: sequelizeConfig.username || sequelizeConfig.user, + password: sequelizeConfig.password, + database: sequelizeConfig.database || 'wms', + }; + } else { + mysqlClient = resolveMysqlClient(appConfig, clientName); + } + } else { + mysqlClient = resolveMysqlClient(appConfig, clientName); + } } const baseConfig = { diff --git a/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js index b7a3fa6..c309e73 100644 --- a/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js +++ b/database/migrations/20260506103000-add-box-fields-to-wms_receiving_detail.js @@ -1,5 +1,28 @@ 'use strict'; +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [ rows ] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + /** * Migration: add box_remainder and box_weight to wms_receiving_detail * - box_remainder: INT NOT NULL DEFAULT 0 COMMENT '箱余数' @@ -16,8 +39,15 @@ */ module.exports = { + /** + * 执行正向迁移,按需新增收货明细箱字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ up: async (queryInterface, Sequelize) => { const table = 'wms_receiving_detail'; + await logMigrationDbContext(queryInterface, 'up', table); const columns = await queryInterface.describeTable(table); if (!columns.box_remainder) { @@ -39,8 +69,15 @@ module.exports = { } }, + /** + * 执行回滚迁移,按需删除收货明细箱字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ down: async (queryInterface, Sequelize) => { const table = 'wms_receiving_detail'; + await logMigrationDbContext(queryInterface, 'down', table); const columns = await queryInterface.describeTable(table); if (columns.box_remainder) { diff --git a/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js b/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js new file mode 100644 index 0000000..786dc12 --- /dev/null +++ b/database/migrations/20260507002000-rename-wms_picking_strategy-to-wms_wave_strategy.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * 将拣货策略表重命名为波次策略表。 + * 幂等处理:仅在源表存在且目标表不存在时执行重命名。 + */ +module.exports = { + /** + * 升级迁移:wms_picking_strategy -> wms_wave_strategy。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + */ + up: async queryInterface => { + const sourceTable = 'wms_picking_strategy'; + const targetTable = 'wms_wave_strategy'; + const allTables = await queryInterface.showAllTables(); + const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName))); + + if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } + }, + + /** + * 回滚迁移:wms_wave_strategy -> wms_picking_strategy。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + */ + down: async queryInterface => { + const sourceTable = 'wms_wave_strategy'; + const targetTable = 'wms_picking_strategy'; + const allTables = await queryInterface.showAllTables(); + const tableNames = new Set(allTables.map(table => (typeof table === 'string' ? table : table.tableName))); + + if (tableNames.has(sourceTable) && !tableNames.has(targetTable)) { + await queryInterface.renameTable(sourceTable, targetTable); + } + }, +}; diff --git a/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js b/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js new file mode 100644 index 0000000..3456fc5 --- /dev/null +++ b/database/migrations/20260507100000-create-wms_order_wave_strategy_match.js @@ -0,0 +1,70 @@ +'use strict'; + +/** + * Migration: 创建 wms_order_wave_strategy_match 表 + * + * 记录每个订单命中的全部波次策略 ID,作为快速扫描结果的副表存储。 + * 不与分仓主表做物理外键,靠应用层逻辑维护一致性。 + * + * 索引: + * idx_warehouse_order (warehouse_id, order_id) — 按订单删除/查询 + * idx_warehouse_strategy (warehouse_id, strategy_id) — 按策略聚合统计 + */ + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tableExists = await queryInterface.showAllTables() + .then(tables => tables.includes('wms_order_wave_strategy_match')); + + if (tableExists) { + return; + } + + await queryInterface.createTable('wms_order_wave_strategy_match', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: Sequelize.INTEGER(10), + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID,逻辑关联分仓主表,不做物理外键', + }, + strategy_id: { + type: Sequelize.INTEGER(10), + allowNull: false, + comment: '命中的波次策略ID', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '写入时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '订单波次策略命中明细表', + }); + + await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'order_id' ], { + name: 'idx_warehouse_order', + }); + + await queryInterface.addIndex('wms_order_wave_strategy_match', [ 'warehouse_id', 'strategy_id' ], { + name: 'idx_warehouse_strategy', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable('wms_order_wave_strategy_match'); + }, +}; diff --git a/database/migrations/20260508123000-create-wave-pick-task-tables.js b/database/migrations/20260508123000-create-wave-pick-task-tables.js new file mode 100644 index 0000000..f496bfb --- /dev/null +++ b/database/migrations/20260508123000-create-wave-pick-task-tables.js @@ -0,0 +1,1108 @@ +'use strict'; + +/** + * 获取当前数据库已存在的表名集合。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 表名集合。 + */ +const getExistingTableSet = async queryInterface => { + const tables = await queryInterface.showAllTables(); + return new Set( + tables.map(table => (typeof table === 'string' ? table : table.tableName)) + ); +}; + +/** + * 构建通用时间字段。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {{create_time: object, update_time: object}} 时间字段定义。 + */ +const buildTimeColumns = Sequelize => ({ + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + update_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, +}); + +/** + * 创建波次拣货任务主表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickTaskTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_no: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '任务编号', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + pick_mode: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '拣货模式:1-小团购 2-单品单件 3-先拣后分 4-边拣边分 5-大团购', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '任务状态:0-待开始 1-拣货中 2-待复核 3-已完成 9-已取消', + }, + source: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '任务来源:1-PDA 2-后台', + }, + wave_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '波次数量', + }, + order_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '订单数量', + }, + box_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '框数量', + }, + batch_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '领单批次号', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货员名称', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '复核员名称', + }, + current_cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定拣货车ID', + }, + current_cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '当前绑定车码快照', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-未就绪 1-待复核 2-复核中 3-复核通过 4-复核异常', + }, + review_version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '复核并发版本号', + }, + review_start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核开始时间', + }, + review_finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核结束时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + expire_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '任务过期时间', + }, + transfer_from_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移来源任务ID', + }, + transfer_to_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移目标任务ID', + }, + start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '开始拣货时间', + }, + finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '完成拣货时间', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核完成时间', + }, + remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '备注', + }, + ext_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务主表', + }); + + await queryInterface.addIndex('wms_wave_pick_task', [ 'task_no' ], { + unique: true, + name: 'uk_task_no', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'warehouse_id', 'status' ], { + name: 'idx_warehouse_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'pick_user_id', 'status' ], { + name: 'idx_pick_user_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'warehouse_id', 'review_status' ], { + name: 'idx_warehouse_review_status', + }); + await queryInterface.addIndex('wms_wave_pick_task', [ 'current_cart_id', 'review_status' ], { + name: 'idx_current_cart_review_status', + }); +}; + +/** + * 创建任务与波次关联表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskWaveTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_wave', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '波次ID', + }, + wave_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '波次号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:0-待拣 1-已拣 2-异常', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务与波次关联表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_wave', [ 'task_id', 'wave_id' ], { + unique: true, + name: 'uk_task_wave', + }); + await queryInterface.addIndex('wms_wave_pick_task_wave', [ 'warehouse_id', 'wave_id' ], { + name: 'idx_warehouse_wave', + }); +}; + +/** + * 创建任务订单明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskOrderTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_order', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID', + }, + order_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '订单号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + pick_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '拣货状态:0-待拣货 1-已拣货', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-待复核 1-已复核 2-异常', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + exception_reason: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '异常原因', + }, + picked_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核完成时间', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务订单表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'order_id' ], { + unique: true, + name: 'uk_task_order', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'warehouse_id', 'order_id' ], { + name: 'idx_warehouse_order', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'pick_status' ], { + name: 'idx_task_pick_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'task_id', 'review_status' ], { + name: 'idx_task_review_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_order', [ 'cart_id' ], { + name: 'idx_cart_id', + }); +}; + +/** + * 创建任务箱明细表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskBoxTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_task_box', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '订单ID', + }, + box_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '箱号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + box_type: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '框类型:1-SKU框 2-订单框 3-波次框', + }, + ref_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '关联ID(SKU或订单或波次)', + }, + ref_label: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '关联展示标签', + }, + required_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '应放数量', + }, + picked_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已放数量', + }, + box_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '箱状态:0-待拣货 1-已拣货 2-已复核', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-缺件 3-多件', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货任务箱明细表', + }); + + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_code' ], { + unique: true, + name: 'uk_task_box', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'order_id' ], { + name: 'idx_order_id', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_status' ], { + name: 'idx_task_box_status', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'task_id', 'box_no' ], { + name: 'idx_task_box_no', + }); + await queryInterface.addIndex('wms_wave_pick_task_box', [ 'ref_id' ], { + name: 'idx_ref_id', + }); +}; + +/** + * 创建拣货车表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createPickCartTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pick_cart', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + cart_code: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '拣货车编码', + }, + cart_name: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '拣货车名称', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '状态:0-停用 1-启用', + }, + current_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定任务ID', + }, + bind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定人ID', + }, + last_bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近绑定时间', + }, + last_seen_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近扫码时间', + }, + ext_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展信息', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '拣货车主表', + }); + + await queryInterface.addIndex('wms_pick_cart', [ 'warehouse_id', 'cart_code' ], { + unique: true, + name: 'uk_warehouse_cart_code', + }); + await queryInterface.addIndex('wms_pick_cart', [ 'status' ], { + name: 'idx_status', + }); + await queryInterface.addIndex('wms_pick_cart', [ 'current_task_id' ], { + name: 'idx_current_task_id', + }); +}; + +/** + * 创建任务拣货车绑定表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createTaskCartBindingTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_pick_task_cart_binding', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '车码快照', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + bind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '绑定人ID', + }, + bind_type: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '绑定类型:1-领单绑定 2-换车绑定 3-管理员改绑', + }, + unbind_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '解绑人ID', + }, + is_active: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '是否有效绑定:0-无效 1-有效', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '绑定时间', + }, + unbind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '解绑时间', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '任务拣货车绑定关系表', + }); + + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'task_id', 'is_active' ], { + name: 'idx_task_active', + }); + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'cart_id', 'is_active' ], { + name: 'idx_cart_active', + }); + await queryInterface.addIndex('wms_pick_task_cart_binding', [ 'warehouse_id', 'is_active' ], { + name: 'idx_warehouse_active', + }); +}; + +/** + * 创建订单拣货轨迹表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createOrderPickTraceTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_order_pick_trace', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '订单ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '任务ID', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货时间', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + event_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '轨迹事件类型', + }, + event_desc: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '轨迹描述', + }, + operator_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '操作人名称', + }, + snapshot: { + type: Sequelize.JSON, + allowNull: true, + comment: '轨迹快照', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '订单拣货轨迹审计表', + }); + + await queryInterface.addIndex('wms_order_pick_trace', [ 'warehouse_id', 'order_id', 'create_time' ], { + name: 'idx_warehouse_order_create_time', + }); + await queryInterface.addIndex('wms_order_pick_trace', [ 'task_id' ], { + name: 'idx_task_id', + }); + await queryInterface.addIndex('wms_order_pick_trace', [ 'cart_id', 'create_time' ], { + name: 'idx_cart_id_create_time', + }); +}; + +/** + * 创建波次拣货动作日志表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickActionLogTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_action_log', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + wave_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '波次ID', + }, + order_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '订单ID', + }, + sku_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '商品ID', + }, + location_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '库位ID', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + qty_delta: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '数量变化', + }, + action_type: { + type: Sequelize.STRING(32), + allowNull: false, + comment: '动作类型(enter_location/scan_sku/put_box/rollback/exception)', + }, + request_id: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '幂等请求ID', + }, + operator_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '操作人ID', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + seq_no: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '序列号', + }, + snapshot: { + type: Sequelize.JSON, + allowNull: true, + comment: '动作快照', + }, + create_time: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货动作日志表', + }); + + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'request_id' ], { + unique: true, + name: 'uk_request_id', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'task_id', 'create_time' ], { + name: 'idx_task_create_time', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'warehouse_id', 'action_type', 'create_time' ], { + name: 'idx_warehouse_action_time', + }); + await queryInterface.addIndex('wms_wave_pick_action_log', [ 'order_id', 'create_time' ], { + name: 'idx_order_create_time', + }); +}; + +/** + * 创建波次拣货断点检查点表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ +const createWavePickCheckpointTable = async (queryInterface, Sequelize) => { + await queryInterface.createTable('wms_wave_pick_checkpoint', { + id: { + type: Sequelize.BIGINT, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + task_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '任务ID', + }, + warehouse_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '仓库ID', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: false, + comment: '拣货员ID', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: false, + comment: '设备ID', + }, + current_location_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前库位ID', + }, + current_sku_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前商品ID', + }, + current_box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '当前框号', + }, + picked_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已拣数量', + }, + remaining_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '剩余数量', + }, + last_event_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '最新事件ID', + }, + last_seq_no: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '最新序列号', + }, + checkpoint_json: { + type: Sequelize.JSON, + allowNull: true, + comment: '检查点快照', + }, + version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '乐观锁版本号', + }, + ...buildTimeColumns(Sequelize), + }, { + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '波次拣货断点检查点表', + }); + + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'task_id', 'pick_user_id', 'device_id' ], { + unique: true, + name: 'uk_task_user_device', + }); + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'task_id', 'update_time' ], { + name: 'idx_task_update_time', + }); + await queryInterface.addIndex('wms_wave_pick_checkpoint', [ 'pick_user_id', 'device_id' ], { + name: 'idx_user_device', + }); +}; + +module.exports = { + /** + * 执行正向迁移,创建波次拣货任务相关 9 张新表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const existingTables = await getExistingTableSet(queryInterface); + + if (!existingTables.has('wms_wave_pick_task')) { + await createWavePickTaskTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task'); + } + if (!existingTables.has('wms_wave_pick_task_wave')) { + await createTaskWaveTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_wave'); + } + if (!existingTables.has('wms_wave_pick_task_order')) { + await createTaskOrderTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_order'); + } + if (!existingTables.has('wms_wave_pick_task_box')) { + await createTaskBoxTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_task_box'); + } + if (!existingTables.has('wms_pick_cart')) { + await createPickCartTable(queryInterface, Sequelize); + existingTables.add('wms_pick_cart'); + } + if (!existingTables.has('wms_pick_task_cart_binding')) { + await createTaskCartBindingTable(queryInterface, Sequelize); + existingTables.add('wms_pick_task_cart_binding'); + } + if (!existingTables.has('wms_order_pick_trace')) { + await createOrderPickTraceTable(queryInterface, Sequelize); + existingTables.add('wms_order_pick_trace'); + } + if (!existingTables.has('wms_wave_pick_action_log')) { + await createWavePickActionLogTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_action_log'); + } + if (!existingTables.has('wms_wave_pick_checkpoint')) { + await createWavePickCheckpointTable(queryInterface, Sequelize); + existingTables.add('wms_wave_pick_checkpoint'); + } + }, + + /** + * 执行回滚迁移,按依赖逆序删除波次拣货任务相关 9 张表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + await queryInterface.dropTable('wms_wave_pick_checkpoint'); + await queryInterface.dropTable('wms_wave_pick_action_log'); + await queryInterface.dropTable('wms_order_pick_trace'); + await queryInterface.dropTable('wms_pick_task_cart_binding'); + await queryInterface.dropTable('wms_pick_cart'); + await queryInterface.dropTable('wms_wave_pick_task_box'); + await queryInterface.dropTable('wms_wave_pick_task_order'); + await queryInterface.dropTable('wms_wave_pick_task_wave'); + await queryInterface.dropTable('wms_wave_pick_task'); + }, +}; diff --git a/database/migrations/20260508140000-add-source-to-wave-batch.js b/database/migrations/20260508140000-add-source-to-wave-batch.js new file mode 100644 index 0000000..fd6f149 --- /dev/null +++ b/database/migrations/20260508140000-add-source-to-wave-batch.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为波次表新增 source 字段。 + * + * 字段语义:0-普通波次 1-管理后台策略任务 2-PDA策略任务 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + up: async queryInterface => { + const tableName = 'wms_wave_batch'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (!columnsBefore.source) { + await queryInterface.sequelize.query(` + ALTER TABLE wms_wave_batch + ADD COLUMN source TINYINT NOT NULL DEFAULT 0 + COMMENT '来源:0-普通波次 1-管理后台策略任务 2-PDA策略任务' + AFTER update_time + `); + } + + const columnsAfter = await getTableColumns(queryInterface, tableName); + if (!columnsAfter.source) { + throw new Error('迁移失败:wms_wave_batch.source 字段不存在'); + } + }, + + /** + * 回滚迁移:删除波次表 source 字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const tableName = 'wms_wave_batch'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (columnsBefore.source) { + await queryInterface.removeColumn(tableName, 'source'); + } + }, +}; diff --git a/database/migrations/20260508150000-add-source-to-wave-pick-task.js b/database/migrations/20260508150000-add-source-to-wave-pick-task.js new file mode 100644 index 0000000..09061ef --- /dev/null +++ b/database/migrations/20260508150000-add-source-to-wave-pick-task.js @@ -0,0 +1,50 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +module.exports = { + /** + * 正向迁移:为拣货任务表补充 source 字段。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (!columnsBefore.source) { + await queryInterface.addColumn(tableName, 'source', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '任务来源:1-PDA 2-后台', + }); + } + }, + + /** + * 回滚迁移:若 source 字段存在则删除。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const tableName = 'wms_wave_pick_task'; + const columnsBefore = await getTableColumns(queryInterface, tableName); + + if (columnsBefore.source) { + await queryInterface.removeColumn(tableName, 'source'); + } + }, +}; diff --git a/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js b/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js new file mode 100644 index 0000000..9dce366 --- /dev/null +++ b/database/migrations/20260508163000-repair-wave-pick-task-schema-drift.js @@ -0,0 +1,349 @@ +'use strict'; + +/** + * 获取表字段定义。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {string} tableName 表名。 + * @return {Promise} 字段定义对象。 + */ +const getTableColumns = async (queryInterface, tableName) => { + return queryInterface.describeTable(tableName); +}; + +/** + * 返回需要补齐的字段定义映射。 + * + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Record>} 表字段映射。 + */ +const getRepairColumnDefinitions = Sequelize => ({ + wms_wave_pick_task: { + wave_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '波次数量', + }, + order_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '订单数量', + }, + box_count: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '框数量', + }, + batch_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '领单批次号', + }, + pick_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货员名称', + }, + review_user_name: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '复核员名称', + }, + current_cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '当前绑定拣货车ID', + }, + current_cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '当前绑定车码快照', + }, + review_status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '复核状态:0-未就绪 1-待复核 2-复核中 3-复核通过 4-复核异常', + }, + review_version: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '复核并发版本号', + }, + review_start_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核开始时间', + }, + review_finish_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核结束时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + device_id: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '设备ID', + }, + expire_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '任务过期时间', + }, + transfer_from_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移来源任务ID', + }, + transfer_to_task_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '转移目标任务ID', + }, + }, + wms_wave_pick_task_wave: { + wave_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '波次号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + status: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '波次状态:0-待拣 1-已拣 2-异常', + }, + bind_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '绑定时间', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货完成时间', + }, + }, + wms_wave_pick_task_order: { + order_no: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '订单号', + }, + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + review_remark: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '复核备注', + }, + exception_reason: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '异常原因', + }, + }, + wms_wave_pick_task_box: { + box_no: { + type: Sequelize.INTEGER, + allowNull: true, + comment: '框号', + }, + box_type: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '框类型:1-SKU框 2-订单框 3-波次框', + }, + ref_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '关联ID(SKU或订单或波次)', + }, + ref_label: { + type: Sequelize.STRING(128), + allowNull: true, + comment: '关联展示标签', + }, + required_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '应放数量', + }, + picked_qty: { + type: Sequelize.INTEGER, + allowNull: false, + defaultValue: 0, + comment: '已放数量', + }, + }, + wms_pick_cart: { + last_seen_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '最近扫码时间', + }, + }, + wms_pick_task_cart_binding: { + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '车码快照', + }, + bind_type: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 1, + comment: '绑定类型:1-领单绑定 2-换车绑定 3-管理员改绑', + }, + }, + wms_order_pick_trace: { + cart_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货车ID', + }, + cart_code_snapshot: { + type: Sequelize.STRING(64), + allowNull: true, + comment: '拣货车码快照', + }, + pick_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '拣货员ID', + }, + pick_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '拣货时间', + }, + review_user_id: { + type: Sequelize.BIGINT, + allowNull: true, + comment: '复核员ID', + }, + review_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '复核时间', + }, + review_result: { + type: Sequelize.TINYINT, + allowNull: true, + comment: '复核结果:1-通过 2-异常', + }, + }, +}); + +/** + * 按字段映射执行幂等新增列。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Record>} repairColumnDefinitions 表字段映射。 + * @return {Promise} 无返回值。 + */ +const addMissingColumns = async (queryInterface, repairColumnDefinitions) => { + const tableNames = Object.keys(repairColumnDefinitions); + + for (const tableName of tableNames) { + const columnsBefore = await getTableColumns(queryInterface, tableName); + const columnEntries = Object.entries(repairColumnDefinitions[tableName]); + + for (const [ columnName, columnDefinition ] of columnEntries) { + if (!columnsBefore[columnName]) { + await queryInterface.addColumn(tableName, columnName, columnDefinition); + } + } + } +}; + +/** + * 按字段映射执行幂等删除列。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {Record>} repairColumnDefinitions 表字段映射。 + * @return {Promise} 无返回值。 + */ +const removeExistingColumns = async (queryInterface, repairColumnDefinitions) => { + const tableNames = Object.keys(repairColumnDefinitions); + + for (const tableName of tableNames) { + const columnsBefore = await getTableColumns(queryInterface, tableName); + const columnEntries = Object.keys(repairColumnDefinitions[tableName]); + + for (const columnName of columnEntries) { + if (columnsBefore[columnName]) { + await queryInterface.removeColumn(tableName, columnName); + } + } + } +}; + +module.exports = { + /** + * 正向迁移:修复拣货任务相关表的字段漂移问题。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize); + await addMissingColumns(queryInterface, repairColumnDefinitions); + }, + + /** + * 回滚迁移:回退本迁移新增的字段(仅在字段存在时删除)。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + const repairColumnDefinitions = getRepairColumnDefinitions(Sequelize); + await removeExistingColumns(queryInterface, repairColumnDefinitions); + }, +}; diff --git a/methods/changes/2026.05.08-system-06.json b/methods/changes/2026.05.08-system-06.json new file mode 100644 index 0000000..66a7b16 --- /dev/null +++ b/methods/changes/2026.05.08-system-06.json @@ -0,0 +1,16 @@ +[ + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json index 74ee9f7..9085f09 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,250 @@ [ + { + "version": "2026.05.10-system-04", + "date": "2026-05-10", + "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", + "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", + "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-02", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", + "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", + "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-03", + "date": "2026-05-10", + "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", + "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", + "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", + "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-01", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "新增 strategy_type 过滤,仅 1/2", + "支持顶层 strategy_type 和 where.strategy_type,顶层优先", + "当前不引入其他 where 字段" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-02", + "date": "2026-05-09", + "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", + "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", + "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-04", + "date": "2026-05-08", + "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", + "methods": [ + "order.wave.wavePickTaskList", + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", + "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", + "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", + "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", + "默认排序:create_time desc.", + "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-03", + "date": "2026-05-08", + "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", + "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", + "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", + "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-02", + "date": "2026-05-08", + "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetch", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "waveStrategyFetchPda 仅用于 PDA 场景", + "waveStrategyFetchAdmin 仅用于后台管理场景", + "两者当前均为壳子受理方法,不执行真实抓取" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-01", + "date": "2026-05-08", + "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", + "methods": [ + "order.wave.waveStrategyFetch" + ], + "notes": [ + "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-05", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", + "methods": [ + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", + "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", + "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", + "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-06", + "date": "2026-05-07", + "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", + "methods": [ + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleFetchByIds" + ], + "notes": [ + "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", + "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", + "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-04", + "date": "2026-05-07", + "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-03", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", + "methods": [ + "order.wave.waveStrategyQuickScan", + "order.wave.waveStrategyQuickScanTaskProgress" + ], + "notes": [ + "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-02", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-01", + "date": "2026-05-07", + "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", + "methods": [ + "order.wave.singleOrderFetchDetailList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "移除 order.wave.singleOrderFetchDetailList。", + "新增 order.wave.waveStrategyFallbackOrderList。", + "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-06", + "date": "2026-05-06", + "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", + "methods": [ + "order.wave.singleOrderFetchDetailList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", + "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", + "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", + "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" + ], + "type": "added" + }, { "version": "2026.05.06-system-05", "date": "2026-05-06", @@ -44,8 +290,6 @@ "version": "2026.05.06-system-02", "date": "2026-05-06", "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", - "date": "2026-05-06", - "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", "methods": [ "order.wave.singleFetchByIds" ], @@ -238,7 +482,7 @@ "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" ], - "type": "added" + "type": "updated" }, { "version": "2026.04.22-system-01", @@ -1274,5 +1518,39 @@ "仓库上下文来自当前登录用户(ctx.user.store_id)。" ], "type": "updated" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + } + + , + { + "version": "2026.05.09-system-01", + "date": "2026-05-09", + "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", + "methods": [ + "order.wave.wavePickTaskCancelSelf", + "order.wave.waveStrategyList" + ], + "notes": [ + "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", + "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", + "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", + "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", + "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", + "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" + ], + "type": "added" } ] diff --git a/methods/system.json b/methods/system.json index cd6cb17..d4d8b79 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "2026.05.03-system-10", - "updatedAt": "2026-05-03", + "version": "2026.05.08-system-05", + "updatedAt": "2026-05-08", "headers": [ { "name": "platform", @@ -2492,6 +2492,1076 @@ "groupName": "订单波次模块", "module": "order.wave", "list": [ + { + "method": "order.wave.waveStrategyList", + "description": "查询当前仓库波次策略列表。仅查询当前登录仓库在 wms_wave_strategy 中的数据,返回标准 list/pagination 结构。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "strategy_type", + "type": "number", + "required": false, + "source": "body", + "description": "仅支持 1=散单、2=团购;与 where.strategy_type 同时存在时以顶层 strategy_type 为准。" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "当前仅支持 where.strategy_type(1/2);其余 where 字段暂不支持。" + }, + { + "name": "calculate_next_fetch_order_count / calculateNextFetchOrderCount", + "type": "number", + "required": false, + "source": "body", + "description": "0-不计算(默认),1-计算并返回每条策略的 next_fetch_order_count;支持别名 calculateNextFetchOrderCount" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "策略列表,每项为波次策略记录", + "children": [ + { + "name": "id", + "type": "number", + "description": "策略ID" + }, + { + "name": "strategy_name", + "type": "string", + "description": "策略名称" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "strategy_type", + "type": "number", + "description": "策略类型:1-散单 2-团购" + }, + { + "name": "status", + "type": "number", + "description": "状态:1-启用 0-停用" + }, + { + "name": "order_min_sku", + "type": "number", + "description": "订单最小 SKU 种类数(可为空)" + }, + { + "name": "order_max_sku", + "type": "number", + "description": "订单最大 SKU 种类数(可为空)" + }, + { + "name": "order_min_qty", + "type": "number", + "description": "订单最小商品总数(可为空)" + }, + { + "name": "order_max_qty", + "type": "number", + "description": "订单最大商品总数(可为空)" + }, + { + "name": "min_same_structure", + "type": "number", + "description": "最小相同结构订单数(可为空)" + }, + { + "name": "max_same_structure", + "type": "number", + "description": "最大相同结构订单数(可为空)" + }, + { + "name": "require_same_express", + "type": "boolean", + "description": "是否要求相同快递" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "description": "是否允许跨货主" + }, + { + "name": "batch_mode", + "type": "number", + "description": "拣货模式" + }, + { + "name": "batch_max_orders", + "type": "number", + "description": "批次最大订单数(可为空)" + }, + { + "name": "batch_max_skus", + "type": "number", + "description": "批次最大 SKU 总数(可为空)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "description": "团购批次最大订单数(可为空)" + }, + { + "name": "allowed_owners", + "type": "array", + "description": "允许的货主 ID 列表(数组或 null)" + }, + { + "name": "allowed_expresses", + "type": "array", + "description": "允许的快递编码列表(数组或 null)" + }, + { + "name": "allowed_provinces", + "type": "array", + "description": "允许的省份列表(数组或 null)" + }, + { + "name": "allowed_platforms", + "type": "array", + "description": "允许的平台列表(数组或 null)" + }, + { + "name": "description", + "type": "string", + "description": "策略描述" + }, + { + "name": "creator_name", + "type": "string", + "description": "创建人" + }, + { + "name": "create_time", + "type": "string", + "description": "创建时间(ISO 字符串)" + }, + { + "name": "update_time", + "type": "string", + "description": "更新时间(ISO 字符串)" + }, + { + "name": "matched_order_count_filtered", + "type": "number", + "description": "按当前仓库且仅统计未在波次(step!=0)并满足同结构区间后的命中订单数" + }, + { + "name": "next_fetch_order_count", + "type": "number", + "description": "按当前策略口径预演一次自动抓取时,预计会选中的订单数量;未开启计算时返回 0" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少仓库上下文或分页参数不合法" + }, + { + "code": "400", + "description": "strategy_type 非法(仅支持 1/2)" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "order.wave.waveStrategyCreate", + "description": "新增波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。创建成功后会推进仓库的 wave_strategy_version 并失效相关缓存。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_name", + "type": "string", + "required": true, + "source": "body", + "description": "策略名称(必填)" + }, + { + "name": "strategy_type", + "type": "number", + "required": true, + "source": "body", + "description": "策略类型(必填,正整数):1-散单 2-团购" + }, + { + "name": "batch_mode", + "type": "number", + "required": true, + "source": "body", + "description": "拣货模式(必填,正整数)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1-启用 0-停用(可选)" + }, + { + "name": "order_min_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_max_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_min_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小商品总数(可选,正整数或 null)" + }, + { + "name": "order_max_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大商品总数(可选,正整数或 null)" + }, + { + "name": "min_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最小相同结构订单数(可选,正整数或 null)" + }, + { + "name": "max_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最大相同结构订单数(可选,正整数或 null)。注意:若传入值 >= 仓库配置的 min_group_order_fetch_quantity,则会被下调为 min_group_order_fetch_quantity - 1,最小为 1。" + }, + { + "name": "batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大订单数(可选)" + }, + { + "name": "batch_max_skus", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大 SKU 总数(可选)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "团购批次最大订单数(可选)" + }, + { + "name": "require_same_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否要求相同快递(可选,布尔)" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否允许跨货主(可选,布尔)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "策略描述(可选)" + }, + { + "name": "allowed_provinces", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的省份列表(可选,支持数组、JSON 字符串或逗号分隔字符串)" + }, + { + "name": "allowed_platforms", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的平台列表(可选,支持数组、JSON 字符串或逗号分隔字符串)" + }, + { + "name": "allowed_owners", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的货主列表(可选,支持数组/JSON/逗号分隔);系统会校验所传货主是否在仓库可用货主范围内,非法值将导致 400 错误。" + }, + { + "name": "allowed_expresses", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "创建的策略对象,字段同 order.wave.waveStrategyList.list[*] 所示" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "HTTP-like 状态码,成功时返回 200" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少必填参数或参数校验失败(包括 allowed_owners/allowed_expresses 非法)" + }, + { + "code": "500", + "description": "创建失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyUpdate", + "description": "修改波次策略。warehouse_id 与 creator_name 强制使用当前上下文,不接受外部覆盖。id(或 strategy_id/strategyId)为必填主键,其他字段为可选更新;更新成功后会推进仓库的 wave_strategy_version 并失效相关缓存。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id / strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略主键,兼容 id / strategy_id / strategyId(必填)" + }, + { + "name": "strategy_name", + "type": "string", + "required": false, + "source": "body", + "description": "策略名称(可选)" + }, + { + "name": "strategy_type", + "type": "number", + "required": false, + "source": "body", + "description": "策略类型(可选,正整数)" + }, + { + "name": "batch_mode", + "type": "number", + "required": false, + "source": "body", + "description": "拣货模式(可选,正整数)" + }, + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态:1-启用 0-停用(可选)" + }, + { + "name": "order_min_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_max_sku", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大 SKU 种类数(可选,正整数或 null)" + }, + { + "name": "order_min_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最小商品总数(可选,正整数或 null)" + }, + { + "name": "order_max_qty", + "type": "number", + "required": false, + "source": "body", + "description": "订单最大商品总数(可选,正整数或 null)" + }, + { + "name": "min_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最小相同结构订单数(可选,正整数或 null)" + }, + { + "name": "max_same_structure", + "type": "number", + "required": false, + "source": "body", + "description": "最大相同结构订单数(可选,正整数或 null)。会受仓库 min_group_order_fetch_quantity 约束,接口会自动调整。" + }, + { + "name": "batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大订单数(可选)" + }, + { + "name": "batch_max_skus", + "type": "number", + "required": false, + "source": "body", + "description": "批次最大 SKU 总数(可选)" + }, + { + "name": "group_batch_max_orders", + "type": "number", + "required": false, + "source": "body", + "description": "团购批次最大订单数(可选)" + }, + { + "name": "require_same_express", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否要求相同快递(可选,布尔)" + }, + { + "name": "allow_cross_owner", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否允许跨货主(可选,布尔)" + }, + { + "name": "description", + "type": "string", + "required": false, + "source": "body", + "description": "策略描述(可选)" + }, + { + "name": "allowed_provinces", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的省份列表(可选,支持数组/JSON/逗号分隔)" + }, + { + "name": "allowed_platforms", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的平台列表(可选,支持数组/JSON/逗号分隔)" + }, + { + "name": "allowed_owners", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的货主列表(可选,支持数组/JSON/逗号分隔);系统会校验所传货主是否在仓库可用货主范围内,非法值将导致 400 错误。" + }, + { + "name": "allowed_expresses", + "type": "array|string", + "required": false, + "source": "body", + "description": "允许的快递编码列表(可选,支持数组/JSON/逗号分隔);系统会校验所传编码是否在可用快递列表内,非法值将导致 400 错误。" + } + ], + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的策略对象,字段同 order.wave.waveStrategyList.list[*] 所示" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "HTTP-like 状态码,成功时返回 200" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 id 或无可更新字段或参数校验失败" + }, + { + "code": "404", + "description": "波次策略不存在" + }, + { + "code": "500", + "description": "更新失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyQuickScan", + "description": "提交波次策略快速扫描异步任务。无外部参数,使用当前仓库上下文;同一仓库同一时刻仅允许一个任务运行,若已有运行任务直接返回已有 task_id。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "status", + "type": "string", + "required": true, + "description": "提交状态,固定 success" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务 ID(用于后续查询进度)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库 ID(来自当前上下文)" + }, + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态(一般为 submitted 或 running)" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息" + }, + { + "name": "accepted_at", + "type": "string", + "required": false, + "description": "任务受理时间(ISO 字符串)" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "任务提交失败或内部错误" + } + ] + }, + { + "method": "order.wave.waveStrategyFetchPda", + "description": "按策略提交并创建抓取主流程任务(PDA)。当前为最小主流程:进行入参校验并创建任务记录,返回创建结果与计划预览;后续扫描/执行阶段将扩展为完整执行流。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID(正整数,支持下划线/驼峰)" + }, + { + "name": "cart_id / cartId", + "type": "string|number", + "required": false, + "source": "body", + "description": "可选,关联拣货车/作业车ID,支持字符串或数字,用于记录作业上下文" + }, + { + "name": "source / operation_source", + "type": "string", + "required": false, + "source": "body", + "description": "可选,操作来源标识(例如 pda/admin/manual/auto),用于审计与分流策略" + }, + { + "name": "strategy_params / strategyParams", + "type": "object", + "required": false, + "source": "body", + "description": "可选,策略参数透传对象(如 order_min_qty/order_max_qty/allow_cross_owner 等),在创建任务时作为策略覆盖或附加参数使用" + } + ], + "response": [ + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:created(已创建主流程任务),后续可能为 running/success/failed" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务唯一 ID(用于后续查询或关联)" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "任务业务编号(便于展示与关联)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(来自当前上下文,如可用则返回)" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "description": "生效的策略 ID(与入参保持一致,兼容回传)" + }, + { + "name": "plan", + "type": "object", + "required": true, + "description": "任务计划/执行预览对象,描述本次任务预估的执行计划", + "children": [ + { + "name": "estimated_wave_count", + "type": "number", + "description": "预估将创建的波次数量(若适用)" + }, + { + "name": "estimated_order_count", + "type": "number", + "description": "预估涉及的订单数量" + }, + { + "name": "estimated_items_total", + "type": "number", + "description": "预估涉及的商品总件数" + }, + { + "name": "preview_orders", + "type": "array", + "description": "可选:示例性订单 ID 列表或摘要(仅为预览,实际执行结果以最终任务为准)" + } + ] + }, + { + "name": "plan_summary", + "type": "string", + "required": true, + "description": "计划摘要字符串,便于前端在受理后快速展示(例如:'创建 3 个波次,涉及 120 单,约 450 件')" + }, + { + "name": "validation_errors", + "type": "array", + "required": false, + "description": "当入参校验失败时返回的数组,每项为 { field, message } 对象,供前端展示或定位问题" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息或错误说明(创建失败时返回简短说明)" + }, + { + "name": "fetch_state", + "type": "number", + "required": true, + "description": "抓取结果三态:1=成功创建任务(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可进入拣货流程)" + }, + { + "name": "tip", + "type": "string", + "required": false, + "description": "简短提示,用于向前端展示简要原因或下一步建议" + }, + { + "name": "can_enter_pick_flow", + "type": "boolean", + "required": false, + "description": "仅当 fetch_state=3 时为 true,表示前端可直接进入拣货流程" + } + ], + "errors": [ + { + "code": "400", + "description": "参数校验失败(详见 validation_errors)" + }, + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "创建任务失败或内部错误,message 字段含简短说明" + } + ] + }, + { + "method": "order.wave.waveStrategyFetchAdmin", + "description": "按策略提交并创建抓取主流程任务(后台管理)。当前为最小主流程:执行入参校验并创建任务记录,返回创建结果与计划预览;后续将扩展完整扫描/执行链路。 注意:当存在未完成任务时,接口返回 fetch_state=3 且同时返回 existing task_id/task_no,前端可直接进入拣货流程。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "strategy_id / strategyId", + "type": "number", + "required": true, + "source": "body", + "description": "策略ID(正整数,支持下划线/驼峰)" + }, + { + "name": "cart_id / cartId", + "type": "string|number", + "required": false, + "source": "body", + "description": "可选,关联拣货车/作业车ID,用于记录作业上下文或幂等识别" + }, + { + "name": "source / operation_source", + "type": "string", + "required": false, + "source": "body", + "description": "可选,操作来源标识(例如 admin/pda/manual/auto),用于审计与分流策略" + }, + { + "name": "strategy_params / strategyParams", + "type": "object", + "required": false, + "source": "body", + "description": "可选,策略参数透传对象(如 order_min_qty/order_max_qty/allow_cross_owner 等),在创建任务时作为策略覆盖或附加参数使用" + } + ], + "response": [ + { + "name": "state", + "type": "string", + "required": true, + "description": "任务状态:created(已创建主流程任务),后续可能为 running/success/failed" + }, + { + "name": "task_id", + "type": "string", + "required": true, + "description": "任务唯一 ID(用于后续查询或关联)" + }, + { + "name": "task_no", + "type": "string", + "required": true, + "description": "任务业务编号(便于展示与关联)" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "description": "生效的仓库 ID(来自当前上下文,如可用则返回)" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "description": "生效的策略 ID(与入参保持一致,兼容回传)" + }, + { + "name": "plan", + "type": "object", + "required": true, + "description": "任务计划/执行预览对象,描述本次任务预估的执行计划", + "children": [ + { + "name": "estimated_wave_count", + "type": "number", + "description": "预估将创建的波次数量(若适用)" + }, + { + "name": "estimated_order_count", + "type": "number", + "description": "预估涉及的订单数量" + }, + { + "name": "estimated_items_total", + "type": "number", + "description": "预估涉及的商品总件数" + }, + { + "name": "preview_orders", + "type": "array", + "description": "可选:示例性订单 ID 列表或摘要(仅为预览,实际执行结果以最终任务为准)" + } + ] + }, + { + "name": "plan_summary", + "type": "string", + "required": true, + "description": "计划摘要字符串,便于前端在受理后快速展示(例如:'创建 3 个波次,涉及 120 单,约 450 件')" + }, + { + "name": "validation_errors", + "type": "array", + "required": false, + "description": "当入参校验失败时返回的数组,每项为 { field, message } 对象,供前端展示或定位问题" + }, + { + "name": "message", + "type": "string", + "required": false, + "description": "可选提示信息或错误说明(创建失败时返回简短说明)" + }, + { + "name": "fetch_state", + "type": "number", + "required": true, + "description": "抓取结果三态:1=成功创建任务(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可进入拣货流程)" + }, + { + "name": "tip", + "type": "string", + "required": false, + "description": "简短提示,用于向前端展示简要原因或下一步建议" + }, + { + "name": "can_enter_pick_flow", + "type": "boolean", + "required": false, + "description": "仅当 fetch_state=3 时为 true,表示前端可直接进入拣货流程" + } + ], + "errors": [ + { + "code": "400", + "description": "参数校验失败(详见 validation_errors)" + }, + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "创建任务失败或内部错误,message 字段含简短说明" + } + ] + }, + { + "method": "order.wave.waveStrategyQuickScanTaskProgress", + "description": "查询波次策略快速扫描任务进度。接受 task_id / taskId,若未找到返回 state='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", + "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" + }, + { + "name": "total_order_count", + "type": "number", + "required": false, + "description": "扫描订单总数" + }, + { + "name": "processed_order_count", + "type": "number", + "required": false, + "description": "已处理订单数" + }, + { + "name": "matched_order_count", + "type": "number", + "required": false, + "description": "命中策略的订单数" + }, + { + "name": "unmatched_order_count", + "type": "number", + "required": false, + "description": "未命中策略的订单数" + }, + { + "name": "progress_percent", + "type": "number", + "required": false, + "description": "进度百分比(0-100)" + }, + { + "name": "submitted_at", + "type": "string", + "required": false, + "description": "提交时间(timestamp 或 ISO)" + }, + { + "name": "start_time", + "type": "string", + "required": false, + "description": "实际开始时间(ISO)" + }, + { + "name": "end_time", + "type": "string", + "required": false, + "description": "结束时间(ISO)" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(若失败)" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(若失败)" + }, + { + "name": "duration_ms", + "type": "number", + "required": false, + "description": "耗时,毫秒" + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 参数不能为空" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, { "method": "order.wave.groupOrderFetchList", "description": "按机器结构分组的可抓取列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。", @@ -2600,7 +3670,7 @@ "type": "array|string|number", "required": true, "source": "body", - "description": "订单ID列表,支持数组、逗号分隔字符串或单个ID;优先使用 ids 字段" + "description": "订单 ID 列表;支持数组、逗号分隔字符串或单个 ID。入参会被去重并转换为正整数。字段解析优先顺序:ids -> order_ids -> orderIds。" } ], "response": [ @@ -2626,37 +3696,37 @@ "name": "fetched_order_ids", "type": "array", "required": true, - "description": "实际被抓取并分配到波次的订单ID列表" + "description": "实际被抓取并成功分配到波次的订单 ID 列表(为归一化后的 ids 的子集)" }, { "name": "fetched_order_count", "type": "number", "required": true, - "description": "实际被抓取的订单数量" + "description": "实际被抓取的订单数量(等于 fetched_order_ids.length)" }, { "name": "excluded_existing_wave_order_ids", "type": "array", "required": false, - "description": "原始入参中已在其它波次中的订单ID(被排除)" + "description": "原始入参中已在其它波次中的订单 ID(被排除,不会被抓取)" }, { "name": "skipped_order_ids", "type": "array", "required": false, - "description": "未被抓取的订单ID(包括已存在波次、状态不符或出库中等)" + "description": "因订单状态不符、正在出库或其他业务原因被跳过的订单 ID(不会被抓取)" }, { "name": "not_found_order_ids", "type": "array", "required": false, - "description": "入参中未在数据库中找到的订单ID" + "description": "入参中未在数据库中找到的订单 ID" } ], "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误" + "description": "未识别到当前仓库上下文或 ids 参数不能为空或格式错误;当入参包含非法字段或别名冲突时也会返回 400" }, { "code": "500", @@ -2664,6 +3734,112 @@ } ] }, + { + "method": "order.wave.waveStrategyFallbackOrderList", + "description": "基于波次策略的回退候选订单列表。该接口内置固定筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。用于展示策略未命中但需回退处理的订单候选。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选白名单字段(object)。仅支持下列字段,且禁止传入 warehouse_id / warehouseId:\n- id(等值)\n- delivery_no / deliveryNo(模糊)\n- tracking_no / trackingNo(模糊)\n- items_count_min / items_count_max(范围)\n- items_total_min / items_total_max(范围)\n- sys_logistics_name(模糊)\n- store_name(模糊)\n- owner_name(等值)\n- province(模糊)\n- sys_platform_name(模糊)\n说明:若传入未列出的字段或禁止字段(如 warehouse_id)接口会返回 400。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "回退候选订单简要列表。数组内对象字段说明见 children。", + "children": [ + { + "name": "id", + "type": "number", + "description": "订单 ID" + }, + { + "name": "delivery_no", + "type": "string", + "description": "配送单号" + }, + { + "name": "tracking_no", + "type": "string", + "description": "运单号" + }, + { + "name": "items_count", + "type": "number", + "description": "SKU 种类数" + }, + { + "name": "items_total", + "type": "number", + "description": "总件数" + }, + { + "name": "sys_logistics_name", + "type": "string", + "description": "系统快递名称" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "province", + "type": "string", + "description": "省/直辖市" + }, + { + "name": "sys_platform_name", + "type": "string", + "description": "平台名称" + }, + { + "name": "item_snapshot", + "type": "string", + "description": "商品快照,格式示例:苹果*2|香蕉*3" + } + ] + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "未识别到当前仓库上下文或 where 中包含非法/禁止字段(如 warehouse_id)或存在别名冲突" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } + ] + }, { "method": "order.wave.singleOrderFetchList", "description": "按机器结构分组的散单候选列表。仅处理待处理订单(排除待审核),且排除已在波次中的订单。与 order.wave.groupOrderFetchList 不同:groupOrderFetchList 返回满足同组订单数量 >= same_order_quantity(或仓库配置 min_group_order_fetch_quantity)的团购命中分组;singleOrderFetchList 则排除这些团购命中分组,仅返回同组订单数量小于该阈值的散单候选分组(即 < same_order_quantity)。", @@ -2754,8 +3930,8 @@ ] }, { - "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者的仓库ID作为查询约束(禁止传入 warehouse_id / warehouseId)。支持通过白名单字段进行过滤(通过 where 对象传入),接口对 wave_status 固定叠加查询状态 0/1,无需客户端传入。列表按订单数量从大到小排序,并附带波次基础信息与分配状态汇总。", + "method": "order.wave.wavePickTaskList", + "description": "按当前仓库分页查询拣货任务列表。支持顶层分页参数 `page_no`/`page_size`(兼容 `pagination` 对象与 `current/size`),支持 `status` 单值或数组;兼容历史 `where` 结构,顶层参数优先。默认按 create_time desc 排序。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2767,19 +3943,124 @@ } ], "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID(必填)" + }, { "name": "pagination", "type": "object", "required": false, "source": "body", - "description": "分页参数,支持 page / pageSize" + "description": "分页参数,支持 page / pageSize,兼容 current / size(兼容旧客户端)" + }, + { + "name": "page_no", + "type": "number", + "required": false, + "source": "body", + "description": "页码(优先于 pagination.page/current)" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "每页大小(优先于 pagination.pageSize/size)" + }, + { + "name": "status", + "type": "array", + "required": false, + "source": "body", + "description": "拣货任务状态过滤;建议传数组,也兼容单值或逗号分隔字符串,兼容 where.status;顶层参数优先" + }, + { + "name": "review_status", + "type": "number", + "required": false, + "source": "body", + "description": "复核状态过滤" + }, + { + "name": "pick_mode", + "type": "number", + "required": false, + "source": "body", + "description": "拣货模式(如批量/逐单等)" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "任务来源标识(业务端语义)" + }, + { + "name": "pick_user_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货执行人ID(兼容旧字段)" + }, + { + "name": "review_user_id", + "type": "number", + "required": false, + "source": "body", + "description": "复核人ID" + }, + { + "name": "task_no", + "type": "string", + "required": false, + "source": "body", + "description": "任务编号(支持模糊匹配)" + }, + { + "name": "cart_id", + "type": "number", + "required": false, + "source": "body", + "description": "拣货车/作业车ID" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字搜索:支持 task_no / batch_no / current_cart_code_snapshot 等字段的模糊匹配" + }, + { + "name": "start_time_start", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间(ISO 字符串),与 start_time_end 一起用于时间范围过滤" + }, + { + "name": "start_time_end", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间(ISO 字符串),与 start_time_start 一起用于时间范围过滤" }, { "name": "where", "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。" + "description": "兼容历史 where 结构(可包含 status 等字段);当存在顶层同名参数时,顶层参数优先" + }, + { + "name": "strategy_id", + "type": "number", + "required": false, + "source": "body", + "description": "策略ID(当前主表未存,该接口会忽略此过滤,建议勿使用)" } ], "response": [ @@ -2787,19 +4068,120 @@ "name": "list", "type": "array", "required": true, - "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" + "description": "拣货任务列表(数组),每项字段如下", + "children": [ + { + "name": "task_id", + "type": "number", + "description": "任务ID" + }, + { + "name": "task_no", + "type": "string", + "description": "任务编号" + }, + { + "name": "status", + "type": "number", + "description": "任务状态" + }, + { + "name": "source", + "type": "string", + "description": "来源" + }, + { + "name": "pick_mode", + "type": "number", + "description": "拣货模式" + }, + { + "name": "wave_count", + "type": "number", + "description": "关联波次数" + }, + { + "name": "order_count", + "type": "number", + "description": "订单数量" + }, + { + "name": "box_count", + "type": "number", + "description": "箱数" + }, + { + "name": "operator_id", + "type": "number", + "description": "操作人ID(兼容旧字段 pick_user_id)" + }, + { + "name": "operator_name", + "type": "string", + "description": "操作人名称(兼容旧字段 pick_user_name)" + }, + { + "name": "pick_user_id", + "type": "number", + "description": "拣货人ID(兼容字段,旧客户端可能使用)" + }, + { + "name": "pick_user_name", + "type": "string", + "description": "拣货人名称(兼容字段,旧客户端可能使用)" + }, + { + "name": "start_at", + "type": "string", + "description": "开始时间(ISO 字符串,兼容 start_time)" + }, + { + "name": "finish_at", + "type": "string", + "description": "完成时间(ISO 字符串,兼容 finish_time)" + }, + { + "name": "start_time", + "type": "string", + "description": "开始时间(ISO 字符串,兼容字段)" + }, + { + "name": "finish_time", + "type": "string", + "description": "完成时间(ISO 字符串,兼容字段)" + }, + { + "name": "created_at", + "type": "string", + "description": "创建时间(ISO 字符串,兼容 create_time)" + }, + { + "name": "create_time", + "type": "string", + "description": "创建时间(ISO 字符串,兼容字段)" + } + ] }, { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + "name": "total", + "type": "number", + "description": "总记录数" + }, + { + "name": "page", + "type": "number", + "description": "当前页码" + }, + { + "name": "page_size", + "type": "number", + "description": "每页大小" } ], "errors": [ { "code": "400", - "description": "未识别到当前仓库上下文" + "description": "缺少仓库上下文或参数格式错误" }, { "code": "500", @@ -2807,6 +4189,124 @@ } ] }, + { + "method": "order.wave.wavePickTaskCancel", + "description": "取消拣货任务(批量),同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。入参仅支持 task_ids(数组,必填),不再支持单个 task_id。操作人与仓库从请求上下文获取(例如当前登录用户上下文 ctx.user),若上下文缺失接口将返回错误。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_ids", + "type": "array", + "required": true, + "source": "body", + "description": "任务ID数组,例如 [123,124];仅支持批量处理,不再支持单个 task_id。" + } + ], + "response": [ + { + "name": "cancelled_count", + "type": "number", + "description": "成功取消的任务数量" + }, + { + "name": "task_ids", + "type": "array", + "description": "处理的任务ID数组(若后端返回)" + }, + { + "name": "task_nos", + "type": "array", + "description": "处理的任务编号数组(若后端返回)" + }, + { + "name": "task_id", + "type": "number", + "description": "任务ID(历史兼容,若后端仍返回)" + }, + { + "name": "task_no", + "type": "string", + "description": "任务编号(历史兼容,若后端仍返回)" + } + ], + "errors": [ + { + "code": "400", + "description": "任务状态不允许取消或入参缺失" + }, + { + "code": "404", + "description": "任务不存在" + }, + { + "code": "500", + "description": "内部错误或事务回滚失败" + } + ] + }, + { + "method": "order.wave.wavePickTaskCancelSelf", + "description": "取消单个拣货任务(仅允许取消当前操作人本人创建的任务;仅支持单个 task_id,明确不支持 task_ids)", + "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(仅支持单个,不支持 task_ids)" + } + ], + "response": [ + { + "name": "cancelled_count", + "type": "number", + "description": "成功取消的任务数量(0 或 1)" + }, + { + "name": "task_id", + "type": "number", + "description": "被处理的任务ID" + }, + { + "name": "task_no", + "type": "string", + "description": "被处理的任务编号(若后端返回)" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法(task_id 缺失或同时传入 task_ids)" + }, + { + "code": "400", + "description": "仅允许取消本人创建任务" + }, + { + "code": "500", + "description": "取消失败" + } + ] + }, { "method": "order.wave.batchCancel", "description": "提交批量解除波次异步任务。该接口为异步任务提交接口,立即返回 task_id,后端异步按当前仓库 + wave_ids 拉取待处理波次并执行解除操作;可通过 order.wave.batchCancelTaskProgress 查询进度与结果。", @@ -8830,6 +10330,166 @@ "description": "内部错误" } ] + }, + { + "method": "pick.wavePickTaskDetail", + "description": "按任务ID获取拣货任务详情,返回精简的 task、boxes、picking_details 与 picking_summary;仅允许任务的 pick_user_id 与当前登录用户(operator_id/employees_id)一致时返回数据,否则返回 403。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "number", + "required": true, + "source": "body", + "description": "wms_wave_pick_task 主键 ID" + } + ], + "response": [ + { + "name": "task", + "type": "object", + "description": "拣货任务主表(精简字段)", + "children": [ + { "name": "task_id", "type": "number", "description": "任务ID" }, + { "name": "task_no", "type": "string", "description": "任务编号" }, + { "name": "status", "type": "number", "description": "任务状态" }, + { "name": "pick_mode", "type": "number", "description": "拣货模式" }, + { "name": "start_at", "type": "string", "description": "开始时间(ISO 字符串或 null)" }, + { "name": "finish_at", "type": "string", "description": "完成时间(ISO 字符串或 null)" }, + { "name": "batch_no", "type": "string", "description": "批次号" } + ] + }, + { + "name": "boxes", + "type": "array", + "description": "箱列表;包含用于前端展示与拣货进度的统计字段", + "children": [ + { "name": "task_id", "type": "number", "description": "任务ID" }, + { "name": "box_id", "type": "number", "description": "箱ID" }, + { "name": "box_no", "type": "string", "description": "箱编码" }, + { "name": "box_type", "type": "number", "description": "箱类型" }, + { "name": "status", "type": "number", "description": "箱状态" }, + { "name": "ref_label", "type": "string", "description": "箱参考标签或关联业务标识(用于前端定位/关联)" }, + { "name": "required_qty", "type": "number", "description": "箱内需要拣货的总数量" }, + { "name": "picked_qty", "type": "number", "description": "当前已完成拣货的数量" } + ] + }, + { + "name": "picking_details", + "type": "array", + "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求", + "children": [ + { "name": "order_id", "type": "number", "description": "订单ID" }, + { "name": "order_item_id", "type": "number", "description": "订单行ID" }, + { "name": "quantity", "type": "number", "description": "本行需拣货数量" }, + { "name": "storage_id", "type": "number", "description": "仓库ID" }, + { "name": "space_id", "type": "number", "description": "库位ID" }, + { "name": "space_name", "type": "string", "description": "库位名称" }, + { + "name": "location_space", + "type": "object", + "description": "库位扩展信息(当存在时返回)", + "children": [ + { "name": "space_code", "type": "string", "description": "库位编码" }, + { "name": "custom_name", "type": "string", "description": "库位自定义名称" }, + { "name": "custom_barcode", "type": "string", "description": "库位自定义条码" }, + { "name": "pick_sequence", "type": "number", "description": "拣货序列,用于路线/优先级排序" }, + { "name": "pick_priority", "type": "number", "description": "拣货优先级(数值越小优先级越高)" } + ] + }, + { "name": "item_code", "type": "string", "description": "商品编码" }, + { "name": "item_name", "type": "string", "description": "商品名称" }, + { "name": "stock_id", "type": "number", "description": "库存记录ID(stock 主键)" }, + { "name": "plan_qty", "type": "number", "description": "计划拣货数量(用于与实际拣货对比)" }, + { "name": "item_snapshot", "type": "object", "description": "商品快照(下单时的商品信息,可能包含规格/属性等)" } + ] + }, + { + "name": "picking_summary", + "type": "object", + "description": "对 picking_details 的汇总信息,用于统计与前端显示", + "children": [ + { "name": "total_lines", "type": "number", "description": "明细行数(picking_details.length)" }, + { "name": "total_qty", "type": "number", "description": "明细总数量(quantity 汇总)" }, + { "name": "distinct_spaces", "type": "number", "description": "涉及的不同库位数量" }, + { "name": "distinct_items", "type": "number", "description": "涉及的不同商品数量" } + ] + }, + { + "name": "picking_view", + "type": "object", + "description": "按 pick_mode 区分的 picking_view 形态输出(五种形态);用于前端按任务类型展示聚合视图。", + "children": [ + { "name": "mode_code", "type": "number", "description": "拣货视图模式编码,与 task.pick_mode 对应" }, + { "name": "mode_name", "type": "string", "description": "拣货视图模式名称" }, + { "name": "require_box_allocations", "type": "boolean", "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false" }, + { "name": "group_by", "type": "string", "description": "分组字段,示例值:\"space+item\"" }, + { "name": "sort_by", "type": "array", "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]" }, + { + "name": "items", + "type": "array", + "description": "分组后的拣货项数组(按库位+商品聚合)", + "children": [ + { "name": "space_id", "type": "number", "description": "库位 ID" }, + { "name": "space_name", "type": "string", "description": "库位名称" }, + { + "name": "location_space", + "type": "object", + "description": "库位扩展信息(同 picking_details.location_space 结构)", + "children": [ + { "name": "space_code", "type": "string", "description": "库位编码" }, + { "name": "custom_name", "type": "string", "description": "库位自定义名称" }, + { "name": "custom_barcode", "type": "string", "description": "库位自定义条码" }, + { "name": "pick_sequence", "type": "number", "description": "拣货序列,用于路线/优先级排序" }, + { "name": "pick_priority", "type": "number", "description": "拣货优先级(数值越小优先)" } + ] + }, + { "name": "item_code", "type": "string", "description": "商品编码" }, + { "name": "item_name", "type": "string", "description": "商品名称" }, + { "name": "stock_id", "type": "number", "description": "库存记录ID(stock 主键)" }, + { "name": "total_qty", "type": "number", "description": "该库位该商品的总需拣货数量" }, + { + "name": "box_allocations", + "type": "array", + "description": "与该库位/商品相关的箱分配列表(当 require_box_allocations=true 时返回)", + "children": [ + { "name": "box_id", "type": "number", "description": "箱ID" }, + { "name": "box_no", "type": "string", "description": "箱编码" }, + { "name": "box_type", "type": "number", "description": "箱类型" }, + { "name": "required_qty", "type": "number", "description": "该箱分配需要拣货的数量" }, + { "name": "picked_qty", "type": "number", "description": "该箱已完成拣货的数量" }, + { "name": "allocated_qty", "type": "number", "description": "该箱已分配的数量(由后端分配)" } + ] + } + ] + } + ] + } + ], + "errors": [ + { + "code": "400", + "description": "task_id 缺失或不合法" + }, + { + "code": "403", + "description": "当前操作人与任务创建人不一致,无权查看" + }, + { + "code": "404", + "description": "拣货任务不存在" + } + ] } ] }, @@ -12806,7 +14466,67 @@ "errors": [] } ] + }, + { + "groupName": "order.wave", + "module": "order", + "list": [ + { + "method": "order.wave.batchList", + "description": "波次列表查询。仅使用当前登录操作者的仓库ID作为查询约束(禁止传入 warehouse_id / warehouseId)。支持通过白名单字段进行过滤(通过 where 对象传入),接口对 wave_status 固定叠加查询状态 0/1,无需客户端传入。列表按订单数量从大到小排序,并附带波次基础信息与分配状态汇总。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page / pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "波次列表,包含波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)。每条记录新增字段 source(number):来源标识,0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务。" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": 400, + "message": "未识别到当前仓库上下文" + }, + { + "code": 500, + "message": "查询失败" + } + ] + } + ] } ] } -} \ No newline at end of file +} diff --git a/script/check_tables.cjs b/script/check_tables.cjs new file mode 100644 index 0000000..756a134 --- /dev/null +++ b/script/check_tables.cjs @@ -0,0 +1,21 @@ +(async () => { + try { + const configs = require('../database/config.js'); + const env = process.env.NODE_ENV || 'development'; + const cfg = configs[env]; + if (!cfg) { + console.error('NO_CONFIG_FOR_ENV'); + process.exit(2); + } + const mysql = require('mysql2/promise'); + const conn = await mysql.createConnection({ host: cfg.host, user: cfg.username, password: cfg.password, database: cfg.database, port: cfg.port || 3306 }); + const [rows] = await conn.execute("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND TABLE_NAME IN (?,?)", [cfg.database, 'wms_wave_strategy', 'wms_picking_strategy']); + const exists = { wms_wave_strategy: false, wms_picking_strategy: false }; + for (const r of rows) { exists[r.TABLE_NAME] = true; } + console.log(JSON.stringify({ env, database: cfg.database, exists })); + await conn.end(); + } catch (err) { + console.error('ERROR', err.message); + process.exit(3); + } +})(); diff --git a/script/run-single-migration.cjs b/script/run-single-migration.cjs new file mode 100644 index 0000000..1210b39 --- /dev/null +++ b/script/run-single-migration.cjs @@ -0,0 +1,156 @@ +const path = require('path'); +const fs = require('fs'); +const SequelizeLib = require('sequelize'); + +(async () => { + const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js'; + const migrationPath = path.join(__dirname, '..', 'database', 'migrations', migrationName); + if (!fs.existsSync(migrationPath)) { + console.error('ERROR: migration file not found:', migrationPath); + process.exitCode = 2; + return; + } + + const dbConfigFile = path.join(__dirname, '..', 'database', 'config.js'); + let dbConfig; + try { + dbConfig = require(dbConfigFile); + } catch (e) { + console.error('ERROR: failed to load database config:', e.message); + process.exitCode = 2; + return; + } + + const config = dbConfig.production; + const sequelize = new SequelizeLib(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: config.dialect || 'mysql', + logging: false, + define: config.define, + pool: config.pool, + }); + + const queryInterface = sequelize.getQueryInterface(); + + try { + await sequelize.authenticate(); + } catch (e) { + console.error('ERROR: DB connection failed:', e.message); + process.exitCode = 2; + return; + } + + // list migration files on disk + const migrationsDir = path.join(__dirname, '..', 'database', 'migrations'); + const migrationFiles = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.js')).sort(); + + // ensure SequelizeMeta exists + let tables = await queryInterface.showAllTables(); + const normalizeTable = t => (typeof t === 'string' ? t : (t.tableName || t.name || '')).toLowerCase(); + const tablesLower = tables.map(normalizeTable); + if (!tablesLower.includes('sequelizemeta')) { + await queryInterface.createTable('SequelizeMeta', { name: { type: SequelizeLib.STRING, allowNull: false, primaryKey: true } }); + } + + // read applied migrations + const appliedRows = await sequelize.query('SELECT name FROM SequelizeMeta', { type: SequelizeLib.QueryTypes.SELECT }); + const appliedNames = appliedRows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); + + // detect pending migrations (not yet recorded) + const pending = migrationFiles.filter(f => !appliedNames.includes(f)); + const earlierPending = pending.filter(f => f < migrationName); + if (earlierPending.length > 0) { + console.error('ERROR: 存在早于目标迁移的 pending migration,拒绝单独执行。'); + console.error('Pending earlier migrations:\n' + earlierPending.join('\n')); + process.exitCode = 3; + return; + } + + if (appliedNames.includes(migrationName)) { + console.log('INFO: 迁移已记录在 SequelizeMeta,跳过执行。'); + } else { + // run single migration up + const migration = require(migrationPath); + try { + await migration.up(queryInterface, SequelizeLib); + } catch (e) { + console.error('ERROR: migration.up 执行失败:', e && e.message ? e.message : e); + // attempt to collect state for rollback advice + try { + const tablesAfter = await queryInterface.showAllTables(); + if (tablesAfter.map(normalizeTable).includes('wms_order_wave_strategy_match')) { + console.error('STATE: 表 wms_order_wave_strategy_match 已存在(可能部分创建)。'); + } + } catch (e2) { + // ignore + } + process.exitCode = 4; + return; + } + + // record migration in SequelizeMeta + try { + await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] }); + } catch (e) { + console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e); + process.exitCode = 5; + return; + } + console.log('INFO: migration 执行并记录完成。'); + } + + // 验证:表存在、字段、索引、SequelizeMeta + const result = { + migrationRecorded: false, + tableExists: false, + columns: {}, + indexes: {}, + }; + + // migration recorded? + const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT }); + result.migrationRecorded = (checkRow && checkRow.length > 0); + + // table exists? + tables = await queryInterface.showAllTables(); + result.tableExists = tables.map(normalizeTable).includes('wms_order_wave_strategy_match'); + + if (result.tableExists) { + const desc = await queryInterface.describeTable('wms_order_wave_strategy_match'); + const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time']; + for (const col of needed) { + result.columns[col] = !!desc[col]; + if (desc[col]) { + result.columns[col + '_meta'] = { + type: desc[col].type, + allowNull: desc[col].allowNull, + defaultValue: desc[col].defaultValue, + primaryKey: !!desc[col].primaryKey || !!desc[col].primary_key || false, + autoIncrement: !!desc[col].autoIncrement || !!desc[col].auto_increment || false, + }; + } + } + + const indexes = await queryInterface.showIndex('wms_order_wave_strategy_match'); + const idxNames = (indexes || []).map(i => i.name); + result.indexes.idx_warehouse_order = idxNames.includes('idx_warehouse_order'); + result.indexes.idx_warehouse_strategy = idxNames.includes('idx_warehouse_strategy'); + + // further check fields for each index + for (const idx of (indexes || [])) { + if (idx.name === 'idx_warehouse_order') { + result.indexes.idx_warehouse_order_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column); + } + if (idx.name === 'idx_warehouse_strategy') { + result.indexes.idx_warehouse_strategy_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column); + } + } + } + + console.log('\n=== VERIFICATION RESULT ==='); + console.log(JSON.stringify(result, null, 2)); + // close + await sequelize.close(); + process.exitCode = 0; +})(); diff --git a/test/app/service/systemMethods/order.base.step.test.js b/test/app/service/systemMethods/order.base.step.test.js index 64647a6..044dacf 100644 --- a/test/app/service/systemMethods/order.base.step.test.js +++ b/test/app/service/systemMethods/order.base.step.test.js @@ -381,6 +381,65 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { assert.ok(outboundResult.list.every(item => item.warehouse_id === 100000)); }); + it('should apply default filters for waveStrategyFallbackOrder in listByModule', async () => { + const { service, captures } = createOrderHarness(OrderBaseService, { + rowsByModule: { + waveStrategyFallbackOrder: [ + { + id: 1, + warehouse_id: 100000, + step: 1, + wave_id: 0, + wave_scan_result: 2, + }, + { + id: 2, + warehouse_id: 100000, + step: 0, + wave_id: 0, + wave_scan_result: 2, + }, + { + id: 3, + warehouse_id: 100000, + step: 1, + wave_id: 99, + wave_scan_result: 2, + }, + { + id: 4, + warehouse_id: 100000, + step: 1, + wave_id: 0, + wave_scan_result: 1, + }, + { + id: 5, + warehouse_id: 100001, + step: 1, + wave_id: 0, + wave_scan_result: 2, + }, + ], + }, + }); + + const result = await service.listByModule('waveStrategyFallbackOrder', { + pagination: { + page: 1, + pageSize: 10, + }, + }); + + assert.equal(captures[0].moduleName, 'waveStrategyFallbackOrder'); + 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); + }); + it('should attach express numbers and normalize sys names in all order lists', async () => { const rows = buildRows(2, index => ({ id: index + 1, @@ -453,6 +512,42 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => { assert.equal(result.list[1].sys_logistics_name, null); }); + it('should include wave fields in list attributes and keep default fields in response', async () => { + const rows = [ + { + id: 1, + warehouse_id: 100000, + step: 1, + wave_strategy_version: 7, + wave_scan_result: null, + }, + { + id: 2, + warehouse_id: 100000, + step: 1, + }, + ]; + const { service, captures } = createOrderHarness(OrderBaseService, { + rowsByModule: { + order: rows, + }, + }); + + const result = await service.listByModule('order', { + pagination: { + page: 1, + pageSize: 10, + }, + }); + + assert.equal(captures[0].findOptions.attributes.includes('wave_strategy_version'), true); + assert.equal(captures[0].findOptions.attributes.includes('wave_scan_result'), true); + assert.equal(result.list[0].wave_strategy_version, 7); + assert.equal(result.list[0].wave_scan_result, 0); + assert.equal(result.list[1].wave_strategy_version, 0); + assert.equal(result.list[1].wave_scan_result, 0); + }); + it('should treat waybill_codes as virtual filter and only append matched order ids to order where', async () => { const rows = buildRows(3, index => ({ id: index + 1, diff --git a/test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js b/test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js new file mode 100644 index 0000000..aee5596 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js @@ -0,0 +1,131 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 buildTaskBoxRows 测试上下文。 + * + * @return {WaveService} 服务实例。 + */ +function createService() { + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + return new WaveService(ctx); +} + +describe('test/app/service/systemMethods/order/wave.buildTaskBoxRows.test.js', () => { + it('buildTaskSkuRows 在 pick_mode=3 时应按 SKU 聚合 required_qty', async () => { + const service = createService(); + service.getOrderItemsModelByTableType = async () => ({ + async findAll() { + return [ + { order_id: 1001, plan_qty: 2, stock_id: 7001, item_code: 'SKU-A', item_name: '商品A' }, + { order_id: 1001, plan_qty: 3, stock_id: 7001, item_code: 'SKU-A', item_name: '商品A' }, + { order_id: 1002, plan_qty: 1, stock_id: 7002, item_code: 'SKU-B', item_name: '商品B' }, + ]; + }, + }); + + const skuRows = await service.buildTaskSkuRows({ + plan: { + warehouse_id: 100000, + pick_mode: 3, + }, + selectedOrderIds: [ 1001, 1002 ], + }); + + assert.equal(skuRows.length, 2); + assert.equal(skuRows[0].ref_id, 7001); + assert.equal(skuRows[0].required_qty, 5); + assert.equal(skuRows[1].ref_id, 7002); + assert.equal(skuRows[1].required_qty, 1); + }); + + it('pick_mode=3 应优先按 SKU 生成 box_type=1 的框', () => { + const service = createService(); + + const rows = service.buildTaskBoxRows({ + taskId: 501, + taskNo: 'TASK-501', + plan: { + warehouse_id: 100000, + pick_mode: 3, + }, + taskOrderRows: [ + { order_id: 1001, box_no: 1 }, + { order_id: 1002, box_no: 2 }, + { order_id: 1003, box_no: 3 }, + ], + taskSkuRows: [ + { box_no: 1, sku_id: 7001, ref_id: 7001, ref_label: 'SKU-A', required_qty: 5 }, + { box_no: 2, sku_id: 7002, ref_id: 7002, ref_label: 'SKU-B', required_qty: 8 }, + ], + }); + + assert.equal(rows.length, 2); + assert.equal(rows[0].box_type, 1); + assert.equal(rows[0].ref_id, 7001); + assert.equal(rows[0].required_qty, 5); + assert.equal(rows[0].box_code, 'TASK-501-S1'); + }); + + it('pick_mode=4 应按订单生成 box_type=2 的框', () => { + const service = createService(); + + const rows = service.buildTaskBoxRows({ + taskId: 601, + taskNo: 'TASK-601', + plan: { + warehouse_id: 100000, + pick_mode: 4, + }, + taskOrderRows: [ + { order_id: 2001, box_no: 1 }, + ], + taskSkuRows: [ + { box_no: 1, sku_id: 8001, ref_id: 8001, ref_label: 'SKU-X', required_qty: 3 }, + ], + }); + + assert.equal(rows.length, 1); + assert.equal(rows[0].box_type, 2); + assert.equal(rows[0].order_id, 2001); + assert.equal(rows[0].ref_id, 2001); + assert.equal(rows[0].box_code, 'TASK-601-O1'); + }); + + it('pick_mode=5 应按波次生成 box_type=3 的框', () => { + const service = createService(); + + const rows = service.buildTaskBoxRows({ + taskId: 701, + taskNo: 'TASK-701', + plan: { + warehouse_id: 100000, + pick_mode: 5, + }, + taskWaveRows: [ + { wave_id: 9001, wave_no: 'WAVE-9001', box_no: 1 }, + ], + }); + + assert.equal(rows.length, 1); + assert.equal(rows[0].box_type, 3); + assert.equal(rows[0].ref_id, 9001); + assert.equal(rows[0].box_code, 'TASK-701-W1'); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js index c03a2a5..40852f4 100644 --- a/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js +++ b/test/app/service/systemMethods/order/wave.singleFetchByIds.test.js @@ -63,6 +63,7 @@ function createHarness({ orders = [], storeId = 100000 } = {}) { const service = new WaveService(ctx); service.getGroupWavePrefix = async () => 'B'; + service.getSingleFetchByIdsWavePrefix = async () => 'A'; service.getMinGroupOrderFetchQuantity = async () => 3; service.createWaveBatchReady = async params => { state.createWaveCalls.push({ ...params }); @@ -190,17 +191,18 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', ( assert.equal(result.flag, 'success'); assert.equal(result.wave_id, 9001); - assert.equal(result.wave_no, 'S202605060001'); - assert.deepEqual(result.fetched_order_ids, [ 1 ]); - assert.equal(result.fetched_order_count, 1); + assert.equal(result.wave_no, 'A202605060001'); + assert.deepEqual(result.fetched_order_ids, [ 1, 3, 4 ]); + assert.equal(result.fetched_order_count, 3); assert.deepEqual(result.excluded_existing_wave_order_ids, [ 2 ]); assert.deepEqual(result.not_found_order_ids, [ 5 ]); assert.equal(state.createWaveCalls.length, 1); - assert.equal(state.createWaveCalls[0].wavePrefix, 'S'); + assert.equal(state.createWaveCalls[0].wavePrefix, 'A'); + assert.equal(state.createWaveCalls[0].waveType, 2); assert.equal(state.createWaveCalls[0].distinguishExpress, false); assert.equal(state.createWaveCalls[0].logisticsName, ''); - assert.equal(state.orderLogItems.length, 1); + assert.equal(state.orderLogItems.length, 3); assert.equal(state.orderLogItems[0].operationCode, 'ORDER_WAVE_ASSIGN'); assert.equal(state.committed, true); assert.equal(state.rolledBack, false); @@ -225,7 +227,7 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', ( assert.equal(state.rolledBack, false); }); - it('should exclude group-candidate orders from singleFetchByIds', async () => { + it('should fetch same-structure orders when they are not in any wave', async () => { const { service, state } = createHarness({ orders: [ { id: 101, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none', items_hash: 'H-A', items: 'I-A', logistics_name: 'ZTO' }, @@ -239,11 +241,49 @@ describe('test/app/service/systemMethods/order/wave.singleFetchByIds.test.js', ( assert.equal(result.flag, 'success'); assert.equal(result.wave_id, 9001); - assert.deepEqual(result.fetched_order_ids, [ 104 ]); - assert.deepEqual(result.excluded_group_order_ids, [ 101 ]); - assert.deepEqual(result.skipped_order_ids, [ 101 ]); + assert.deepEqual(result.fetched_order_ids, [ 101, 104 ]); + assert.deepEqual(result.skipped_order_ids, []); + assert.equal(state.createWaveCalls.length, 1); + assert.equal(state.createWaveCalls[0].wavePrefix, 'A'); + assert.equal(state.createWaveCalls[0].waveType, 2); + assert.equal(state.createWaveCalls[0].distinguishExpress, false); + assert.equal(state.committed, true); + assert.equal(state.rolledBack, false); + }); + + it('should support order_ids alias for delete-by-ids scene', async () => { + const { service, state } = createHarness({ + orders: [ + { id: 201, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' }, + { id: 202, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' }, + ], + }); + + const result = await service.singleFetchByIds({ order_ids: [ 201, 202 ] }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.ids, [ 201, 202 ]); + assert.deepEqual(result.fetched_order_ids, [ 201, 202 ]); + assert.equal(result.fetched_order_count, 2); + assert.equal(state.createWaveCalls.length, 1); + assert.equal(state.committed, true); + assert.equal(state.rolledBack, false); + }); + + it('should support orderIds alias for delete-by-ids scene', async () => { + const { service, state } = createHarness({ + orders: [ + { id: 301, wave_id: 0, wave_no: '', step: 1, status: 'new', outbound_status: 'none' }, + ], + }); + + const result = await service.singleFetchByIds({ orderIds: [ 301 ] }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.ids, [ 301 ]); + assert.deepEqual(result.fetched_order_ids, [ 301 ]); + assert.equal(result.fetched_order_count, 1); assert.equal(state.createWaveCalls.length, 1); - assert.equal(state.createWaveCalls[0].wavePrefix, 'S'); assert.equal(state.committed, true); assert.equal(state.rolledBack, false); }); diff --git a/test/app/service/systemMethods/order/wave.wavePickTaskList.test.js b/test/app/service/systemMethods/order/wave.wavePickTaskList.test.js new file mode 100644 index 0000000..acb420d --- /dev/null +++ b/test/app/service/systemMethods/order/wave.wavePickTaskList.test.js @@ -0,0 +1,143 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 wavePickTaskList 测试上下文。 + * + * @return {{ service: WaveService, captures: { sqlList: Array, replacementList: Array } }} 测试对象。 + */ +function createHarness() { + const captures = { + sqlList: [], + replacementList: [], + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + model: { + async query(sql, queryOptions = {}) { + const normalizedSql = String(sql || '').replace(/\s+/g, ' ').trim(); + captures.sqlList.push(normalizedSql); + captures.replacementList.push(queryOptions.replacements || {}); + + if (/COUNT\(1\) AS total/i.test(normalizedSql)) { + return [[{ total: 2 }]]; + } + + return [[{ + id: 501, + task_no: 'WPT100000117892299991ABCDEF', + warehouse_id: 100000, + pick_mode: 1, + status: 0, + review_status: 0, + source: 1, + wave_count: 2, + order_count: 10, + box_count: 2, + pick_user_id: 9001, + pick_user_name: 'tester', + review_user_id: 0, + review_user_name: '', + current_cart_id: 11, + current_cart_code_snapshot: 'CART-11', + batch_no: 'BATCH-1', + device_id: 'PDA-1', + start_time: null, + finish_time: null, + review_start_time: null, + review_finish_time: null, + create_time: '2026-05-08 10:00:00', + update_time: '2026-05-08 10:00:00', + }]]; + }, + }, + }; + + const service = new WaveService(ctx); + return { + service, + captures, + }; +} + +describe('test/app/service/systemMethods/order/wave.wavePickTaskList.test.js', () => { + it('默认分页应查询成功并返回 list/total/page/page_size', async () => { + const { service } = createHarness(); + + const result = await service.wavePickTaskList({}); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(result.total, 2); + assert.equal(result.page, 1); + assert.equal(result.page_size, 20); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list.length, 1); + assert.deepEqual(result.list[0], { + task_id: 501, + task_no: 'WPT100000117892299991ABCDEF', + warehouse_id: 100000, + pick_mode: 1, + status: 0, + review_status: 0, + source: 1, + wave_count: 2, + order_count: 10, + box_count: 2, + pick_user_id: 9001, + pick_user_name: 'tester', + review_user_id: 0, + review_user_name: '', + current_cart_id: 11, + current_cart_code_snapshot: 'CART-11', + batch_no: 'BATCH-1', + device_id: 'PDA-1', + start_time: null, + finish_time: null, + review_start_time: null, + review_finish_time: null, + create_time: '2026-05-08 10:00:00', + update_time: '2026-05-08 10:00:00', + }); + }); + + it('task_no 与 keyword 过滤应正确拼接到 SQL 与 replacements', async () => { + const { service, captures } = createHarness(); + + const result = await service.wavePickTaskList({ + current: 2, + size: 50, + where: { + task_no: 'WPT100', + keyword: 'tester', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(captures.sqlList.length, 2); + + const listSql = captures.sqlList[0]; + const listReplacements = captures.replacementList[0]; + + assert.ok(listSql.includes('t.task_no LIKE :whereTaskNo')); + assert.ok(listSql.includes('t.task_no LIKE :whereKeyword')); + assert.ok(listSql.includes('t.pick_user_name LIKE :whereKeyword')); + assert.ok(listSql.includes('t.review_user_name LIKE :whereKeyword')); + assert.ok(listSql.includes('t.batch_no LIKE :whereKeyword')); + assert.equal(listReplacements.whereTaskNo, '%WPT100%'); + assert.equal(listReplacements.whereKeyword, '%tester%'); + assert.equal(listReplacements.limit, 50); + assert.equal(listReplacements.offset, 50); + assert.equal(result.page, 2); + assert.equal(result.page_size, 50); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js new file mode 100644 index 0000000..07cd433 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js @@ -0,0 +1,240 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 构建 waveStrategyFallbackOrderList 的测试上下文。 + * + * @return {{ service: WaveService, captures: { moduleName: string|null, data: Object|null } }} 测试对象。 + */ +function createHarness() { + const captures = { + moduleName: null, + data: null, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + warn: () => {}, + }, + }; + + const service = new WaveService(ctx); + service.getWarehouseId = () => 1; + service.listByModule = async (moduleName, data) => { + captures.moduleName = moduleName; + captures.data = data; + return { + list: [ + { + id: 101, + delivery_order_code: 'FH20260507001', + express_numbers: [ 'YT20260507001' ], + items_count: 2, + items_total: 5, + sys_logistics_name: '系统圆通', + logistics_name: '圆通', + shop_nick: '货主A', + province: '浙江省', + sys_platform_name: '抖音', + wave_scan_result: 2, + tel: '13800000000', + }, + ], + pagination: { + page: 1, + pageSize: 20, + total: 1, + totalPages: 1, + }, + }; + }; + + return { + service, + captures, + }; +} + +describe('test/app/service/systemMethods/order/wave.waveStrategyFallbackOrderList.test.js', () => { + it('should only return fallback whitelist fields and wrap success response', async () => { + const { service, captures } = createHarness(); + const requestData = { + where: { + id: 1001, + delivery_no: 'FH2026', + tracking_no: 'YT2026', + items_count: 2, + items_total: 5, + sys_logistics_name: '圆通', + store_name: '货主A', + province: '浙江', + sys_platform_name: '抖音', + }, + pagination: { + page: 2, + pageSize: 10, + }, + sort: { + sortField: 'updated_at', + sortOrder: 'DESC', + }, + }; + + 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, [ + { + id: 101, + delivery_no: 'FH20260507001', + tracking_no: 'YT20260507001', + items_count: 2, + items_total: 5, + sys_logistics_name: '系统圆通', + store_name: '货主A', + province: '浙江省', + sys_platform_name: '抖音', + item_snapshot: '', + }, + ]); + 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', + }); + }); + + it('should normalize pagination when pagination object is passed directly', async () => { + const { service } = createHarness(); + + const normalizedPagination = service.normalizePagination({ + page: 2, + pageSize: 20, + }); + + assert.deepEqual(normalizedPagination, { + page: 2, + pageSize: 20, + }); + }); + + it('should fill item_snapshot with 商品名称*数量|... when order items exist', async () => { + const { service } = createHarness(); + service.getOrderItemsModelByTableType = async () => ({ + findAll: async () => ([ + { + order_id: 101, + plan_qty: 1, + stock_id: 1, + item_code: 'A-1', + item_name: '商品A', + item_snapshot: '{"item_name":"商品A","item_code":"A-1"}', + }, + { + order_id: 101, + plan_qty: 2, + stock_id: 1, + item_code: 'A-1', + item_name: '商品A', + item_snapshot: '{"item_name":"商品A","item_code":"A-1"}', + }, + { + order_id: 101, + plan_qty: 3, + stock_id: 2, + item_code: 'B-1', + item_name: '商品B', + item_snapshot: '{"item_name":"商品B","item_code":"B-1"}', + }, + ]), + }); + + const result = await service.waveStrategyFallbackOrderList({}); + + assert.equal(result.flag, 'success'); + assert.equal(result.list[0].item_snapshot, '商品A*3|商品B*3'); + assert.deepEqual(Object.keys(result.list[0]).sort(), [ + 'delivery_no', + 'id', + 'item_snapshot', + 'items_count', + 'items_total', + 'province', + 'store_name', + 'sys_logistics_name', + 'sys_platform_name', + 'tracking_no', + ].sort()); + }); + + it('should return empty item_snapshot when no order items found', async () => { + const { service } = createHarness(); + service.getOrderItemsModelByTableType = async () => ({ + findAll: async () => ([]), + }); + + const result = await service.waveStrategyFallbackOrderList({}); + + assert.equal(result.flag, 'success'); + assert.equal(result.list[0].item_snapshot, ''); + }); + + it('should reject unsupported where fields', async () => { + const { service } = createHarness(); + + await assert.rejects(async () => { + await service.waveStrategyFallbackOrderList({ + where: { + wave_id: 1, + }, + }); + }, /where 存在不支持的字段: wave_id/); + }); + + it('should allow owner_name as where alias and map to shop_nick', async () => { + const { service, captures } = createHarness(); + + const result = await service.waveStrategyFallbackOrderList({ + where: { + owner_name: '货主B', + }, + }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(captures.data.where, { + shop_nick: '货主B', + }); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js b/test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js new file mode 100644 index 0000000..369cf33 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js @@ -0,0 +1,255 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 waveStrategyFetch 测试上下文。 + * + * @param {Object} [options={}] 测试选项。 + * @param {Object} [options.strategyRow] 策略模型返回行。 + * @return {{ service: WaveService, captures: Object }} 测试上下文。 + */ +function createHarness(options = {}) { + const strategyRow = options.strategyRow || { + id: 99, + warehouse_id: 100000, + status: 1, + strategy_type: 2, + batch_mode: 0, + group_batch_max_orders: 2, + batch_max_orders: 20, + batch_max_skus: 10, + }; + + const captures = { + transactionCount: 0, + committed: 0, + rolledBack: 0, + inserts: [], + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + captures.committed += 1; + }, + async rollback() { + captures.rolledBack += 1; + }, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + id: 9001, + name: 'tester', + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + captures.transactionCount += 1; + return transaction; + }, + async query(sql, queryOptions = {}) { + const compactSql = String(sql || '').replace(/\s+/g, ' ').trim() + .toLowerCase(); + + if (compactSql.includes('select b.task_id from wms_pick_task_cart_binding')) { + return []; + } + + if (compactSql.includes('select id, cart_code, current_task_id from wms_pick_cart')) { + return [{ + id: 9, + cart_code: 'CART-09', + current_task_id: null, + }]; + } + + if (compactSql.includes('insert into wms_wave_pick_task ')) { + captures.inserts.push('wms_wave_pick_task'); + return [{ insertId: 501 }, { insertId: 501 }]; + } + + if (compactSql.includes('insert into wms_wave_pick_task_wave')) { + captures.inserts.push('wms_wave_pick_task_wave'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_wave_pick_task_order')) { + captures.inserts.push('wms_wave_pick_task_order'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_wave_pick_task_box')) { + captures.inserts.push('wms_wave_pick_task_box'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_pick_task_cart_binding')) { + captures.inserts.push('wms_pick_task_cart_binding'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_wave_pick_checkpoint')) { + captures.inserts.push('wms_wave_pick_checkpoint'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_wave_pick_action_log')) { + captures.inserts.push('wms_wave_pick_action_log'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('insert into wms_order_pick_trace')) { + captures.inserts.push('wms_order_pick_trace'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('update wms_pick_cart')) { + captures.inserts.push('wms_pick_cart_update'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('update wms_wave_pick_task')) { + captures.inserts.push('wms_wave_pick_task_update'); + return [{ affectedRows: 1 }]; + } + + if (compactSql.includes('select last_insert_id() as insertid')) { + return [[{ insertId: 501 }]]; + } + + return queryOptions.type === 'SELECT' ? [] : [{ affectedRows: 0 }]; + }, + wms_wave_strategy: { + async findOne() { + return strategyRow; + }, + }, + }, + }; + + const service = new WaveService(ctx); + return { + service, + captures, + }; +} + +describe('test/app/service/systemMethods/order/wave.waveStrategyFetch.test.js', () => { + it('waveStrategyFetchPda 应进入创建流程并写入核心表', async () => { + const { service, captures } = createHarness(); + + const result = await service.waveStrategyFetchPda({ + strategy_id: 99, + selected_wave_ids: [ 20001 ], + cart_id: 9, + device_id: 'pda-1', + request_id: 'req-1', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.state, 'created'); + assert.equal(result.fetch_state, 1); + assert.equal(result.tip, '任务创建成功'); + assert.equal(result.can_enter_pick_flow, false); + assert.equal(result.task_id, 501); + assert.ok(typeof result.task_no === 'string' && result.task_no.length > 0); + + assert.equal(captures.transactionCount, 1); + assert.equal(captures.committed, 1); + assert.equal(captures.rolledBack, 0); + + const insertedSet = new Set(captures.inserts); + assert.equal(insertedSet.has('wms_wave_pick_task'), true); + assert.equal(insertedSet.has('wms_wave_pick_task_wave'), true); + assert.equal(insertedSet.has('wms_wave_pick_task_box'), true); + assert.equal(insertedSet.has('wms_pick_task_cart_binding'), true); + assert.equal(insertedSet.has('wms_wave_pick_checkpoint'), true); + assert.equal(insertedSet.has('wms_wave_pick_action_log'), true); + assert.equal(insertedSet.has('wms_order_pick_trace'), true); + assert.equal(insertedSet.has('wms_pick_cart_update'), true); + }); + + it('校验失败时应短路返回 failure 且不进入事务', async () => { + const { service, captures } = createHarness(); + + const result = await service.waveStrategyFetchPda({ + strategy_id: 99, + selected_wave_ids: [], + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.equal(result.data.fetch_state, 2); + assert.equal(result.data.tip, '创建失败,请重试'); + assert.equal(result.data.task_id, null); + assert.equal(result.data.can_enter_pick_flow, false); + assert.equal(captures.transactionCount, 0); + }); + + it('waveStrategyFetchPda 在存在未完成任务时返回 fetch_state=3 并回填任务ID', async () => { + const { service } = createHarness(); + service.createWavePickTaskFromPlan = async () => { + throw new Error('当前用户存在未完成任务,请先完成后再创建(task_id=777,task_no=PK20260510001)'); + }; + + const result = await service.waveStrategyFetchPda({ + strategy_id: 99, + selected_wave_ids: [ 20001 ], + cart_id: 9, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.fetch_state, 3); + assert.equal(result.tip, '存在未完成任务,已返回任务ID,可继续拣货'); + assert.equal(result.task_id, 777); + assert.equal(result.task_no, 'PK20260510001'); + assert.equal(result.can_enter_pick_flow, true); + assert.equal(result.status, 'failed'); + }); + + it('waveStrategyFetchAdmin 成功时返回 task_id/task_no/state=created', async () => { + const { service } = createHarness({ + strategyRow: { + id: 100, + warehouse_id: 100000, + status: 1, + strategy_type: 1, + batch_mode: 1, + group_batch_max_orders: 1, + batch_max_orders: 30, + batch_max_skus: 10, + }, + }); + + const result = await service.waveStrategyFetchAdmin({ + strategy_id: 100, + selected_order_ids: [ 3001, 3002 ], + request_id: 'req-admin-1', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.state, 'created'); + assert.equal(result.fetch_state, 1); + assert.equal(result.tip, '任务创建成功'); + assert.equal(result.can_enter_pick_flow, false); + assert.equal(result.task_id, 501); + assert.ok(typeof result.task_no === 'string' && result.task_no.length > 0); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyList.test.js b/test/app/service/systemMethods/order/wave.waveStrategyList.test.js new file mode 100644 index 0000000..9af8ad7 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.waveStrategyList.test.js @@ -0,0 +1,201 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 waveStrategyList 测试上下文。 + * + * @param {Object} [options={}] 测试选项。 + * @param {number} [options.warehouseId=100000] 当前仓库ID。 + * @param {Array} [options.strategyRows] 自定义策略列表。 + * @param {Array} [options.matchedRows] 命中订单统计查询结果。 + * @return {{ service: WaveService, captures: { findOptions: Object|null } }} 测试上下文。 + */ +function createHarness(options = {}) { + const warehouseId = Number(options.warehouseId || 100000); + const strategyRows = Array.isArray(options.strategyRows) + ? options.strategyRows + : [ + { + id: 21, + warehouse_id: warehouseId, + strategy_name: '优先散单', + status: 1, + }, + { + id: 20, + warehouse_id: warehouseId, + strategy_name: '团购策略', + status: 0, + }, + ]; + const matchedRows = Array.isArray(options.matchedRows) + ? options.matchedRows + : [ + { strategy_id: 21, matched_order_count_filtered: 8 }, + ]; + const captures = { + findOptions: null, + querySql: '', + queryOptions: null, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: warehouseId, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + wms_wave_strategy: { + async findAndCountAll(findOptions) { + captures.findOptions = findOptions; + return { + count: 5, + rows: strategyRows, + }; + }, + }, + async query(sql, queryOptions) { + captures.querySql = String(sql || ''); + captures.queryOptions = queryOptions; + return matchedRows; + }, + }, + }; + + const service = new WaveService(ctx); + service.getOrderModel = async () => ({ + getTableName: () => 'wms_order_delivery_test', + }); + + return { + service, + captures, + }; +} + +describe('test/app/service/systemMethods/order/wave.waveStrategyList.test.js', () => { + it('should query by current warehouse and wrap success response with pagination', async () => { + const { service, captures } = createHarness({ warehouseId: 200001 }); + + const result = await service.waveStrategyList({ + pagination: { + page: 2, + pageSize: 2, + }, + }); + + assert.deepEqual(captures.findOptions.where, { + warehouse_id: 200001, + }); + assert.deepEqual(captures.findOptions.order, [ + [ 'status', 'DESC' ], + [ 'id', 'DESC' ], + ]); + assert.equal(captures.findOptions.offset, 2); + assert.equal(captures.findOptions.limit, 2); + assert.equal(captures.findOptions.raw, true); + assert.ok(captures.querySql.includes('FROM wms_order_wave_strategy_match m')); + assert.ok(captures.querySql.includes('o.wave_id = 0')); + assert.ok(captures.querySql.includes('o.step != 0')); + assert.ok(captures.querySql.includes('src.wave_id = 0')); + assert.ok(captures.querySql.includes('src.step != 0')); + assert.ok(captures.querySql.includes('COALESCE(NULLIF(TRIM(COALESCE(src.items_hash, \'\')), \'\'), TRIM(COALESCE(src.items, \'\')))')); + assert.ok(captures.querySql.includes('same_structure.same_structure_count >= COALESCE(s.min_same_structure, 0)')); + assert.ok(captures.querySql.includes('(s.max_same_structure IS NULL OR same_structure.same_structure_count <= s.max_same_structure)')); + assert.deepEqual(captures.queryOptions.replacements, { + warehouseId: 200001, + strategyIds: [ 21, 20 ], + }); + assert.equal(captures.queryOptions.type, 'SELECT'); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list.length, 2); + assert.equal(result.list[0].warehouse_id, 200001); + assert.equal(result.list[0].matched_order_count_filtered, 8); + assert.equal(result.list[0].next_fetch_order_count, 0); + assert.equal(result.list[1].matched_order_count_filtered, 0); + assert.equal(result.list[1].next_fetch_order_count, 0); + assert.deepEqual(result.pagination, { + page: 2, + pageSize: 2, + total: 5, + totalPages: 3, + hasPrevious: true, + hasNext: true, + }); + }); + + it('should return next_fetch_order_count=0 and skip preview when calculation flag is disabled', async () => { + const { service } = createHarness({ warehouseId: 200002 }); + let calledCount = 0; + service.getWaveStrategyNextFetchOrderCountMap = async () => { + calledCount += 1; + return new Map(); + }; + + const result = await service.waveStrategyList({ + pagination: { + page: 1, + pageSize: 20, + }, + }); + + assert.equal(calledCount, 0); + assert.ok(Array.isArray(result.list)); + assert.equal(result.list[0].next_fetch_order_count, 0); + assert.equal(result.list[1].next_fetch_order_count, 0); + }); + + it('should calculate next_fetch_order_count when calculate_next_fetch_order_count=1', async () => { + const { service } = createHarness({ + warehouseId: 200003, + strategyRows: [ + { + id: 31, + warehouse_id: 200003, + strategy_name: '散单策略A', + strategy_type: 1, + batch_mode: 1, + batch_max_orders: 2, + batch_max_skus: 10, + status: 1, + }, + ], + matchedRows: [ + { strategy_id: 31, matched_order_count_filtered: 3 }, + ], + }); + + service.getWaveStrategyFetchCandidateOrders = async () => ([ + { id: 101, items_hash: 'hash_a', items: 'A', logistics_name: 'ZTO', items_count: 1, items_total: 1 }, + { id: 102, items_hash: 'hash_b', items: 'B', logistics_name: 'YTO', items_count: 1, items_total: 1 }, + { id: 103, items_hash: 'hash_c', items: 'C', logistics_name: 'STO', items_count: 1, items_total: 1 }, + ]); + service.buildWaveStrategyFetchOrderSkuMap = async () => { + throw new Error('pick_mode=2 场景不应触发 SKU 预演'); + }; + + const result = await service.waveStrategyList({ + calculate_next_fetch_order_count: 1, + pagination: { + page: 1, + pageSize: 20, + }, + }); + + assert.ok(Array.isArray(result.list)); + assert.equal(result.list.length, 1); + assert.equal(result.list[0].matched_order_count_filtered, 3); + assert.equal(result.list[0].next_fetch_order_count, 2); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js b/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js new file mode 100644 index 0000000..d616c8c --- /dev/null +++ b/test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js @@ -0,0 +1,394 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { Op } = require('sequelize'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); +const runWaveStrategyQuickScanRunner = require('../../../../../app/lib/wave_strategy_quick_scan_runner'); + +/** + * 构建快速扫描测试上下文。 + * + * @return {{ service: WaveService, cache: Map }} 服务实例与缓存。 + */ +function createHarness() { + const cache = new Map(); + + const ctx = { + app: { + config: {}, + async setCacheAsync(key, payload) { + cache.set(key, payload); + }, + async getCacheAsync(key) { + return cache.get(key) || null; + }, + async delCacheAsync(key) { + cache.delete(key); + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + wms_wave_strategy: { + async findAll() { + return []; + }, + }, + }, + }; + + return { + service: new WaveService(ctx), + cache, + }; +} + +describe('test/app/service/systemMethods/order/wave.waveStrategyQuickScan.test.js', () => { + it('传入 warehouse_id 参数时应抛错', async () => { + const { service } = createHarness(); + + await assert.rejects( + async () => { + await service.waveStrategyQuickScan({ warehouse_id: 100000 }); + }, + error => { + assert.match(String(error && error.message || ''), /不支持传入 warehouse_id/u); + return true; + } + ); + }); + + it('同仓存在运行任务时应返回已有 task_id 且不重复启动', async () => { + const { service } = createHarness(); + const runCalls = []; + + service.runWaveStrategyQuickScanTask = async params => { + runCalls.push(params); + await service.setWaveStrategyQuickScanTaskProgress(params.taskId, 'running', { + warehouse_id: 100000, + }); + }; + + const firstResult = await service.waveStrategyQuickScan({}); + await new Promise(resolve => setImmediate(resolve)); + + const secondResult = await service.waveStrategyQuickScan({}); + + assert.equal(firstResult.flag, 'success'); + assert.equal(secondResult.flag, 'success'); + assert.equal(secondResult.task_id, firstResult.task_id); + assert.equal(runCalls.length, 1); + }); + + it('执行任务时应按策略命中写入扫描结果和策略版本', async () => { + const { service } = createHarness(); + const updateCalls = []; + const warehouseId = 100000; + const taskId = 'wave_quick_scan_test_task_1'; + + service.getWarehouseSubjectConfig = async () => ({ + subject_config: { + wave_strategy_version: 9, + }, + }); + + service.ctx.model.wms_wave_strategy = { + async findAll() { + return [ + { + status: 1, + order_min_sku: 1, + order_max_sku: 1, + order_min_qty: 1, + order_max_qty: 2, + min_same_structure: 1, + max_same_structure: 10, + allowed_owners: [ 11 ], + allowed_expresses: [ 'YD' ], + allowed_platforms: [ 'PDD' ], + allow_cross_owner: true, + require_same_express: false, + }, + ]; + }, + }; + + service.getOrderModel = async () => ({ + async findAll() { + return [ + { + id: 1, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_a', + items: '', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + { + id: 2, + store_id: 12, + items_count: 3, + items_total: 6, + items_hash: 'hash_b', + items: '', + logistics_code: 'SF', + sys_logistics_code: 'SF', + logistics_name: '顺丰', + province: 'js', + sys_platform_code: 'TB', + source_platform_code: '', + }, + ]; + }, + async update(values, options) { + updateCalls.push({ values, options }); + return [ Array.isArray(options.where.id[Op.in]) ? options.where.id[Op.in].length : 0 ]; + }, + }); + + await service.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, { + state: 'submitted', + }); + await service.runWaveStrategyQuickScanTask({ + taskId, + warehouseId, + }); + + const matchedCall = updateCalls.find(item => Number(item.values.wave_scan_result) === 1); + const unmatchedCall = updateCalls.find(item => Number(item.values.wave_scan_result) === 2); + + assert.ok(matchedCall); + assert.ok(unmatchedCall); + assert.equal(matchedCall.values.wave_strategy_version, 9); + assert.equal(unmatchedCall.values.wave_strategy_version, 9); + assert.deepEqual(matchedCall.options.where.id[Op.in], [ 1 ]); + assert.deepEqual(unmatchedCall.options.where.id[Op.in], [ 2 ]); + + const progress = await service.getWaveStrategyQuickScanTaskProgress(taskId); + assert.equal(progress.state, 'success'); + assert.equal(progress.total_order_count, 2); + assert.equal(progress.processed_order_count, 2); + assert.equal(progress.matched_order_count, 1); + assert.equal(progress.unmatched_order_count, 1); + + const lockPayload = await service.getWaveStrategyQuickScanWarehouseLock(warehouseId); + assert.equal(lockPayload, null); + }); + + it('进度查询应返回 running 和 success 的基础字段', async () => { + const { service } = createHarness(); + const taskId = 'wave_quick_scan_test_task_2'; + + await service.setWaveStrategyQuickScanTaskProgress(taskId, 'running', { + warehouse_id: 100000, + total_order_count: 10, + processed_order_count: 3, + matched_order_count: 1, + unmatched_order_count: 2, + progress_percent: 30, + submitted_at: 1000, + start_time: 2000, + end_time: null, + }); + + const runningResult = await service.waveStrategyQuickScanTaskProgress({ + task_id: taskId, + }); + + assert.equal(runningResult.flag, 'success'); + assert.equal(runningResult.state, 'running'); + assert.equal(runningResult.total_order_count, 10); + assert.equal(runningResult.processed_order_count, 3); + assert.equal(runningResult.progress_percent, 30); + + await service.setWaveStrategyQuickScanTaskProgress(taskId, 'success', { + processed_order_count: 10, + matched_order_count: 4, + unmatched_order_count: 6, + progress_percent: 100, + end_time: 3000, + }); + + const successResult = await service.waveStrategyQuickScanTaskProgress({ + taskId, + }); + + assert.equal(successResult.flag, 'success'); + assert.equal(successResult.state, 'success'); + assert.equal(successResult.total_order_count, 10); + assert.equal(successResult.processed_order_count, 10); + assert.equal(successResult.matched_order_count, 4); + assert.equal(successResult.unmatched_order_count, 6); + assert.equal(successResult.progress_percent, 100); + assert.equal(successResult.end_time, 3000); + }); + + it('allow_cross_owner=false 时应按同结构主货主优先命中', async () => { + const { service } = createHarness(); + + const orders = [ + { + id: 101, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_owner_same_structure', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + { + id: 102, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_owner_same_structure', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + { + id: 103, + store_id: 12, + items_count: 1, + items_total: 1, + items_hash: 'hash_owner_same_structure', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + ]; + + const strategyList = [ + { + strategy_id: 1001, + order_min_sku: 1, + order_max_sku: 999, + order_min_qty: 1, + order_max_qty: 999, + min_same_structure: 1, + max_same_structure: 999, + allowed_owners: [], + allowed_expresses: [], + allowed_provinces: [], + allowed_platforms: [], + allow_cross_owner: false, + require_same_express: false, + }, + ]; + + const result = await runWaveStrategyQuickScanRunner({ + orders, + strategyList, + getStructureKey: order => service.getWaveStrategyQuickScanStructureKey(order), + getExpressKey: order => service.getWaveStrategyQuickScanExpressKey(order), + getMatchedStrategyIds: (order, normalizedStrategyList, context) => service.getWaveStrategyQuickScanMatchedStrategyIds( + order, + normalizedStrategyList, + context + ), + }); + + assert.deepEqual(result.matchedOrderIds, [ 101, 102 ]); + }); + + it('require_same_express=true 时应按同结构主快递优先命中', async () => { + const { service } = createHarness(); + + const orders = [ + { + id: 201, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_express_same_structure', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + { + id: 202, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_express_same_structure', + logistics_code: 'YD', + sys_logistics_code: 'YD', + logistics_name: '韵达', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + { + id: 203, + store_id: 11, + items_count: 1, + items_total: 1, + items_hash: 'hash_express_same_structure', + logistics_code: 'SF', + sys_logistics_code: 'SF', + logistics_name: '顺丰', + province: 'zj', + sys_platform_code: 'PDD', + source_platform_code: '', + }, + ]; + + const strategyList = [ + { + strategy_id: 1002, + order_min_sku: 1, + order_max_sku: 999, + order_min_qty: 1, + order_max_qty: 999, + min_same_structure: 1, + max_same_structure: 999, + allowed_owners: [], + allowed_expresses: [], + allowed_provinces: [], + allowed_platforms: [], + allow_cross_owner: true, + require_same_express: true, + }, + ]; + + const result = await runWaveStrategyQuickScanRunner({ + orders, + strategyList, + getStructureKey: order => service.getWaveStrategyQuickScanStructureKey(order), + getExpressKey: order => service.getWaveStrategyQuickScanExpressKey(order), + getMatchedStrategyIds: (order, normalizedStrategyList, context) => service.getWaveStrategyQuickScanMatchedStrategyIds( + order, + normalizedStrategyList, + context + ), + }); + + assert.deepEqual(result.matchedOrderIds, [ 201, 202 ]); + }); +}); diff --git a/test/app/service/systems/setting/warehouse.test.js b/test/app/service/systems/setting/warehouse.test.js index 346ab33..e3f1f3c 100644 --- a/test/app/service/systems/setting/warehouse.test.js +++ b/test/app/service/systems/setting/warehouse.test.js @@ -14,6 +14,15 @@ function createHarness(options = {}) { max_wave_quantity: 500, }; + const expressRows = Array.isArray(options.expressRows) ? options.expressRows : [ + { code: 'STO', name: '申通快递' }, + { code: 'YTO', name: '圆通快递' }, + ]; + const platformRows = Array.isArray(options.platformRows) ? options.platformRows : [ + { code: 'TB', name: '淘宝' }, + { code: 'JD', name: '京东' }, + ]; + const storeRecord = { id: Number(options.storeId || 100000), subject_config: { @@ -51,6 +60,26 @@ function createHarness(options = {}) { }; }, }, + ...(options.withoutExpressModel ? {} : { + Express: { + async findAll() { + if (options.expressQueryShouldThrow) { + throw new Error('query express failed'); + } + return expressRows; + }, + }, + }), + ...(options.withoutPlatformModel ? {} : { + Platform: { + async findAll() { + if (options.platformQueryShouldThrow) { + throw new Error('query platform failed'); + } + return platformRows; + }, + }, + }), }, }; @@ -101,4 +130,84 @@ describe('test/app/service/systems/setting/warehouse.test.js', () => { } ); }); + + it('外部传入 wave_strategy_version 不应覆盖现有内部版本,且响应不暴露该字段', async () => { + const { ctx, calls } = createHarness({ + initialSubjectConfig: { + max_wave_quantity: 500, + wave_strategy_version: 9, + }, + }); + const service = new SettingWarehouseService(ctx); + + const result = await service.saveSettings({ + subject_config: { + wave_strategy_version: 2, + max_wave_quantity: 700, + }, + }); + + assert.equal(calls.updatePayload.subject_config.wave_strategy_version, 9); + assert.equal(calls.updatePayload.subject_config.max_wave_quantity, 700); + assert.equal(Object.prototype.hasOwnProperty.call(result.subject_config, 'wave_strategy_version'), false); + }); + + it('should omit internal wave_strategy_version from getSettings response', async () => { + const { ctx } = createHarness({ + initialSubjectConfig: { + max_wave_quantity: 500, + wave_strategy_version: 3, + }, + }); + const service = new SettingWarehouseService(ctx); + + const result = await service.getSettings(); + + assert.equal(result.warehouse_id, 100000); + assert.equal(Object.prototype.hasOwnProperty.call(result.subject_config, 'wave_strategy_version'), false); + assert.equal(result.subject_config.max_wave_quantity, 500); + }); + + it('should include dynamic options for default_express_code and default_platform_code', async () => { + const { ctx } = createHarness(); + const service = new SettingWarehouseService(ctx); + + const list = await service.getFieldMeta(); + + const defaultExpressField = list.find(item => item.key === 'default_express_code'); + const defaultPlatformField = list.find(item => item.key === 'default_platform_code'); + + assert.ok(defaultExpressField, '字段信息应包含 default_express_code'); + assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code'); + assert.ok(Array.isArray(defaultExpressField.options), 'default_express_code 应包含 options 数组'); + assert.ok(Array.isArray(defaultPlatformField.options), 'default_platform_code 应包含 options 数组'); + assert.ok(defaultExpressField.options.every(option => option && typeof option.value === 'string' && typeof option.label === 'string')); + assert.ok(defaultPlatformField.options.every(option => option && typeof option.value === 'string' && typeof option.label === 'string')); + assert.deepEqual(defaultExpressField.options, [ + { value: 'STO', label: '申通快递' }, + { value: 'YTO', label: '圆通快递' }, + ]); + assert.deepEqual(defaultPlatformField.options, [ + { value: 'TB', label: '淘宝' }, + { value: 'JD', label: '京东' }, + ]); + }); + + it('should degrade gracefully when model missing or query fails', async () => { + const { ctx } = createHarness({ + withoutExpressModel: true, + platformQueryShouldThrow: true, + }); + const service = new SettingWarehouseService(ctx); + + const list = await service.getFieldMeta(); + + const defaultExpressField = list.find(item => item.key === 'default_express_code'); + const defaultPlatformField = list.find(item => item.key === 'default_platform_code'); + + assert.ok(defaultExpressField, '字段信息应包含 default_express_code'); + assert.ok(defaultPlatformField, '字段信息应包含 default_platform_code'); + assert.deepEqual(defaultExpressField.options, []); + assert.deepEqual(defaultPlatformField.options, []); + }); }); diff --git a/tmp/verify_migration.cjs b/tmp/verify_migration.cjs new file mode 100644 index 0000000..310d0f5 --- /dev/null +++ b/tmp/verify_migration.cjs @@ -0,0 +1,37 @@ +'use strict'; + +(async () => { + try { + const cfg = require('../database/config.js').production; + const mysql = require('mysql2/promise'); + const conn = await mysql.createConnection({ + host: cfg.host, + user: cfg.username || cfg.user, + password: cfg.password, + database: cfg.database, + port: cfg.port || 3306, + }); + + const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js'; + const schema = cfg.database; + + const [metaRows] = await conn.query('SELECT name FROM SequelizeMeta WHERE name = ? LIMIT 1', [migrationName]); + const migrationInMeta = (metaRows.length && metaRows.length > 0) ? true : false; + + const [tableRows] = await conn.query('SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND table_name = ?', [schema, 'wms_order_wave_strategy_match']); + const tableExists = (tableRows.length && tableRows.length > 0) ? true : false; + + const [columnsRows] = await conn.query('SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND COLUMN_NAME IN (?,?,?,?,?)', [schema, 'wms_order_wave_strategy_match', 'id','warehouse_id','order_id','strategy_id','create_time']); + const columns = (columnsRows || []).map(r => r.COLUMN_NAME); + + const [idxRows] = await conn.query('SELECT DISTINCT INDEX_NAME FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? AND INDEX_NAME IN (?,?)', [schema, 'wms_order_wave_strategy_match', 'idx_warehouse_order', 'idx_warehouse_strategy']); + const indices = (idxRows || []).map(r => r.INDEX_NAME); + + console.log(JSON.stringify({ migrationInMeta, tableExists, columns, indices }, null, 2)); + await conn.end(); + process.exit(0); + } catch (err) { + console.error('ERROR:', err && err.message ? err.message : err); + process.exit(2); + } +})();