diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index f12ecb0..d9f1539 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -214,6 +214,31 @@ function parseItems(rawItems) { return rawItems; } + if (isPlainObject(rawItems)) { + for (const key of Object.keys(rawItems)) { + if (Array.isArray(rawItems[key])) { + return rawItems[key]; + } + } + + const candidates = [ + rawItems.items, + rawItems.list, + rawItems.goods, + rawItems.products, + rawItems.product_list, + rawItems.rows, + ]; + + for (const candidate of candidates) { + if (Array.isArray(candidate)) { + return candidate; + } + } + + return []; + } + if (typeof rawItems === 'string') { const text = rawItems.trim(); if (!text) { @@ -222,15 +247,103 @@ function parseItems(rawItems) { try { const parsed = JSON.parse(text); - return Array.isArray(parsed) ? parsed : []; + return parseItems(parsed); } catch (error) { - return []; + function isNoiseQuantityOnlyText(value) { + const sample = String(value || '').trim(); + if (!sample) { + return true; + } + + return /^(?:\[?\s*\d+(?:\.\d+)?\s*\]?|【\s*\d+(?:\.\d+)?\s*】)(?:\s+0+)?$/.test(sample); + } + + function parseLooseItemText(rawText) { + const normalizedText = String(rawText || '').replace(/[;;]+$/g, '').trim(); + if (!normalizedText || isNoiseQuantityOnlyText(normalizedText)) { + return null; + } + + let quantity = '1'; + let workingText = normalizedText; + + const qtyBracketMatch = workingText.match(/【\s*(\d+(?:\.\d+)?)\s*】/); + if (qtyBracketMatch) { + quantity = String(qtyBracketMatch[1] || '1').trim() || '1'; + workingText = workingText.replace(qtyBracketMatch[0], ' ').trim(); + } else { + const qtyTailMatch = workingText.match(/(?:[xX×*]\s*(\d+(?:\.\d+)?))\s*$/); + if (qtyTailMatch) { + quantity = String(qtyTailMatch[1] || '1').trim() || '1'; + workingText = workingText.slice(0, qtyTailMatch.index).trim(); + } + } + + const barcodeMatch = workingText.match(/(?:^|[;;\s])(\d{5,})(?!\d)/); + const barcode = barcodeMatch ? String(barcodeMatch[1] || '').trim() : ''; + + let pickLocation = ''; + let itemName = workingText; + const locationMatch = workingText.match(/^([^\s;;]+(?:[-_][^\s;;]+)*)\s+/); + if (locationMatch) { + pickLocation = String(locationMatch[1] || '').trim(); + itemName = workingText.slice(locationMatch[0].length).trim(); + } + + if (barcode) { + itemName = itemName.replace(new RegExp(`(?:^|[;;\\s])${barcode}(?:$|[;;\\s])`), ' ').trim(); + } + itemName = itemName.replace(/[;;]+/g, ' ').trim(); + + if (isNoiseQuantityOnlyText(itemName)) { + itemName = ''; + } + + return { + pick_location: pickLocation, + item_name: itemName || workingText, + barcode, + quantity, + raw_text: normalizedText, + }; + } + + const itemTextList = text + .split(/\||\r\n|\n|\r/) + .map(part => String(part || '').trim()) + .filter(Boolean); + + if (itemTextList.length === 0) { + return []; + } + + const parsedItems = itemTextList + .map(itemText => parseLooseItemText(itemText)) + .filter(item => isPlainObject(item)); + return parsedItems; } } return []; } +/** + * 解析自定义区商品来源,优先兼容 order_delivery 与 order_express 双来源。 + * @param {Object} orderExpress 快递单对象。 + * @param {Object} orderDelivery 订单对象。 + * @return {Array} 商品列表。 + */ +function resolveCustomComposeItems(orderExpress, orderDelivery) { + const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const deliveryItems = parseItems(safeOrderDelivery.items); + if (deliveryItems.length > 0) { + return deliveryItems; + } + + return parseItems(safeOrderExpress.items); +} + /** * 在候选键中读取首个非空字段。 * @param {Object} item 商品对象。 @@ -292,6 +405,7 @@ function resolveItemBarcodeText(item) { 'item_barcode', 'item_code', 'sku_code', + 'sku', ]); } @@ -342,18 +456,20 @@ function resolveItemQuantity(item) { * @param {string} lineBreak 换行符。 * @return {string} 自定义区文本。 */ -function buildWaybillCustomProductInfo(items, policyConfig, lineBreak = LINE_BREAK_MAP.LF) { +function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { const safeItems = Array.isArray(items) ? items : []; const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; - const displayType = String( - safePolicyConfig[WAYBILL_CUSTOM_DISPLAY_FIELD] || WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE - ).trim(); + const safeOptions = isPlainObject(options) ? options : {}; + const hasDisplayType = Object.prototype.hasOwnProperty.call(safePolicyConfig, WAYBILL_CUSTOM_DISPLAY_FIELD); + const displayType = hasDisplayType + ? String(safePolicyConfig[WAYBILL_CUSTOM_DISPLAY_FIELD] || '').trim() + : WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY; - if (displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE || safeItems.length === 0) { - return ''; + if (displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE) { + return []; } - const lines = []; + const detailLines = []; let totalQty = 0; for (const item of safeItems) { @@ -384,6 +500,10 @@ function buildWaybillCustomProductInfo(items, policyConfig, lineBreak = LINE_BRE break; case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_LAST5_QTY: { const barcodeLast5 = barcode ? barcode.slice(-5) : ''; + if (!pickLocation && !barcodeLast5) { + line = ''; + break; + } line = `${pickLocation} ${barcodeLast5} 【${qtyText}】`.trim(); break; } @@ -396,16 +516,59 @@ function buildWaybillCustomProductInfo(items, policyConfig, lineBreak = LINE_BRE } if (line) { - lines.push(line.replace(/\s{2,}/g, ' ')); + detailLines.push(line.replace(/\s{2,}/g, ' ')); } } - if (lines.length === 0) { + const waveNo = String(safeOptions.waveNo || '').trim(); + const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0); + const waveIndex = toNumber(safeOptions.wave_index, 0); + const platformsIndex = toNumber(safeOptions.platforms_index, 0); + const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim(); + const fallbackTotalQtyRaw = Number(safeOptions.fallbackTotalQty); + const finalTotalQty = totalQty > 0 + ? totalQty + : (Number.isFinite(fallbackTotalQtyRaw) && fallbackTotalQtyRaw > 0 ? fallbackTotalQtyRaw : 0); + const hasWaveCustomPrefix = waveTotalOrders > 0 + && waveIndex > 0 + && platformsIndex > 0 + && Boolean(waveNo); + const waveHeaderText = hasWaveCustomPrefix + ? `【${waveTotalOrders}】${waveNo}_${waveIndex}_${platformsIndex}` + : waveNo; + const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); + headerParts.push(`商品数量【${finalTotalQty}】`); + const headerLine = headerParts.join(' '); + + if (detailLines.length === 0) { + return [ headerLine ]; + } + + return [ headerLine, ...detailLines ]; +} + +/** + * 将自定义文本行按平台换行符合并为字符串。 + * @param {Array} lines 文本行数组。 + * @param {Object} options 合并选项。 + * @param {string} [options.lineBreak=LINE_BREAK_MAP.LF] 换行符。 + * @param {boolean} [options.trailingLineBreak=false] 是否追加末尾换行。 + * @return {string} 合并后的文本。 + */ +function mergeWaybillCustomLines(lines = [], options = {}) { + const safeLines = Array.isArray(lines) ? lines.filter(line => String(line || '').trim() !== '') : []; + if (safeLines.length === 0) { return ''; } - const header = `商品总数 【${Number.isFinite(totalQty) ? totalQty : 0}】`; - return normalizeLineBreak([ header, ...lines ].join(LINE_BREAK_MAP.LF), lineBreak); + const safeOptions = isPlainObject(options) ? options : {}; + const lineBreak = safeOptions.lineBreak || LINE_BREAK_MAP.LF; + const trailingLineBreak = Boolean(safeOptions.trailingLineBreak); + let text = normalizeLineBreak(safeLines.join(LINE_BREAK_MAP.LF), lineBreak); + if (trailingLineBreak) { + text += lineBreak; + } + return text; } /** @@ -660,7 +823,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 */ -function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, warnings, policyConfig, customDataTemplateURL) { +function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL) { if (platform !== 'kuaishou') { return; } @@ -680,11 +843,28 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, warn const signature = toTrimmedString(safeOrderExpress.signature); const key = toTrimmedString(safeOrderExpress.encryptprintinfo); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); - const customProductInfo = buildWaybillCustomProductInfo( - parseItems(safeOrderExpress.items), + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, safePolicyConfig, - LINE_BREAK_MAP.LF + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.LF, + }); for (const document of documents) { if (!isPlainObject(document)) { @@ -782,7 +962,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, warn * @param {Object} orderExpress 快递单对象。 * @param {Object} policyConfig 策略配置对象。 */ -function applyPddExpressFieldMapping(platform, skeleton, orderExpress, policyConfig) { +function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { if (platform !== 'pdd') { return; } @@ -801,11 +981,29 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, policyCon const encryptedData = toTrimmedString(safeOrderExpress.printinfo); const signature = toTrimmedString(safeOrderExpress.signature); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); - const customProductInfo = buildWaybillCustomProductInfo( - parseItems(safeOrderExpress.items), + const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; + const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); + const customProductInfoLines = buildWaybillCustomProductInfoLines( + composeItems, safePolicyConfig, - LINE_BREAK_MAP.CR + { + waveNo: toTrimmedString(safeOrderDelivery.wave_no), + wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), + wave_index: Number(safeOrderDelivery.wave_index || 0), + platforms_index: Number(safeOrderDelivery.platforms_index || 0), + expressInterfaceName: toTrimmedString( + safeOrderExpress.logistics_interface_name + || safeOrderExpress.logistics_name + || safeOrderDelivery.logistics_interface_name + || safeOrderDelivery.logistics_name + ), + fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), + } ); + const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { + lineBreak: LINE_BREAK_MAP.CR, + trailingLineBreak: true, + }); /** * 判断内容对象是否属于拼多多自定义区。 @@ -997,6 +1195,7 @@ function buildPlatformRequestSkeleton(input = {}) { normalized.platform, skeleton, orderExpressForCompose, + orderDeliveryForCompose, warnings, policyConfig, customDataTemplateURL @@ -1006,6 +1205,7 @@ function buildPlatformRequestSkeleton(input = {}) { normalized.platform, skeleton, orderExpressForCompose, + orderDeliveryForCompose, policyConfig ); diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 8650894..3702280 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -2,7 +2,6 @@ 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; @@ -25,8 +24,6 @@ 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(); @@ -48,41 +45,6 @@ const WAVE_STRATEGY_FALLBACK_WHERE_FIELD_MAP = Object.freeze({ province: 'province', sys_platform_name: 'sys_platform_name', }); -const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({ - storage: Object.freeze({ - fieldName: 'storage_assignment_status', - enumMap: Object.freeze({ - 未分配: 'none', - 部分分配: 'partial', - 已分配: 'finished', - }), - caseInsensitive: false, - statsColumnPrefix: 'storage', - withErrorStatus: true, - }), - express: Object.freeze({ - fieldName: 'express_assignment_status', - enumMap: Object.freeze({ - unassigned: 'none', - partially_assigned: 'partial', - assigned: 'finished', - }), - caseInsensitive: true, - statsColumnPrefix: 'post', - withErrorStatus: true, - }), - print: Object.freeze({ - fieldName: 'print_assignment_status', - enumMap: Object.freeze({ - unprinted: 'none', - partially_printed: 'partial', - printed: 'finished', - }), - caseInsensitive: true, - statsColumnPrefix: 'print', - withErrorStatus: false, - }), -}); class WaveService extends OrderBaseService { /** @@ -93,9 +55,9 @@ class WaveService extends OrderBaseService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'wavePickTaskCancelSelf,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'; + const _noNeedRight = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; + const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -696,9 +658,8 @@ 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}>} 创建结果。 */ @@ -714,7 +675,6 @@ class WaveService extends OrderBaseService { wavePrefix, waveNo, waveType, - source, transaction, } = {}) { const normalizedWarehouseId = Number(warehouseId || 0); @@ -728,8 +688,6 @@ class WaveService extends OrderBaseService { 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(); @@ -754,7 +712,6 @@ class WaveService extends OrderBaseService { item_snapshot_key, warehouse_id, creator, - source, create_time, update_time ) @@ -773,7 +730,6 @@ class WaveService extends OrderBaseService { :itemSnapshotKey, :warehouseId, :creator, - :source, NOW(), NOW() ) @@ -792,7 +748,6 @@ class WaveService extends OrderBaseService { itemSnapshotKey: normalizedItemSnapshotKey, warehouseId: Number.isInteger(normalizedWarehouseId) ? normalizedWarehouseId : 0, creator, - source: normalizedSource, }, transaction, }); @@ -854,7 +809,6 @@ 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( @@ -873,8 +827,6 @@ 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) @@ -933,7 +885,6 @@ class WaveService extends OrderBaseService { logisticsName: structure.logistics_name, itemSnapshotKey: structure.item_snapshot_key, wavePrefix, - source: normalizedSource, transaction, }); const orderFlagExpression = this.app.Sequelize.literal(`CASE @@ -1024,10 +975,6 @@ 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 = '可抓取订单不足'; @@ -1212,64 +1159,6 @@ class WaveService extends OrderBaseService { * @return {string} 规范化后的筛选值,未传时返回空字符串。 */ normalizeBatchListStorageAssignmentStatusFilter(value) { - return this.normalizeBatchListAssignmentStatusFilterByType(value, 'storage'); - } - - /** - * 规范化波次列表快递分配状态筛选值(英文枚举)。 - * - * @param {string} value 入参筛选值。 - * @return {string} 规范化后的筛选值,未传时返回空字符串。 - */ - normalizeBatchListExpressAssignmentStatusFilter(value) { - return this.normalizeBatchListAssignmentStatusFilterByType(value, 'express'); - } - - /** - * 规范化波次列表打印状态筛选值(英文枚举)。 - * - * @param {string} value 入参筛选值。 - * @return {string} 规范化后的筛选值,未传时返回空字符串。 - */ - normalizeBatchListPrintAssignmentStatusFilter(value) { - return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print'); - } - - /** - * 根据类型获取波次分配状态筛选配置。 - * - * @param {'storage'|'express'|'print'} type 筛选类型。 - * @return {{ fieldName: string, enumMap: Object, caseInsensitive: boolean, statsColumnPrefix: string, withErrorStatus: boolean }} 筛选配置。 - */ - getBatchListAssignmentFilterSchema(type) { - const normalizedType = String(type || '').trim(); - const schema = BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS[normalizedType]; - if (!schema) { - throw new Error(`不支持的分配状态筛选类型: ${normalizedType}`); - } - return schema; - } - - /** - * 按类型规范化波次列表分配状态筛选值。 - * - * @param {string} value 入参筛选值。 - * @param {'storage'|'express'|'print'} type 筛选类型。 - * @return {string} 规范化后的筛选值,未传时返回空字符串。 - */ - normalizeBatchListAssignmentStatusFilterByType(value, type) { - const schema = this.getBatchListAssignmentFilterSchema(type); - return this.normalizeBatchListAssignmentStatusFilter(value, schema); - } - - /** - * 规范化波次列表分配状态筛选值。 - * - * @param {string} value 入参筛选值。 - * @param {{ fieldName: string, enumMap: Object, caseInsensitive: boolean }} schema 筛选配置。 - * @return {string} 规范化后的筛选标识(none/partial/finished)。 - */ - normalizeBatchListAssignmentStatusFilter(value, schema) { if (value === undefined || value === null || value === '') { return ''; } @@ -1279,23 +1168,12 @@ class WaveService extends OrderBaseService { return ''; } - const enumMap = this.isPlainObject(schema && schema.enumMap) ? schema.enumMap : {}; - const allowedValues = Object.keys(enumMap); - const isCaseInsensitive = Boolean(schema && schema.caseInsensitive); - const lookupValue = isCaseInsensitive ? normalizedValue.toLowerCase() : normalizedValue; - const normalizedEnumMap = isCaseInsensitive - ? Object.fromEntries( - Object.entries(enumMap).map(([ key, mappedValue ]) => [ String(key).toLowerCase(), mappedValue ]) - ) - : enumMap; - const matchedValue = normalizedEnumMap[lookupValue]; - - if (!matchedValue) { - const fieldName = String(schema && schema.fieldName || 'assignment_status'); - throw new Error(`${fieldName} 参数不合法,仅支持: ${allowedValues.join('、')}`); + const allowedValues = [ '未分配', '部分分配', '已分配' ]; + if (!allowedValues.includes(normalizedValue)) { + throw new Error(`storage_assignment_status 参数不合法,仅支持: ${allowedValues.join('、')}`); } - return matchedValue; + return normalizedValue; } /** @@ -1339,50 +1217,7 @@ class WaveService extends OrderBaseService { * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 */ buildBatchListStorageAssignmentFilterClause(statusFilter = '') { - return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'storage'); - } - - /** - * 构建波次列表快递分配状态筛选 SQL 条件。 - * - * @param {string} statusFilter 快递分配状态筛选值(none/partial/finished)。 - * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 - */ - buildBatchListExpressAssignmentFilterClause(statusFilter = '') { - return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'express'); - } - - /** - * 构建波次列表打印状态筛选 SQL 条件。 - * - * @param {string} statusFilter 打印状态筛选值(none/partial/finished)。 - * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 - */ - buildBatchListPrintAssignmentFilterClause(statusFilter = '') { - return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print'); - } - - /** - * 按类型构建波次列表分配状态筛选 SQL 条件。 - * - * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 - * @param {'storage'|'express'|'print'} type 筛选类型。 - * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 - */ - buildBatchListAssignmentStatusFilterClauseByType(statusFilter = '', type = 'storage') { - const schema = this.getBatchListAssignmentFilterSchema(type); - return this.buildBatchListAssignmentStatusFilterClause(statusFilter, schema); - } - - /** - * 构建波次列表分配状态筛选 SQL 条件(通用)。 - * - * @param {string} statusFilter 分配状态筛选值(none/partial/finished)。 - * @param {{ statsColumnPrefix: string, withErrorStatus: boolean }} schema 筛选配置。 - * @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。 - */ - buildBatchListAssignmentStatusFilterClause(statusFilter = '', schema = {}) { - const normalizedStatusFilter = String(statusFilter || '').trim(); + const normalizedStatusFilter = this.normalizeBatchListStorageAssignmentStatusFilter(statusFilter); if (!normalizedStatusFilter) { return { sql: '', @@ -1390,54 +1225,47 @@ class WaveService extends OrderBaseService { }; } - const statsPrefix = String(schema && schema.statsColumnPrefix || '').trim(); - if (!statsPrefix) { - throw new Error('分配状态筛选配置不完整,缺少统计字段前缀'); - } - const totalExpr = 'COALESCE(wave_order_stats.order_total, 0)'; - const noneExpr = `COALESCE(wave_order_stats.${statsPrefix}_none_count, 0)`; - const finExpr = `COALESCE(wave_order_stats.${statsPrefix}_fin_count, 0)`; - const withErrorStatus = Boolean(schema && schema.withErrorStatus); - const errorExpr = withErrorStatus ? `COALESCE(wave_order_stats.${statsPrefix}_error_count, 0)` : ''; + const storageNoneExpr = 'COALESCE(wave_order_stats.storage_none_count, 0)'; + const storageFinExpr = 'COALESCE(wave_order_stats.storage_fin_count, 0)'; + const storageErrorExpr = 'COALESCE(wave_order_stats.storage_error_count, 0)'; + let whereClause = ''; - if (normalizedStatusFilter === 'finished') { - return { - sql: ` - AND ${finExpr} = ${totalExpr} - AND ${totalExpr} > 0`, - replacements: {}, - }; - } - - if (normalizedStatusFilter === 'partial') { - return { - sql: ` - AND ${withErrorStatus ? `${errorExpr} = 0\n AND ` : ''}${noneExpr} <> ${totalExpr} - AND ${finExpr} <> ${totalExpr}`, - replacements: {}, - }; - } - - if (normalizedStatusFilter === 'none') { + if (normalizedStatusFilter === '已分配') { + whereClause = ` + ${storageFinExpr} = ${totalExpr} + AND ${totalExpr} > 0 + `; + } else if (normalizedStatusFilter === '部分分配') { + whereClause = ` + ${storageErrorExpr} = 0 + AND ${storageNoneExpr} <> ${totalExpr} + AND ${storageFinExpr} <> ${totalExpr} + `; + } else if (normalizedStatusFilter === '未分配') { return { sql: ` AND ( ${totalExpr} = 0 - ${withErrorStatus ? `OR ${errorExpr} > 0\n ` : ''}OR ${noneExpr} = ${totalExpr} + OR ${storageErrorExpr} > 0 + OR ${storageNoneExpr} = ${totalExpr} )`, replacements: {}, }; } - throw new Error(`不支持的分配状态筛选值: ${normalizedStatusFilter}`); + return { + sql: ` + AND ${whereClause}`, + replacements: {}, + }; } /** * 构建波次列表 where 条件(白名单字段)。 * - * @param {Object} whereData 查询 where 入参。 - * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string, expressAssignmentStatus: string, printAssignmentStatus: string }} SQL 条件片段、参数与分配状态筛选值。 + * @param {Object} whereData 查询 where 入参。 + * @return {{ sql: string, replacements: Object, storageAssignmentStatus: string }} SQL 条件片段、参数与库位分配状态筛选值。 */ buildBatchListWhereClause(whereData = {}) { const normalizedWhere = this.isPlainObject(whereData) ? whereData : {}; @@ -1459,14 +1287,11 @@ class WaveService extends OrderBaseService { 'item_snapshot_key', 'item_detail_machine', 'distinguish_express', - 'source', 'total_orders_min', 'total_orders_max', 'processed_orders_min', 'processed_orders_max', 'storage_assignment_status', - 'express_assignment_status', - 'print_assignment_status', ]; const invalidFields = whereKeys.filter(key => !allowedFields.includes(key)); @@ -1542,7 +1367,6 @@ 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'); @@ -1594,231 +1418,11 @@ class WaveService extends OrderBaseService { const storageAssignmentStatus = this.normalizeBatchListStorageAssignmentStatusFilter( normalizedWhere.storage_assignment_status ); - const expressAssignmentStatus = this.normalizeBatchListExpressAssignmentStatusFilter( - normalizedWhere.express_assignment_status - ); - const printAssignmentStatus = this.normalizeBatchListPrintAssignmentStatusFilter( - normalizedWhere.print_assignment_status - ); return { sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '', replacements, storageAssignmentStatus, - expressAssignmentStatus, - printAssignmentStatus, - }; - } - - /** - * 解析拣货任务列表分页参数。 - * - * 兼容 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, }; } @@ -2542,17 +2146,6 @@ class WaveService extends OrderBaseService { */ 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) { @@ -2565,15 +2158,10 @@ class WaveService extends OrderBaseService { } const offset = (page - 1) * pageSize; - const where = { - warehouse_id: contextWarehouseId, - }; - if (normalizedStrategyType !== undefined) { - where.strategy_type = normalizedStrategyType; - } - const queryResult = await strategyModel.findAndCountAll({ - where, + where: { + warehouse_id: contextWarehouseId, + }, order: [ [ 'status', 'DESC' ], [ 'id', 'DESC' ], @@ -2584,33 +2172,11 @@ class WaveService extends OrderBaseService { }); 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, + list, pagination: { page, pageSize, @@ -2622,231 +2188,6 @@ class WaveService extends OrderBaseService { }); } - /** - * 批量预演当前页策略“下一个抓取订单数”。 - * - * 仅执行候选查询与规则计算,不写库、不建波次、不占锁。 - * - * @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; - } - /** * 新增波次策略。 * @@ -3067,30 +2408,6 @@ class WaveService extends OrderBaseService { 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') { @@ -3150,13 +2467,7 @@ class WaveService extends OrderBaseService { } 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 参数不能为空'); - } + payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); } else { if (Object.prototype.hasOwnProperty.call(requestData, 'strategy_name')) { const strategyName = String(requestData.strategy_name || '').trim(); @@ -3169,9 +2480,7 @@ class WaveService extends OrderBaseService { 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; + payload.batch_mode = this.normalizeRequiredPositiveInteger(requestData.batch_mode, 'batch_mode'); } } @@ -3189,58 +2498,9 @@ class WaveService extends OrderBaseService { 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'); - } - } + this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_orders'); + this.patchWaveStrategyIntegerField(payload, requestData, 'batch_max_skus'); + this.patchWaveStrategyIntegerField(payload, requestData, 'group_batch_max_orders'); if (Object.prototype.hasOwnProperty.call(requestData, 'require_same_express')) { payload.require_same_express = this.normalizeBoolean(requestData.require_same_express, false); @@ -3251,9 +2511,6 @@ class WaveService extends OrderBaseService { if (Object.prototype.hasOwnProperty.call(requestData, 'description')) { payload.description = String(requestData.description || '').trim(); } - if (mode === 'create' || Object.prototype.hasOwnProperty.call(requestData, 'wave_prefix')) { - payload.wave_prefix = this.normalizeWaveStrategyWavePrefix(requestData.wave_prefix); - } if (Object.prototype.hasOwnProperty.call(requestData, 'allowed_provinces')) { payload.allowed_provinces = this.normalizeWaveStrategyQuickScanStringList(requestData.allowed_provinces); } @@ -3282,71 +2539,6 @@ class WaveService extends OrderBaseService { return payload; } - /** - * 归一化波次策略波次前缀。 - * - * 规则: - * 1. 允许为空字符串(表示回退仓库前缀); - * 2. 非空时统一转大写; - * 3. 非空时仅允许 A-Z0-9,长度 1-5。 - * - * @param {*} rawWavePrefix 原始波次前缀入参。 - * @return {string} 归一化后的波次前缀。 - */ - normalizeWaveStrategyWavePrefix(rawWavePrefix) { - if (rawWavePrefix === undefined || rawWavePrefix === null) { - return ''; - } - - const normalizedWavePrefix = String(rawWavePrefix).trim() - .toUpperCase(); - if (!normalizedWavePrefix) { - return ''; - } - - if (normalizedWavePrefix.length < 1 || normalizedWavePrefix.length > 5) { - throw new Error('wave_prefix 非空时长度必须为 1-5 个字符'); - } - - if (!/^[A-Z0-9]+$/.test(normalizedWavePrefix)) { - throw new Error('wave_prefix 非空时仅支持 A-Z0-9'); - } - - return normalizedWavePrefix; - } - - /** - * 解析策略抓取建波使用的前缀(策略优先,仓库前缀兜底)。 - * - * @param {Object} params 解析参数。 - * @param {number|string} params.warehouseId 仓库ID。 - * @param {number|string} params.strategyType 策略类型(1-散单,2-团购)。 - * @param {Object} [params.strategyRow={}] 策略行。 - * @return {Promise<{ wavePrefix: string, source: string }>} 前缀及来源。 - */ - async resolveWaveStrategyFetchWavePrefix(params = {}) { - const warehouseId = this.normalizeRequiredPositiveInteger(params.warehouseId, 'warehouse_id'); - const strategyType = Number(params.strategyType || 0); - const strategyRow = this.isPlainObject(params.strategyRow) ? params.strategyRow : {}; - const strategyWavePrefix = this.normalizeWaveStrategyWavePrefix(strategyRow.wave_prefix); - - if (strategyWavePrefix) { - return { - wavePrefix: strategyWavePrefix, - source: 'strategy', - }; - } - - const warehouseWavePrefix = strategyType === 2 - ? await this.getGroupWavePrefix(warehouseId) - : await this.getSingleFetchByIdsWavePrefix(warehouseId); - - return { - wavePrefix: String(warehouseWavePrefix || '').trim() || (strategyType === 2 ? 'B' : 'A'), - source: 'warehouse_fallback', - }; - } - /** * 按字段补丁方式归一化波次策略正整数参数。 * @@ -3840,8 +3032,6 @@ class WaveService extends OrderBaseService { const orderTableName = this.getModelTableSqlName(orderModel); const whereClause = this.buildBatchListWhereClause(requestData.where); const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus); - const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus); - const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus); const baseBatchWhereSql = ` warehouse_id = :warehouseId AND wave_status IN (:waveStatusList) @@ -3857,7 +3047,6 @@ class WaveService extends OrderBaseService { total_orders, processed_orders, distinguish_express, - source, logistics_name, item_snapshot_key, warehouse_id, @@ -3873,12 +3062,7 @@ class WaveService extends OrderBaseService { COUNT(od.wave_id) AS order_total, SUM(CASE WHEN od.storage_status = 'none' THEN 1 ELSE 0 END) AS storage_none_count, SUM(CASE WHEN od.storage_status = 'fin' THEN 1 ELSE 0 END) AS storage_fin_count, - SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count, - SUM(CASE WHEN od.post_status = 'none' THEN 1 ELSE 0 END) AS post_none_count, - SUM(CASE WHEN od.post_status = 'fin' THEN 1 ELSE 0 END) AS post_fin_count, - SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count, - SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count, - SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count + SUM(CASE WHEN od.storage_status = 'error' THEN 1 ELSE 0 END) AS storage_error_count FROM ( SELECT wave_id FROM wms_wave_batch @@ -3889,8 +3073,6 @@ class WaveService extends OrderBaseService { ) wave_order_stats ON wave_order_stats.wave_id = wb.wave_id WHERE 1 = 1 ${storageAssignmentFilterClause.sql} - ${expressAssignmentFilterClause.sql} - ${printAssignmentFilterClause.sql} `; const listSql = ` @@ -3902,22 +3084,12 @@ 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, wb.creator, wb.create_time, - wb.update_time, - COALESCE(wave_order_stats.order_total, 0) AS order_total, - COALESCE(wave_order_stats.storage_none_count, 0) AS storage_none_count, - COALESCE(wave_order_stats.storage_fin_count, 0) AS storage_fin_count, - COALESCE(wave_order_stats.storage_error_count, 0) AS storage_error_count, - COALESCE(wave_order_stats.post_none_count, 0) AS post_none_count, - COALESCE(wave_order_stats.post_fin_count, 0) AS post_fin_count, - COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count, - COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count, - COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count + wb.update_time ${batchListFromSql} ORDER BY wb.total_orders DESC, wb.wave_id DESC LIMIT :limit OFFSET :offset @@ -3935,8 +3107,6 @@ class WaveService extends OrderBaseService { waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.replacements, - ...expressAssignmentFilterClause.replacements, - ...printAssignmentFilterClause.replacements, limit: pageSize, offset, }, @@ -3947,8 +3117,6 @@ class WaveService extends OrderBaseService { waveStatusList, ...whereClause.replacements, ...storageAssignmentFilterClause.replacements, - ...expressAssignmentFilterClause.replacements, - ...printAssignmentFilterClause.replacements, }, }), ]); @@ -3972,17 +3140,82 @@ class WaveService extends OrderBaseService { }); } + const waveIds = rawList + .map(item => Number(item && item.wave_id || 0)) + .filter(id => Number.isInteger(id) && id > 0); + + const orderRows = waveIds.length > 0 + ? await orderModel.findAll({ + where: { + wave_id: { [Op.in]: waveIds }, + }, + attributes: [ 'wave_id', 'storage_status', 'post_status', 'print_status' ], + raw: true, + }) + : []; + + const waveOrderStatsMap = new Map(); + for (const row of orderRows) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + if (!waveOrderStatsMap.has(waveId)) { + waveOrderStatsMap.set(waveId, { + orderCount: 0, + storageNoneCount: 0, + storageFinCount: 0, + storageErrorCount: 0, + expressNoneCount: 0, + expressFinCount: 0, + expressErrorCount: 0, + printNoneCount: 0, + printFinCount: 0, + }); + } + + const stats = waveOrderStatsMap.get(waveId); + const storageStatus = String(row && row.storage_status || '').trim(); + const expressStatus = String(row && row.post_status || '').trim(); + const printStatus = String(row && row.print_status || '').trim(); + + stats.orderCount += 1; + if (storageStatus === 'none') { + stats.storageNoneCount += 1; + } else if (storageStatus === 'fin') { + stats.storageFinCount += 1; + } else if (storageStatus === 'error') { + stats.storageErrorCount += 1; + } + + if (expressStatus === 'none') { + stats.expressNoneCount += 1; + } else if (expressStatus === 'fin') { + stats.expressFinCount += 1; + } else if (expressStatus === 'error') { + stats.expressErrorCount += 1; + } + + if (printStatus === 'none') { + stats.printNoneCount += 1; + } else if (printStatus === 'fin') { + stats.printFinCount += 1; + } + } + const list = rawList.map(batch => { const waveId = Number(batch && batch.wave_id || 0); - const orderCount = Number(batch && batch.order_total || 0); - const storageNoneCount = Number(batch && batch.storage_none_count || 0); - const storageFinCount = Number(batch && batch.storage_fin_count || 0); - const storageErrorCount = Number(batch && batch.storage_error_count || 0); - const expressNoneCount = Number(batch && batch.post_none_count || 0); - const expressFinCount = Number(batch && batch.post_fin_count || 0); - const expressErrorCount = Number(batch && batch.post_error_count || 0); - const printNoneCount = Number(batch && batch.print_none_count || 0); - const printFinCount = Number(batch && batch.print_fin_count || 0); + const stats = waveOrderStatsMap.get(waveId) || {}; + const orderCount = Number(stats.orderCount || 0); + const storageNoneCount = Number(stats.storageNoneCount || 0); + const storageFinCount = Number(stats.storageFinCount || 0); + const storageErrorCount = Number(stats.storageErrorCount || 0); + const expressNoneCount = Number(stats.expressNoneCount || 0); + const expressFinCount = Number(stats.expressFinCount || 0); + const expressErrorCount = Number(stats.expressErrorCount || 0); + const printNoneCount = Number(stats.printNoneCount || 0); + const printFinCount = Number(stats.printFinCount || 0); return { wave_id: waveId, @@ -3995,7 +3228,6 @@ 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), @@ -4026,133 +3258,6 @@ 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); - } - } - /** * 批量解除波次任务提交接口。 * @@ -4188,22 +3293,6 @@ 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); @@ -4214,7 +3303,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: '批量解除波次任务已存在,请勿重复提交。', + message: 'Batch cancel task already exists. Check progress with order.wave.batchCancelTaskProgress', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4260,7 +3349,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: '批量解除波次任务已提交。', + message: 'Batch cancel submitted. Check progress with order.wave.batchCancelTaskProgress', accepted_at: acceptedAt, }); } @@ -4411,7 +3500,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: '批量分配快递任务已存在,请勿重复提交。', + message: 'Batch allocate express task already exists. Check progress with order.wave.batchAllocateExpressTaskProgress', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4465,7 +3554,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: '批量分配快递任务已提交。', + message: 'Batch allocate express submitted. Check progress with order.wave.batchAllocateExpressTaskProgress', accepted_at: acceptedAt, }); } catch (error) { @@ -4591,7 +3680,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: '批量分配储位任务已存在,请勿重复提交。', + message: 'Batch allocate storage task already exists. Check progress with order.wave.batchAllocateStorageTaskProgress', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -4642,7 +3731,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: '批量分配储位任务已提交。', + message: 'Batch allocate storage submitted. Check progress with order.wave.batchAllocateStorageTaskProgress', accepted_at: acceptedAt, }); } @@ -4751,110 +3840,6 @@ 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数组。 - * @param {boolean} [options.wait=false] 是否等待任务执行完成后再返回最终进度快照。 - * @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 wait = this.normalizeBoolean(normalizedOptions.wait, false); - - 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, - }); - - if (wait) { - await this.runWaveStrategyQuickScanTask({ - taskId, - warehouseId: normalizedWarehouseId, - ...(orderIds.length > 0 ? { orderIds } : {}), - }); - - const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {}; - return { - ...finalProgress, - task_id: taskId, - warehouse_id: normalizedWarehouseId, - 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, - }; - } - /** * 提交波次策略快速扫描异步任务。 * @@ -4868,11 +3853,72 @@ class WaveService extends OrderBaseService { throw new Error('未识别到当前仓库上下文'); } - const submitPayload = await this.submitWaveStrategyQuickScanForWarehouse(contextWarehouseId); + const warehouseId = contextWarehouseId; + const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(warehouseId); + if (runningTask && runningTask.task_id) { + const existingTaskId = String(runningTask.task_id || '').trim(); + const existingProgress = await this.getWaveStrategyQuickScanTaskProgress(existingTaskId); + const existingState = String(existingProgress && existingProgress.state || runningTask.state || 'running').trim() || 'running'; + + if (![ 'success', 'failed' ].includes(existingState)) { + return this.success('ok', { + status: 'success', + task_id: existingTaskId, + warehouse_id: warehouseId, + state: existingState, + message: 'Quick scan task is already running. Check progress with order.wave.waveStrategyQuickScanTaskProgress', + accepted_at: runningTask.accepted_at || existingProgress && existingProgress.accepted_at || new Date().toISOString(), + }); + } + + await this.clearWaveStrategyQuickScanWarehouseLock(warehouseId, existingTaskId); + } + + const taskId = this.generateWaveStrategyQuickScanTaskId(warehouseId); + const acceptedAt = new Date().toISOString(); + + await this.setWaveStrategyQuickScanTaskProgress(taskId, 'submitted', { + warehouse_id: warehouseId, + total_order_count: 0, + processed_order_count: 0, + matched_order_count: 0, + unmatched_order_count: 0, + progress_percent: 0, + submitted_at: Date.now(), + accepted_at: acceptedAt, + start_time: null, + end_time: null, + error: '', + error_code: '', + result: null, + }); + + await this.setWaveStrategyQuickScanWarehouseLock(warehouseId, taskId, { + state: 'submitted', + accepted_at: acceptedAt, + }); + + setImmediate(() => { + this.runWaveStrategyQuickScanTask({ + taskId, + warehouseId, + }).catch(error => { + this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', { + taskId, + warehouseId, + error: error && error.message ? error.message : error, + stack: error && error.stack ? error.stack : '', + }); + }); + }); return this.success('ok', { status: 'success', - ...submitPayload, + task_id: taskId, + warehouse_id: warehouseId, + state: 'submitted', + message: 'Quick scan task submitted. Check progress with order.wave.waveStrategyQuickScanTaskProgress', + accepted_at: acceptedAt, }); } @@ -4916,418 +3962,6 @@ class WaveService extends OrderBaseService { }); } - /** - * 构建快速扫描订单查询条件。 - * - * @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, - }; - } - /** * 执行波次策略快速扫描后台任务。 * @@ -5336,9 +3970,6 @@ class WaveService extends OrderBaseService { * @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 = {}) { @@ -5382,27 +4013,61 @@ class WaveService extends OrderBaseService { }); 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, + const strategyModel = this.ctx.model && ( + this.ctx.model.wms_wave_strategy + || this.ctx.model.PickingStrategy + || this.ctx.model.WmsWaveStrategy + ); + if (!strategyModel || typeof strategyModel.findAll !== 'function') { + throw new Error('波次策略模型不可用'); + } + + const strategyRows = await strategyModel.findAll({ + where: { + warehouse_id: warehouseId, + status: 1, + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows); + + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + const orderRows = await orderModel.findAll({ + attributes: [ + 'id', + 'store_id', + 'items_count', + 'items_total', + 'items_hash', + 'items', + 'logistics_code', + 'sys_logistics_code', + 'logistics_name', + 'province', + 'sys_platform_code', + 'source_platform_code', + ], + where: { + warehouse_id: warehouseId, + step: { [Op.ne]: 0 }, + wave_id: 0, + [Op.or]: [ + { wave_strategy_version: { [Op.ne]: strategyVersion } }, + { wave_strategy_version: { [Op.is]: null } }, + ], + }, + raw: true, }); - if (scanResult.totalOrderCount === 0) { + const normalizedOrders = Array.isArray(orderRows) ? orderRows : []; + const totalOrderCount = normalizedOrders.length; + if (totalOrderCount === 0) { const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, @@ -5422,24 +4087,77 @@ class WaveService extends OrderBaseService { return; } + const structureStoreSetMap = new Map(); + + for (const order of normalizedOrders) { + const structureKey = this.getWaveStrategyQuickScanStructureKey(order); + if (!structureKey) { + continue; + } + + const storeId = String(order && order.store_id || '').trim(); + if (!structureStoreSetMap.has(structureKey)) { + structureStoreSetMap.set(structureKey, new Set()); + } + if (storeId) { + structureStoreSetMap.get(structureKey).add(storeId); + } + } + + const matchedOrderIds = []; + const unmatchedOrderIds = []; + let processedOrderCount = 0; + + for (const order of normalizedOrders) { + const matched = this.isWaveStrategyQuickScanOrderMatched(order, strategyList, { + structureStoreSetMap, + }); + + const orderId = Number(order && order.id || 0); + if (Number.isInteger(orderId) && orderId > 0) { + if (matched) { + matchedOrderIds.push(orderId); + } else { + unmatchedOrderIds.push(orderId); + } + } + + processedOrderCount += 1; + if (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount) { + await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'running', { + warehouse_id: warehouseId, + total_order_count: totalOrderCount, + processed_order_count: processedOrderCount, + matched_order_count: matchedOrderIds.length, + unmatched_order_count: unmatchedOrderIds.length, + progress_percent: Math.min(99, Math.round((processedOrderCount / totalOrderCount) * 100)), + }); + } + } + + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, matchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 1, + }); + await this.batchUpdateWaveStrategyQuickScanOrders(orderModel, unmatchedOrderIds, { + wave_strategy_version: strategyVersion, + wave_scan_result: 2, + }); + const durationMs = Date.now() - startTime; await this.setWaveStrategyQuickScanTaskProgress(normalizedTaskId, 'success', { warehouse_id: warehouseId, - total_order_count: scanResult.totalOrderCount, - processed_order_count: scanResult.processedOrderCount, - matched_order_count: scanResult.matchedOrderCount, - unmatched_order_count: scanResult.unmatchedOrderCount, + total_order_count: totalOrderCount, + processed_order_count: totalOrderCount, + matched_order_count: matchedOrderIds.length, + unmatched_order_count: unmatchedOrderIds.length, progress_percent: 100, end_time: Date.now(), duration_ms: durationMs, result: { strategy_version: strategyVersion, - 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, + matched_order_count: matchedOrderIds.length, + unmatched_order_count: unmatchedOrderIds.length, duration_ms: durationMs, message: '波次策略快速扫描完成', }, @@ -5715,9 +4433,7 @@ class WaveService extends OrderBaseService { 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), @@ -5832,13 +4548,23 @@ class WaveService extends OrderBaseService { } /** - * 计算订单快递 key(同快递判定仅使用 sys_logistics_code)。 + * 计算订单快递 key。 * * @param {Object} order 订单记录。 - * @return {string} 快递 key(sys_logistics_code 去首尾空格后结果,空值返回空字符串)。 + * @return {string} 快递 key。 */ getWaveStrategyQuickScanExpressKey(order = {}) { - return String(order && order.sys_logistics_code || '').trim(); + const sysLogisticsCode = String(order && order.sys_logistics_code || '').trim(); + if (sysLogisticsCode) { + return sysLogisticsCode; + } + + const logisticsCode = String(order && order.logistics_code || '').trim(); + if (logisticsCode) { + return logisticsCode; + } + + return String(order && order.logistics_name || '').trim(); } /** @@ -5850,39 +4576,18 @@ class WaveService extends OrderBaseService { * @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 []; + return false; } - 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); + if (this.isWaveStrategyQuickScanOrderMatchedSingleStrategy(order, strategy, context)) { + return true; } } - return [ ...new Set(matchedStrategyIds) ]; + return false; } /** @@ -5897,42 +4602,15 @@ class WaveService extends OrderBaseService { 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) { + const ownerSet = structureStoreSetMap.get(structureKey); + if (ownerSet instanceof Set && ownerSet.size > 1) { return false; } } @@ -5947,6 +4625,7 @@ class WaveService extends OrderBaseService { return false; } + const storeId = String(normalizedOrder.store_id || '').trim().toLowerCase(); if (normalizedStrategy.allowed_owners.length > 0 && !normalizedStrategy.allowed_owners.includes(storeId)) { return false; } @@ -6145,7 +4824,6 @@ class WaveService extends OrderBaseService { } const orderModel = await this.getOrderModel('pendingOrder', warehouseId); - const transaction = await this.ctx.model.transaction(); try { @@ -6301,10 +4979,6 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'singleFetchByIds', }); - this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, grabbedOrderIds, { - triggerScan: false, - source: 'singleFetchByIds', - }); return this.success('ok', { ids: normalizedIds, @@ -6358,37 +5032,6 @@ 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 { @@ -6536,10 +5179,6 @@ class WaveService extends OrderBaseService { warehouseId, scene: 'batchRemoveOrders', }); - this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, removedOrderIds, { - triggerScan: true, - source: 'batchRemoveOrders', - }); return this.success('ok', { ids: normalizedIds, @@ -6602,7 +5241,7 @@ class WaveService extends OrderBaseService { task_id: taskId, warehouse_id: Number(existingTask.warehouse_id || warehouseId), state: String(existingTask.state || 'submitted').trim() || 'submitted', - message: '批量移除异常订单任务已存在,请勿重复提交。', + message: 'Batch remove exception orders task already exists. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', accepted_at: existingTask.accepted_at || existingTask.submitted_at || new Date().toISOString(), }); } @@ -6651,7 +5290,7 @@ class WaveService extends OrderBaseService { status: 'success', task_id: taskId, warehouse_id: warehouseId, - message: '批量移除异常订单任务已提交。', + message: 'Batch remove exception orders submitted. Check progress with order.wave.batchRemoveExceptionOrdersTaskProgress', accepted_at: acceptedAt, }); } @@ -7291,7 +5930,6 @@ 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); @@ -7363,13 +6001,6 @@ 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 @@ -7413,12 +6044,6 @@ 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, @@ -9025,2710 +7650,6 @@ 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, - wave_prefix: '', - wave_prefix_source: '', - }; - - const wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ - warehouseId, - strategyType, - strategyRow, - }); - result.wave_prefix = wavePrefixResolution.wavePrefix; - result.wave_prefix_source = wavePrefixResolution.source; - - 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('团购策略未找到可创建波次的同结构分组'); - } - - for (const group of selectedGroups) { - const created = await this.createWaveBatchByOrderIdsInTransaction({ - warehouseId, - orderIds: group.order_ids, - waveType: 1, - wavePrefix: wavePrefixResolution.wavePrefix, - 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 createdWave = await this.createWaveBatchByOrderIdsInTransaction({ - warehouseId, - orderIds: limitedOrderIds, - waveType: 2, - wavePrefix: wavePrefixResolution.wavePrefix, - 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, - strategy_type: strategyType, - wave_prefix: result.wave_prefix, - wave_prefix_source: result.wave_prefix_source, - 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; - } - - /** - * 按策略直接抓取候选订单并创建波次(不创建拣货任务)。 - * - * 在一个事务内完成候选查询、分组与建波: - * - 团购策略(strategy_type=2):每个结构分组创建一个波次; - * - 散单策略(strategy_type=1):合并全部候选订单后创建一个散单波次。 - * - * @param {Object} params 执行参数。 - * @param {Object} params.plan 预处理计划。 - * @param {Object} [params.strategyRow={}] 策略行(可选,默认取 plan.strategy_row)。 - * @param {number|string} [params.waveBatchSource=0] 波次来源:0-普通波次 1-管理后台策略抓取 2-PDA策略抓取。 - * @return {Promise} 建波结果汇总。 - */ - async executeWaveStrategyDirectFetch(params = {}) { - const plan = this.isPlainObject(params && params.plan) ? params.plan : {}; - const strategyRow = this.isPlainObject(params && params.strategyRow) - ? params.strategyRow - : (this.isPlainObject(plan.strategy_row) ? plan.strategy_row : {}); - const waveBatchSourceInput = Number(params && 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 strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0); - const transaction = await this.ctx.model.transaction(); - - try { - 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 wavePrefixResolution = await this.resolveWaveStrategyFetchWavePrefix({ - warehouseId, - strategyType, - strategyRow, - }); - - const createdWaveIds = []; - const createdWaveNos = []; - const createdOrderIds = []; - - if (strategyType === 2) { - for (const group of groupedRows) { - const created = await this.createWaveBatchByOrderIdsInTransaction({ - warehouseId, - orderIds: group.order_ids, - waveType: 1, - wavePrefix: wavePrefixResolution.wavePrefix, - source: waveBatchSource, - transaction, - }); - createdWaveIds.push(created.waveId); - createdWaveNos.push(created.waveNo); - createdOrderIds.push(...created.selectedOrderIds); - } - } 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 createdWave = await this.createWaveBatchByOrderIdsInTransaction({ - warehouseId, - orderIds: mergedOrderIds, - waveType: 2, - wavePrefix: wavePrefixResolution.wavePrefix, - source: waveBatchSource, - transaction, - }); - createdWaveIds.push(createdWave.waveId); - createdWaveNos.push(createdWave.waveNo); - createdOrderIds.push(...createdWave.selectedOrderIds); - } else { - throw new Error(`不支持的策略类型: ${strategyType}`); - } - - const normalizedWaveIds = [ ...new Set(createdWaveIds) ].sort((a, b) => a - b); - const normalizedWaveNos = [ ...new Set(createdWaveNos.map(item => String(item || '').trim()).filter(Boolean)) ]; - const normalizedOrderIds = [ ...new Set(createdOrderIds) ].sort((a, b) => a - b); - - if (normalizedWaveIds.length <= 0 || normalizedOrderIds.length <= 0) { - throw new Error('按策略抓取建波失败:未生成有效波次或订单结果'); - } - - const result = { - wave_ids: normalizedWaveIds, - wave_nos: normalizedWaveNos, - order_ids: normalizedOrderIds, - created_wave_count: normalizedWaveIds.length, - created_order_count: normalizedOrderIds.length, - wave_prefix: wavePrefixResolution.wavePrefix, - wave_prefix_source: wavePrefixResolution.source, - candidate_count: candidateCount, - grouped_count: groupedRows.length, - strategy_type: strategyType, - }; - - await transaction.commit(); - - this.ctx.logger.info('[wave.executeWaveStrategyDirectFetch] 按策略直接建波完成', { - strategy_id: strategyId, - warehouse_id: warehouseId, - strategy_type: strategyType, - wave_prefix: result.wave_prefix, - wave_prefix_source: result.wave_prefix_source, - candidate_count: result.candidate_count, - grouped_count: result.grouped_count, - created_wave_count: result.created_wave_count, - created_order_count: result.created_order_count, - }); - - return result; - } catch (error) { - await transaction.rollback(); - throw error; - } - } - - /** - * 执行按策略抓取任务创建主流程。 - * - * 该方法在一个事务内完成任务主表、明细表、断点与日志的初始化写入。 - * - * @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: '建波失败,请重试', - warehouse_id: warehouseId, - strategy_id: strategyId, - source: 'admin', - plan, - }, - }, 400); - } - - try { - const directFetchResult = await this.executeWaveStrategyDirectFetch({ - plan, - waveBatchSource: 1, - }); - - this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', { - warehouseId, - strategyId, - strategyType: directFetchResult.strategy_type, - createdWaveCount: directFetchResult.created_wave_count, - createdOrderCount: directFetchResult.created_order_count, - }); - - return this.success('ok', { - status: 'success', - fetch_state: 1, - tip: '建波成功', - warehouse_id: warehouseId, - strategy_id: strategyId, - source: 'admin', - plan, - wave_ids: directFetchResult.wave_ids, - wave_nos: directFetchResult.wave_nos, - order_ids: directFetchResult.order_ids, - created_wave_count: directFetchResult.created_wave_count, - created_order_count: directFetchResult.created_order_count, - wave_prefix: directFetchResult.wave_prefix, - wave_prefix_source: directFetchResult.wave_prefix_source, - candidate_count: directFetchResult.candidate_count, - grouped_count: directFetchResult.grouped_count, - strategy_type: directFetchResult.strategy_type, - accepted_at: new Date().toISOString(), - }); - } catch (error) { - return this.fail(`按策略抓取建波失败: ${error.message}`, { - data: { - status: 'failed', - fetch_state: 2, - tip: '建波失败,请重试', - warehouse_id: warehouseId, - strategy_id: strategyId, - source: 'admin', - plan, - }, - }, 500); - } - } - /** * 兼容旧方法名 fetch,内部转调 groupFetch。 * diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 218f7ae..3195bf4 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -26,6 +26,273 @@ const SYS_PLATFORM_TO_PRINT_PLATFORM_MAP = Object.freeze({ }); class OrderPrintSystemService extends OrderBaseService { + /** + * 判断当前配置是否需要补查拣货明细。 + * + * 未配置时默认按类型5处理,因此也需要补查。 + * + * @param {Object} policyConfig 策略配置。 + * @return {boolean} 是否需要补查拣货明细。 + */ + shouldLoadPickingDetails(policyConfig = {}) { + const config = this.isPlainObject(policyConfig) ? policyConfig : {}; + const displayType = Object.prototype.hasOwnProperty.call(config, 'waybill_custom_display_type') + ? String(config.waybill_custom_display_type || '').trim() + : '5'; + + return [ '2', '3', '4', '5' ].includes(displayType); + } + + /** + * 归一化商品快照,兼容 JSON 字符串。 + * + * @param {*} rawSnapshot 原始商品快照。 + * @return {Object} 快照对象。 + */ + normalizeItemSnapshot(rawSnapshot) { + if (this.isPlainObject(rawSnapshot)) { + return rawSnapshot; + } + + if (typeof rawSnapshot === 'string') { + const text = rawSnapshot.trim(); + if (!text) { + return {}; + } + + try { + const parsed = JSON.parse(text); + return this.isPlainObject(parsed) ? parsed : {}; + } catch (error) { + return {}; + } + } + + return {}; + } + + /** + * 从候选字段中读取首个非空文本。 + * + * @param {Object} source 源对象。 + * @param {Array} keys 候选键。 + * @return {string} 首个非空文本。 + */ + getFirstNonEmptyFieldText(source, keys = []) { + if (!this.isPlainObject(source)) { + return ''; + } + + for (const key of keys) { + const value = source[key]; + if (value === undefined || value === null) { + continue; + } + + const text = String(value).trim(); + if (text) { + return text; + } + } + + return ''; + } + + /** + * 批量补查打印所需的拣货明细。 + * + * 优先使用 wms_picking.space_name,只有缺失时才查询库位表,减少额外 SQL。 + * + * @param {Array} orderRows 订单列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单ID到补齐后订单对象的映射。 + */ + async buildPrintOrderRowMapWithPicking(orderRows = [], warehouseId) { + const rows = Array.isArray(orderRows) ? orderRows : []; + const orderIds = Array.from(new Set(rows + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0))); + const resultMap = new Map(); + + if (orderIds.length === 0) { + return resultMap; + } + + const pickingModel = this.ctx.model && this.ctx.model.Picking; + if (!pickingModel || typeof pickingModel.findAll !== 'function') { + return resultMap; + } + + const pickingRows = await pickingModel.findAll({ + where: { + order_id: { + [Op.in]: orderIds, + }, + status: { + [Op.ne]: 'cancel', + }, + }, + attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status' ], + order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + + const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; + if (normalizedPickingRows.length === 0) { + return resultMap; + } + + const orderItemIds = Array.from(new Set(normalizedPickingRows + .map(row => Number(row && row.order_item_id || 0)) + .filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0))); + + const orderItemModelFactory = this.ctx.model && this.ctx.model.OrderItemsFactory; + const orderItemModel = orderItemModelFactory && typeof orderItemModelFactory.getCurrentModel === 'function' + ? await orderItemModelFactory.getCurrentModel(warehouseId) + : null; + + const orderItemRows = orderItemModel && typeof orderItemModel.findAll === 'function' && orderItemIds.length > 0 + ? await orderItemModel.findAll({ + where: { + id: { + [Op.in]: orderItemIds, + }, + }, + attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ], + raw: true, + }) + : []; + + const orderItemMap = new Map(); + for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) { + const orderItemId = Number(row && row.id || 0); + if (orderItemId > 0) { + orderItemMap.set(orderItemId, row); + } + } + + const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows + .filter(row => !String(row && row.space_name || '').trim()) + .map(row => Number(row && row.space_id || 0)) + .filter(spaceId => Number.isInteger(spaceId) && spaceId > 0))); + const locationModel = this.ctx.model && this.ctx.model.LocationSpace; + const locationRows = locationModel + && typeof locationModel.findAll === 'function' + && locationFallbackSpaceIds.length > 0 + ? await locationModel.findAll({ + where: { + id: { + [Op.in]: locationFallbackSpaceIds, + }, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode' ], + raw: true, + }) + : []; + const locationMap = new Map((Array.isArray(locationRows) ? locationRows : []) + .map(row => [ Number(row && row.id || 0), row ])); + + const pickingRowsByOrderId = new Map(); + for (const row of normalizedPickingRows) { + const orderId = Number(row && row.order_id || 0); + if (orderId <= 0) { + continue; + } + + const list = pickingRowsByOrderId.get(orderId) || []; + list.push(row); + pickingRowsByOrderId.set(orderId, list); + } + + for (const orderRow of rows) { + const orderId = Number(orderRow && orderRow.id || 0); + const pickingList = pickingRowsByOrderId.get(orderId) || []; + if (pickingList.length === 0) { + continue; + } + + const printItems = pickingList.map(pickingRow => { + const orderItemId = Number(pickingRow && pickingRow.order_item_id || 0); + const orderItemRow = orderItemMap.get(orderItemId) || {}; + const itemSnapshot = this.normalizeItemSnapshot(orderItemRow.item_snapshot); + const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {}; + const pickLocation = this.getFirstNonEmptyFieldText({ + space_name: pickingRow && pickingRow.space_name, + space_code: locationRow.space_code, + custom_name: locationRow.custom_name, + custom_barcode: locationRow.custom_barcode, + }, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]); + const itemName = this.getFirstNonEmptyFieldText({ + snapshot_item_name: itemSnapshot.item_name, + snapshot_name: itemSnapshot.name, + snapshot_title: itemSnapshot.title, + item_name: orderItemRow.item_name, + }, [ 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]); + const barcode = this.getFirstNonEmptyFieldText({ + barcode: itemSnapshot.barcode, + item_barcode: itemSnapshot.item_barcode, + bar_code: itemSnapshot.bar_code, + item_code: orderItemRow.item_code, + sku_code: itemSnapshot.sku_code, + sku: itemSnapshot.sku, + }, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]); + const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0); + + return { + order_item_id: orderItemId, + item_name: itemName, + barcode, + quantity: quantity > 0 ? quantity : 0, + pick_location: pickLocation, + }; + }).filter(item => { + return String(item.item_name || '').trim() + || String(item.barcode || '').trim() + || String(item.pick_location || '').trim(); + }); + + if (printItems.length === 0) { + continue; + } + + resultMap.set(orderId, { + ...orderRow, + items: JSON.stringify(printItems), + }); + } + + return resultMap; + } + + /** + * 归一化签约策略配置,兼容缓存中的字符串形态。 + * + * @param {*} rawPolicyConfig 原始策略配置。 + * @return {Object} 归一化后的策略配置对象。 + */ + normalizeContractPolicyConfig(rawPolicyConfig) { + if (this.isPlainObject(rawPolicyConfig)) { + return rawPolicyConfig; + } + + if (typeof rawPolicyConfig === 'string') { + const text = rawPolicyConfig.trim(); + if (!text) { + return {}; + } + + try { + const parsed = JSON.parse(text); + return this.isPlainObject(parsed) ? parsed : {}; + } catch (error) { + this.ctx.logger.warn('[orderPrint.normalizeContractPolicyConfig] policy_config 解析失败: %s', error.message); + } + } + + return {}; + } + /** * 获取波次打印数据。 * @@ -151,6 +418,17 @@ class OrderPrintSystemService extends OrderBaseService { this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows); const orderExpressMap = this.buildOrderExpressMap(orderExpressRows); const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId); + const pickingCandidateRows = validOrderRows.filter(orderRow => { + const storeId = Number(orderRow && orderRow.store_id || 0); + const policyConfig = policyConfigMap.get(storeId) || {}; + return this.shouldLoadPickingDetails(policyConfig); + }); + const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(orderIds, normalizedWarehouseId); + const waveIdsForCount = Array.from(new Set(Array.from(waveOrderIndexMap.values()) + .map(item => Number(item && item.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); const templateSampleCache = new Map(); const orderPrintList = []; @@ -161,13 +439,25 @@ class OrderPrintSystemService extends OrderBaseService { } const orderExpress = orderExpressMap.get(orderId) || {}; + const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; + const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; + const waveIdForCount = Number(waveOrderIndexInfo.wave_id || effectiveOrderRow.wave_id || 0); + const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); + const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); + const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); + const effectiveOrderRowWithWaveIndex = { + ...effectiveOrderRow, + wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0, + wave_index: waveIndex > 0 ? waveIndex : 0, + platforms_index: platformsIndex > 0 ? platformsIndex : 0, + }; const storeId = Number(orderRow && orderRow.store_id || 0); const policyConfig = policyConfigMap.get(storeId) || {}; - const platformCode = this.resolvePrintPlatformCode(orderRow, orderExpress); + const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress); const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache); orderPrintList.push(this.buildOrderPlatformPrintItem({ - orderRow, + orderRow: effectiveOrderRowWithWaveIndex, orderExpress, policyConfig, platformCode, @@ -363,6 +653,7 @@ class OrderPrintSystemService extends OrderBaseService { 'waybill_code', 'logistics_code', 'logistics_name', + 'logistics_interface_name', 'platform_code', 'warehouse_id', 'printinfo', @@ -382,6 +673,128 @@ class OrderPrintSystemService extends OrderBaseService { return Array.isArray(rows) ? rows : []; } + /** + * 按订单ID批量查询波次顺序信息。 + * + * 数据来源:wms_order_wave_index。 + * 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。 + * + * @param {Array} orderIds 订单ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 订单顺序映射。 + */ + async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId) { + const resultMap = new Map(); + const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + + if (normalizedOrderIds.length === 0) { + return resultMap; + } + + const queryMethod = this.ctx.model && this.ctx.model.query; + if (typeof queryMethod !== 'function') { + return resultMap; + } + + const querySql = ` + SELECT order_id, wave_id, wave_index, platforms_index + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `; + + try { + const rows = await queryMethod.call(this.ctx.model, querySql, { + replacements: { + warehouseId, + orderIds: normalizedOrderIds, + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const orderId = Number(row && row.order_id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + resultMap.set(orderId, { + wave_id: Number(row && row.wave_id || 0), + wave_index: Number(row && row.wave_index || 0), + platforms_index: Number(row && row.platforms_index || 0), + }); + } + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.queryWaveOrderIndexMapByOrderIds] 查询失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + return resultMap; + } + + /** + * 按波次ID批量查询波次总订单数。 + * + * 数据来源:wms_order_wave_index。 + * 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。 + * + * @param {Array} waveIds 波次ID数组。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} 波次ID到总订单数映射。 + */ + async queryWaveTotalOrderCountMap(waveIds = [], warehouseId) { + const resultMap = new Map(); + const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); + + if (normalizedWaveIds.length === 0) { + return resultMap; + } + + const queryMethod = this.ctx.model && this.ctx.model.query; + if (typeof queryMethod !== 'function') { + return resultMap; + } + + const querySql = ` + SELECT wave_id, COUNT(1) AS total_orders + FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + GROUP BY wave_id + `; + + try { + const rows = await queryMethod.call(this.ctx.model, querySql, { + replacements: { + warehouseId, + waveIds: normalizedWaveIds, + }, + type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, + }); + + for (const row of Array.isArray(rows) ? rows : []) { + const waveId = Number(row && row.wave_id || 0); + if (!Number.isInteger(waveId) || waveId <= 0) { + continue; + } + + const totalOrders = Number(row && row.total_orders || 0); + resultMap.set(waveId, totalOrders > 0 ? totalOrders : 0); + } + } catch (error) { + this.ctx.logger.warn( + `[orderPrint.queryWaveTotalOrderCountMap] 查询失败 warehouseId=${warehouseId} message=${error.message}` + ); + } + + return resultMap; + } + /** * 校验业务ID为1的运单号数据完整性。 * @@ -476,9 +889,7 @@ class OrderPrintSystemService extends OrderBaseService { await Promise.all(storeIds.map(async storeId => { try { const contractConfig = await storeWarehouseService.getContractConfig(warehouseId, storeId); - const policyConfig = this.isPlainObject(contractConfig && contractConfig.policy_config) - ? contractConfig.policy_config - : {}; + const policyConfig = this.normalizeContractPolicyConfig(contractConfig && contractConfig.policy_config); policyMap.set(storeId, policyConfig); } catch (error) { this.ctx.logger.warn( diff --git a/database/migrations/20260513113000-create-wms_order_wave_index.js b/database/migrations/20260513113000-create-wms_order_wave_index.js new file mode 100644 index 0000000..856bdd5 --- /dev/null +++ b/database/migrations/20260513113000-create-wms_order_wave_index.js @@ -0,0 +1,86 @@ +'use strict'; + +module.exports = { + /** + * 创建订单波次顺序副表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @returns {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.createTable('wms_order_wave_index', { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + comment: '主键ID', + }, + warehouse_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID', + }, + order_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单ID', + }, + wave_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '波次ID', + }, + wave_index: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在波次中的全局顺序', + }, + platforms_index: { + type: Sequelize.INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '订单在平台分组内顺序', + }, + create_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + comment: '订单波次顺序定位副表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'order_id' ], { + name: 'uk_warehouse_order', + unique: true, + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id' ], { + name: 'idx_warehouse_wave', + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id', 'wave_index' ], { + name: 'idx_warehouse_wave_index', + }); + await queryInterface.addIndex('wms_order_wave_index', [ 'warehouse_id', 'wave_id', 'platforms_index' ], { + name: 'idx_warehouse_wave_platform_index', + }); + }, + + /** + * 回滚删除订单波次顺序副表。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @returns {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('wms_order_wave_index'); + }, +}; diff --git a/test/app/service/systemMethods/order/wave.fetch.test.js b/test/app/service/systemMethods/order/wave.fetch.test.js index 147a3c2..393ab9f 100644 --- a/test/app/service/systemMethods/order/wave.fetch.test.js +++ b/test/app/service/systemMethods/order/wave.fetch.test.js @@ -444,4 +444,125 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { assert.ok(fallbackCall); assert.equal(fallbackCall.options.transaction, transaction); }); + + it('fetchSingleStructure 成功后应写入 wms_order_wave_index', async () => { + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() {}, + async rollback() {}, + }; + + const sqlCalls = []; + const orders = [ + { id: 301, wave_id: 0 }, + { id: 302, wave_id: 0 }, + ]; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + sqlCalls.push({ sql, options }); + if (sql.includes('INSERT INTO wms_wave_batch')) { + return [{ insertId: 900003 }, { insertId: 900003 }]; + } + if (sql.includes('SELECT wave_no')) { + return []; + } + if (sql.includes('UPDATE wms_wave_batch')) { + return [{ affectedRows: 1 }]; + } + if (sql.includes('DELETE FROM wms_wave_batch')) { + return [{ affectedRows: 1 }]; + } + if (sql.includes('DELETE FROM wms_order_wave_index')) { + return [{ affectedRows: 2 }]; + } + if (sql.includes('INSERT INTO wms_order_wave_index')) { + return [{ affectedRows: 2 }]; + } + return [[]]; + }, + }, + }; + + const service = new WaveService(ctx); + service.app.Sequelize = { + literal(value) { + return value; + }, + }; + service.batchCreateOrderOperationLogs = async () => 0; + service.getCurrentDatePart = () => '20260513'; + service.getNextWaveNoSequence = async () => 3; + + const model = { + async findAll(options = {}) { + const where = options.where || {}; + if (where.wave_id === 0) { + return orders + .filter(item => item.wave_id === 0) + .map(item => ({ id: item.id })); + } + if (where.wave_id === 900003) { + return orders + .filter(item => item.wave_id === 900003) + .map(item => ({ id: item.id })); + } + return []; + }, + async update(values = {}, options = {}) { + const where = options.where || {}; + const targetIds = (where.id && where.id[Op.in]) || []; + for (const item of orders) { + if (targetIds.includes(item.id) && item.wave_id === 0) { + item.wave_id = Number(values.wave_id || 0); + item.wave_no = String(values.wave_no || ''); + } + } + return [ targetIds.length ]; + }, + }; + + await service.fetchSingleStructure( + model, + { + item_detail_machine: 'token-c', + quantity: 2, + item_part_type: 'items_hash', + item_part: 'hash-c', + distinguish_express: false, + logistics_name: '', + item_snapshot_key: '', + }, + 100000, + 'B', + 1, + { maxFetchQuantity: 2 } + ); + + const deleteCall = sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.ok(deleteCall, '应触发 DELETE FROM wms_order_wave_index'); + + const insertCall = sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(insertCall, '应触发 INSERT INTO wms_order_wave_index'); + }); }); diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index fce0acb..867b231 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -63,6 +63,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' printinfo: 'ENC_FROM_DB', signature: 'SIG_FROM_DB', encryptprintinfo: 'KEY_FROM_DB', + logistics_name: '顺丰', + logistics_interface_name: '申通快递', }, policyConfig: { province_name: '浙江省', @@ -124,7 +126,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' const customDataContent = result.print_data.contents.find(content => content && content.customData); assert.ok(customDataContent); assert.equal(customDataContent.templateURL, 'http://www.ye4s.com/mb/kuaishou.xml'); - assert.ok(customDataContent.customData.productInfo.includes('商品总数 【2】')); + assert.ok(customDataContent.customData.productInfo.includes('W010 申通快递 商品数量【2】')); assert.ok(customDataContent.customData.productInfo.includes('E2区02-04-02 化妆品 6973348850399 【2】')); }); @@ -151,6 +153,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' waybill_code: ' WB201 ', printinfo: ' ENC_FROM_DB_PDD ', signature: ' SIG_FROM_DB_PDD ', + logistics_name: '中通', + logistics_interface_name: '顺丰空运', }, policyConfig: { province_name: '广东省', @@ -215,10 +219,466 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.ok(customContent); assert.equal(customContent.templateURL, 'http://www.ye4s.com/mb/pdd.xml'); assert.ok(customContent.data.list[0].text.includes('\r')); - assert.ok(customContent.data.list[0].text.includes('商品总数 【1】')); + assert.ok(customContent.data.list[0].text.includes('W020 顺丰空运 商品数量【1】')); assert.ok(customContent.data.list[0].text.includes('A1-01-01 90123 【1】')); }); + it('should build custom text when order items is wrapped object string', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 202, + wave_id: 21, + wave_no: 'W021', + delivery_order_code: 'DO202', + store_id: 1, + warehouse_id: 100000, + items: JSON.stringify({ + items: [ + { + pick_location: 'C1-01-01', + barcode: '9988776655443', + quantity: 3, + }, + ], + }), + }, + orderExpress: { + waybill_code: 'WB202', + printinfo: 'ENC_202', + signature: 'SIG_202', + logistics_name: '圆通', + }, + policyConfig: { + waybill_custom_display_type: '3', + sender_name: '张三', + sender_tel: '13800000000', + province_name: '浙江省', + city_name: '杭州市', + district_name: '西湖区', + address: '文三路 1 号', + }, + platformCode: 'pdd', + templateSample: { + cmd: 'print', + requestID: 'REQ-202', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: { + city: '', + detail: '', + district: '', + province: '', + }, + mobile: '', + name: '', + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + }, + ], + documentID: 'DOC-202', + }, + ], + }, + }, + }); + + const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); + assert.ok(customContent); + assert.ok(customContent.data.list[0].text.includes('W021 圆通 商品数量【3】')); + assert.ok(customContent.data.list[0].text.includes('C1-01-01 9988776655443 【3】')); + }); + + it('should parse string policy_config in getPolicyConfigMapByStore', async () => { + const service = createOrderPrintServiceHarness(); + service.ctx.service.systems.storeWarehouse.getContractConfig = async () => ({ + policy_config: JSON.stringify({ + waybill_custom_display_type: '3', + sender_name: '赵六', + }), + }); + + const policyMap = await service.getPolicyConfigMapByStore([ + { store_id: 9 }, + ], 100000); + + const storePolicy = policyMap.get(9) || {}; + assert.equal(storePolicy.waybill_custom_display_type, '3'); + assert.equal(storePolicy.sender_name, '赵六'); + }); + + it('should default to literal compose when waybill display type is missing', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 203, + wave_id: 22, + wave_no: 'W022', + delivery_order_code: 'DO203', + store_id: 1, + warehouse_id: 100000, + items: JSON.stringify([ + { + item_name: '皮带黑色', + pick_location: 'E2区08-05-02', + barcode: '665835404213', + quantity: 1, + }, + ]), + }, + orderExpress: { + waybill_code: 'WB203', + printinfo: 'ENC_203', + signature: 'SIG_203', + logistics_name: '韵达', + }, + policyConfig: { + province_name: '广东省', + city_name: '广州市', + district_name: '白云区', + address: '良沙二路32号', + sender_name: '刘付明仁', + sender_tel: '18022440198', + }, + platformCode: 'pdd', + templateSample: { + cmd: 'print', + requestID: 'REQ-203', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: { + city: '', + detail: '', + district: '', + province: '', + }, + mobile: '', + name: '', + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + }, + ], + documentID: 'DOC-203', + }, + ], + }, + }, + }); + + const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); + assert.ok(customContent); + assert.ok(customContent.data.list[0].text.includes('W022 韵达 商品数量【1】')); + assert.ok(customContent.data.list[0].text.includes('E2区08-05-02 皮带黑色 665835404213 【1】')); + }); + + it('should keep header line when item details are unavailable', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 204, + wave_id: 23, + wave_no: 'W023', + delivery_order_code: 'DO204', + store_id: 1, + warehouse_id: 100000, + items: '', + items_count: 2, + }, + orderExpress: { + waybill_code: 'WB204', + printinfo: 'ENC_204', + signature: 'SIG_204', + logistics_name: '中通', + }, + policyConfig: { + waybill_custom_display_type: '5', + province_name: '广东省', + city_name: '广州市', + district_name: '白云区', + address: '良沙二路32号', + sender_name: '刘付明仁', + sender_tel: '18022440198', + }, + platformCode: 'pdd', + templateSample: { + cmd: 'print', + requestID: 'REQ-204', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: { + city: '', + detail: '', + district: '', + province: '', + }, + mobile: '', + name: '', + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + }, + ], + documentID: 'DOC-204', + }, + ], + }, + }, + }); + + const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); + assert.ok(customContent); + assert.equal(customContent.data.list[0].text, 'W023 中通 商品数量【2】\r'); + }); + + it('should render detail lines from non-json string items', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 205, + wave_id: 24, + wave_no: 'W024', + delivery_order_code: 'DO205', + store_id: 1, + warehouse_id: 100000, + items: '皮带黑色*1|皮带金色*2', + items_count: 2, + }, + orderExpress: { + waybill_code: 'WB205', + printinfo: 'ENC_205', + signature: 'SIG_205', + logistics_name: '申通快递', + }, + policyConfig: { + waybill_custom_display_type: '2', + province_name: '广东省', + city_name: '广州市', + district_name: '白云区', + address: '良沙二路32号', + sender_name: '刘付明仁', + sender_tel: '18022440198', + }, + platformCode: 'kuaishou', + templateSample: { + cmd: 'print', + requestID: 'REQ-205', + version: '1.0', + task: { + documents: [ + { + contents: [ + { + encryptedData: '', + signature: '', + key: '', + templateURL: 'https://example.com/kuaishou.xml', + }, + { + templateURL: 'http://www.ye4s.com/mb/kuaishou.xml', + customData: { + productInfo: '', + }, + }, + ], + }, + ], + }, + }, + }); + + const customDataContent = result.print_data.contents.find(content => content && content.customData); + assert.ok(customDataContent); + assert.ok(customDataContent.customData.productInfo.includes('W024 申通快递 商品数量【3】')); + assert.ok(customDataContent.customData.productInfo.includes('皮带黑色 【1】')); + assert.ok(customDataContent.customData.productInfo.includes('皮带金色 【2】')); + }); + + it('should render display type 4 as pick location + last 5 barcode + qty per line', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 206, + wave_id: 25, + wave_no: 'W025', + delivery_order_code: 'DO206', + store_id: 1, + warehouse_id: 100000, + items: 'E2区08-05-02 皮带黑色;665835404213 【1】 0|E2区08-04-02 皮带金色;600507 【1】 0', + items_count: 2, + }, + orderExpress: { + waybill_code: 'WB206', + printinfo: 'ENC_206', + signature: 'SIG_206', + logistics_name: '顺丰空运', + }, + policyConfig: { + waybill_custom_display_type: '4', + province_name: '广东省', + city_name: '广州市', + district_name: '白云区', + address: '良沙二路32号', + sender_name: '刘付明仁', + sender_tel: '18022440198', + }, + platformCode: 'pdd', + templateSample: { + cmd: 'print', + requestID: 'REQ-206', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: { + city: '', + detail: '', + district: '', + province: '', + }, + mobile: '', + name: '', + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + }, + ], + documentID: 'DOC-206', + }, + ], + }, + }, + }); + + const customContent = result.print_data.contents.find(content => content && content.data && Array.isArray(content.data.list)); + assert.ok(customContent); + const text = customContent.data.list[0].text; + assert.ok(text.includes('W025 顺丰空运 商品数量【2】')); + assert.ok(text.includes('E2区08-05-02 04213 【1】')); + assert.ok(text.includes('E2区08-04-02 00507 【1】')); + assert.ok(!text.includes('\r【1】\r')); + }); + it('should query order_express with kuaishou encrypted payload columns', async () => { const service = createOrderPrintServiceHarness(); let capturedAttributes = []; @@ -236,6 +696,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.ok(capturedAttributes.includes('printinfo')); assert.ok(capturedAttributes.includes('signature')); assert.ok(capturedAttributes.includes('encryptprintinfo')); + assert.ok(capturedAttributes.includes('logistics_interface_name')); assert.equal(capturedWhere.business_key, 1); }); @@ -448,4 +909,292 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' filtered_wave_ids: [], }); }); + + it('should batch load picking locations from wms_picking for print items', async () => { + const service = createOrderPrintServiceHarness(); + const currentOrderItemsModel = { + async findAll() { + return [ + { + id: 5001, + order_id: 301, + item_code: 'SKU-301', + item_name: '商品301', + plan_qty: 1, + item_snapshot: { + barcode: '9988776655443', + }, + }, + ]; + }, + }; + + service.ctx.model.Picking = { + async findAll() { + return [ + { + id: 1, + order_id: 301, + order_item_id: 5001, + quantity: 1, + space_id: 9001, + space_name: 'E2区08-05-02', + status: 'pending', + }, + ]; + }, + }; + service.ctx.model.OrderItemsFactory = { + async getCurrentModel() { + return currentOrderItemsModel; + }, + }; + service.ctx.model.LocationSpace = { + async findAll() { + throw new Error('space_name 已存在时不应查询库位表'); + }, + }; + + service.queryWavesByIds = async () => ([ + { wave_id: 30, wave_no: 'W030' }, + ]); + service.queryOrdersByWaveIds = async () => ([ + { + id: 301, + wave_id: 30, + wave_no: 'W030', + warehouse_id: 100000, + store_id: 1, + delivery_order_code: 'O301', + post_status: 'fin', + sys_platform_code: 'pdd', + items: '', + }, + ]); + service.filterFullyAssignedExpressWaves = () => ({ + validWaveIds: [ 30 ], + filteredWaveIds: [], + }); + service.queryOrderExpressByOrderIds = async () => ([ + { + order_id: 301, + business_key: 1, + waybill_code: 'WB301', + logistics_name: '顺丰空运', + }, + ]); + service.queryWaveOrderIndexMapByOrderIds = async () => new Map([ + [ 301, { + wave_id: 30, + wave_index: 12, + platforms_index: 3, + } ], + ]); + service.queryWaveTotalOrderCountMap = async () => new Map([ + [ 30, 66 ], + ]); + service.getPolicyConfigMapByStore = async () => new Map([ + [ 1, { + waybill_custom_display_type: '4', + } ], + ]); + service.loadTemplateSampleByPlatform = () => ({ + cmd: 'print', + requestID: 'REQ-301', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: {}, + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + }, + ], + documentID: 'DOC-301', + }, + ], + }, + }); + + const result = await service.getWavePlatformPrintData({ + waveIds: [ 30 ], + warehouseId: 100000, + }); + + const printText = result.waveGroups[0].platforms[0].orders[0].contents[1].data.list[0].text; + assert.ok(printText.includes('【66】W030_12_3')); + assert.ok(printText.includes('E2区08-05-02 55443 【1】')); + }); + + it('should prefer snapshot item_name for display type 2 in getWavePlatformPrintData', async () => { + const service = createOrderPrintServiceHarness(); + const currentOrderItemsModel = { + async findAll() { + return [ + { + id: 6001, + order_id: 302, + item_code: 'SKU-302', + item_name: '旧商品名-不应展示', + plan_qty: 1, + item_snapshot: { + item_name: '快照商品名-应展示', + }, + }, + ]; + }, + }; + + service.ctx.model.Picking = { + async findAll() { + return [ + { + id: 2, + order_id: 302, + order_item_id: 6001, + quantity: 1, + space_id: 9101, + space_name: 'A1区01-01-01', + status: 'pending', + }, + ]; + }, + }; + service.ctx.model.OrderItemsFactory = { + async getCurrentModel() { + return currentOrderItemsModel; + }, + }; + service.ctx.model.LocationSpace = { + async findAll() { + throw new Error('space_name 已存在时不应查询库位表'); + }, + }; + + service.queryWavesByIds = async () => ([ + { wave_id: 31, wave_no: 'W031' }, + ]); + service.queryOrdersByWaveIds = async () => ([ + { + id: 302, + wave_id: 31, + wave_no: 'W031', + warehouse_id: 100000, + store_id: 1, + delivery_order_code: 'O302', + post_status: 'fin', + sys_platform_code: 'pdd', + items: '', + }, + ]); + service.filterFullyAssignedExpressWaves = () => ({ + validWaveIds: [ 31 ], + filteredWaveIds: [], + }); + service.queryOrderExpressByOrderIds = async () => ([ + { + order_id: 302, + business_key: 1, + waybill_code: 'WB302', + logistics_name: '圆通', + }, + ]); + service.queryWaveOrderIndexMapByOrderIds = async () => new Map([ + [ 302, { + wave_id: 31, + wave_index: 1, + platforms_index: 1, + } ], + ]); + service.queryWaveTotalOrderCountMap = async () => new Map([ + [ 31, 10 ], + ]); + service.getPolicyConfigMapByStore = async () => new Map([ + [ 1, { + waybill_custom_display_type: '2', + } ], + ]); + service.loadTemplateSampleByPlatform = () => ({ + cmd: 'print', + requestID: 'REQ-302', + version: '11', + task: { + documents: [ + { + contents: [ + { + addData: { + sender: { + address: {}, + }, + }, + encryptedData: '', + signature: '', + templateUrl: 'https://file-link.pinduoduo.com/sto_one', + userid: '', + ver: '11', + }, + { + templateURL: 'http://www.ye4s.com/mb/pdd.xml', + data: { + height: 240, + list: [ + { + fontSize: 28, + left: 2.08, + text: '', + top: 2.08, + width: 550, + }, + ], + waterdata: { + text: '', + }, + width: 560, + }, + }, + ], + documentID: 'DOC-302', + }, + ], + }, + }); + + const result = await service.getWavePlatformPrintData({ + waveIds: [ 31 ], + warehouseId: 100000, + }); + + const printText = result.waveGroups[0].platforms[0].orders[0].contents[1].data.list[0].text; + assert.ok(printText.includes('快照商品名-应展示')); + assert.ok(!printText.includes('旧商品名-不应展示')); + }); });