'use strict'; const MainService = require('../main'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; const ORDER_STEP_EXCEPTION = 3; const ALLOCATION_LOG_SAMPLE_LIMIT = 20; /** * 规范化块状日志的输出值。 * * @param {unknown} payload 日志载荷。 * @param {WeakSet} [seen] 循环引用跟踪集。 * @return {unknown} 规范化后的值。 */ function normalizeAllocationLogPayload(payload, seen = new WeakSet()) { if (payload instanceof Error) { return { name: payload.name, message: payload.message, stack: payload.stack, }; } if (payload === null || typeof payload !== 'object') { if (typeof payload === 'bigint') { return payload.toString(); } return payload; } if (payload instanceof Date) { return payload.toISOString(); } if (seen.has(payload)) { return '[Circular]'; } seen.add(payload); if (Array.isArray(payload)) { return payload.map(item => normalizeAllocationLogPayload(item, seen)); } const normalized = {}; for (const [ key, value ] of Object.entries(payload)) { normalized[key] = normalizeAllocationLogPayload(value, seen); } return normalized; } /** * 格式化块状日志文本。 * * @param {string} title 日志标题。 * @param {unknown} payload 日志载荷。 * @return {string} 块状日志文本。 */ function formatAllocationLogBlock(title, payload) { const normalizedPayload = normalizeAllocationLogPayload(payload); let payloadText; if (typeof normalizedPayload === 'string') { payloadText = normalizedPayload; } else { try { const stringifiedPayload = JSON.stringify(normalizedPayload, null, 2); payloadText = stringifiedPayload === undefined ? String(payload) : stringifiedPayload; } catch (error) { payloadText = JSON.stringify({ message: error.message, originalPayload: String(payload), }, null, 2); } } return [ '==============', `时间:${Date.now()}`, String(title || ''), payloadText, '==============', ].join('\n'); } /** * 输出块状文本日志。 * * @param {string} title 日志标题。 * @param {unknown} payload 日志载荷。 * @return {void} */ function writeAllocationTextLog(title, payload) { process.stdout.write(`${formatAllocationLogBlock(title, payload)}\n`); } /** * 生成数组日志摘要,避免输出全量数据。 * * @param {Array} list 原始数组。 * @param {number} [limit=ALLOCATION_LOG_SAMPLE_LIMIT] 采样数量上限。 * @return {{count: number, sample: Array}} 摘要信息。 */ function summarizeArrayForLog(list, limit = ALLOCATION_LOG_SAMPLE_LIMIT) { const normalizedList = Array.isArray(list) ? list : []; return { count: normalizedList.length, sample: normalizedList.slice(0, limit), }; } /** * 将输入值规范化为布尔值。 * * @param {unknown} value 待转换的值。 * @param {boolean} [defaultValue=false] 空值时的默认布尔值。 * @return {boolean} 是否为真。 */ function normalizeBooleanFlag(value, defaultValue = false) { if (value === undefined || value === null || value === '') { return defaultValue; } if (typeof value === 'boolean') { return value; } if (typeof value === 'number') { return value === 1; } if (typeof value === 'string') { return [ '1', 'Y', 'YES', 'TRUE', 'ON' ].includes(value.trim().toUpperCase()); } return false; } /** * 将输入值转换为有限数字。 * * @param {unknown} value 待转换的值。 * @param {number} [defaultValue=0] 默认值。 * @return {number} 转换后的数字。 */ function toNumber(value, defaultValue = 0) { const normalized = Number(value); return Number.isFinite(normalized) ? normalized : defaultValue; } /** * 将模型记录转换为普通对象。 * * @param {unknown} record 模型记录。 * @return {Object|null} 普通对象。 */ function toPlainRecord(record) { if (!record) { return null; } if (typeof record.get === 'function') { return record.get({ plain: true }); } return record; } /** * 解析日期值并返回时间戳。 * * @param {unknown} value 日期值。 * @return {number} 时间戳或 Number.MAX_SAFE_INTEGER。 */ function toTimeValue(value) { if (!value) { return Number.MAX_SAFE_INTEGER; } const timeValue = new Date(value).getTime(); return Number.isFinite(timeValue) ? timeValue : Number.MAX_SAFE_INTEGER; } /** * 生成储位库存摘要。 * * @param {number|string} stockId 库存 ID。 * @param {Array} storageRows 储位库存列表。 * @return {Object} 储位库存摘要。 */ function summarizeStorageRows(stockId, storageRows = []) { const rows = Array.isArray(storageRows) ? storageRows : []; const firstRow = rows[0] || {}; return { stock_id: Number(stockId) || 0, rowCount: rows.length, availableQuantityTotal: rows.reduce((sum, row) => sum + toNumber(row.available_quantity, 0), 0), enabledCount: rows.filter(row => normalizeBooleanFlag(row.is_enabled, true)).length, firstStorageId: Number(firstRow.id) || 0, firstSpaceId: Number(firstRow.space_id) || 0, }; } /** * 对可分配库存按优先级排序。 * * @param {Object} left 左侧库存。 * @param {Object} right 右侧库存。 * @return {number} 排序结果。 */ function compareStorageRows(left, right) { const leftHasProductionDate = Boolean(left.production_date); const rightHasProductionDate = Boolean(right.production_date); if (leftHasProductionDate !== rightHasProductionDate) { return leftHasProductionDate ? -1 : 1; } if (leftHasProductionDate && rightHasProductionDate) { const productionDiff = toTimeValue(left.production_date) - toTimeValue(right.production_date); if (productionDiff !== 0) { return productionDiff; } } const inboundDiff = toTimeValue(left.inbound_time) - toTimeValue(right.inbound_time); if (inboundDiff !== 0) { return inboundDiff; } return toNumber(left.id, 0) - toNumber(right.id, 0); } /** * 生成库位类型限制导致的缺货原因文本。 * * @param {Object} diagnostics 库位类型限制统计。 * @param {number} diagnostics.totalRows 原始库位行数。 * @param {number} diagnostics.allowAllocationFilteredRows allow_allocation 过滤行数。 * @param {number} diagnostics.isActiveFilteredRows is_active 过滤行数。 * @return {string} 缺货原因文本。 */ function buildLocationTypeRestrictionReason(diagnostics = {}) { const totalRows = toNumber(diagnostics.totalRows, 0); const allowAllocationFilteredRows = toNumber(diagnostics.allowAllocationFilteredRows, 0); const isActiveFilteredRows = toNumber(diagnostics.isActiveFilteredRows, 0); if (totalRows <= 0) { return ''; } const reasonParts = []; if (allowAllocationFilteredRows > 0) { reasonParts.push('库位类型不可分配'); } if (isActiveFilteredRows > 0) { reasonParts.push('库位类型未启用'); } return reasonParts.join('/'); } /** * 诊断库存是否因库位类型限制导致无可分配库位。 * * @param {Object} options 参数。 * @param {Object} options.ctx 请求上下文。 * @param {Object} options.Op Sequelize 操作符集合。 * @param {number} options.warehouseId 仓库 ID。 * @param {number} options.stockId 库存 ID。 * @param {Object} options.transaction 事务对象。 * @param {Map} options.cache 诊断缓存。 * @return {Promise} 诊断结果。 */ async function diagnoseStorageTypeRestriction(options = {}) { const { ctx, Op, warehouseId, stockId, transaction, cache, } = options; const normalizedStockId = toNumber(stockId, 0); if (normalizedStockId <= 0 || !ctx || !Op) { return { totalRows: 0, allowAllocationFilteredRows: 0, isActiveFilteredRows: 0, reason: '', }; } if (cache instanceof Map && cache.has(normalizedStockId)) { return cache.get(normalizedStockId); } const rawStorageRows = await ctx.model.Storage.findAll({ where: { warehouse_id: warehouseId, stock_id: normalizedStockId, is_enabled: 1, delete_at: null, available_quantity: { [Op.gt]: 0, }, }, include: [ { model: ctx.model.LocationSpace, as: 'space', required: true, attributes: [ 'id' ], include: [ { model: ctx.model.LocationType, as: 'locationType', required: true, attributes: [ 'id', 'allow_allocation', 'is_active' ], }, ], }, ], transaction, }); let allowAllocationFilteredRows = 0; let isActiveFilteredRows = 0; for (const storageRow of Array.isArray(rawStorageRows) ? rawStorageRows : []) { const plainStorage = toPlainRecord(storageRow) || {}; const space = toPlainRecord(plainStorage.space) || {}; const locationType = toPlainRecord(space.locationType) || {}; if (toNumber(locationType.allow_allocation, 0) !== 1) { allowAllocationFilteredRows += 1; } if (toNumber(locationType.is_active, 0) !== 1) { isActiveFilteredRows += 1; } } const diagnostics = { totalRows: Array.isArray(rawStorageRows) ? rawStorageRows.length : 0, allowAllocationFilteredRows, isActiveFilteredRows, reason: '', }; diagnostics.reason = buildLocationTypeRestrictionReason(diagnostics); if (cache instanceof Map) { cache.set(normalizedStockId, diagnostics); } return diagnostics; } /** * 生成库存不足提示文本。 * * @param {Array} shortageItems 缺货条目。 * @return {string} 提示文本。 */ function buildShortageMessage(shortageItems = []) { const parts = shortageItems .filter(item => item && Number(item.stock_id) > 0) .map(item => { const shortageReason = String(item.reason || '').trim(); const reasonText = shortageReason ? `,原因:${shortageReason}` : ''; return `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}${reasonText}`; }); return parts.length > 0 ? `库存不足:${parts.join('|')}` : ''; } /** * 规范化订单 ID 列表。 * * @param {Object} data 请求体。 * @return {number[]} 订单 ID 列表。 */ function normalizeOrderIds(data = {}) { const requestData = data && typeof data === 'object' ? data : {}; const rawValues = []; if (Array.isArray(requestData.order_ids)) { rawValues.push(...requestData.order_ids); } else if (Array.isArray(requestData.orderIds)) { rawValues.push(...requestData.orderIds); } else if (Array.isArray(requestData.ids)) { rawValues.push(...requestData.ids); } else if (typeof requestData.order_ids === 'string') { rawValues.push(...requestData.order_ids.split(',')); } else if (typeof requestData.orderIds === 'string') { rawValues.push(...requestData.orderIds.split(',')); } else if (typeof requestData.ids === 'string') { rawValues.push(...requestData.ids.split(',')); } else if (requestData.order_ids !== undefined && requestData.order_ids !== null && requestData.order_ids !== '') { rawValues.push(requestData.order_ids); } else if (requestData.orderIds !== undefined && requestData.orderIds !== null && requestData.orderIds !== '') { rawValues.push(requestData.orderIds); } else if (requestData.ids !== undefined && requestData.ids !== null && requestData.ids !== '') { rawValues.push(requestData.ids); } else if (requestData.order_id !== undefined && requestData.order_id !== null && requestData.order_id !== '') { rawValues.push(requestData.order_id); } else if (requestData.orderId !== undefined && requestData.orderId !== null && requestData.orderId !== '') { rawValues.push(requestData.orderId); } else if (requestData.id !== undefined && requestData.id !== null && requestData.id !== '') { rawValues.push(requestData.id); } const orderIds = rawValues .map(value => Number(String(value).trim())) .filter(value => Number.isFinite(value) && value > 0); return Array.from(new Set(orderIds)); } /** * 规范化取消储位分配相关入参。 * * 仅保留订单 ID 归一化结果,不再接收或透传存储位开关字段。 * * @param {Object} data 请求体。 * @return {{ orderIds: number[], forbiddenWarehouseKeys: string[] }} 规范化结果。 */ function normalizeCancelStorageAllocationRequest(data = {}) { const requestData = data && typeof data === 'object' ? data : {}; const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ] .filter(key => Object.prototype.hasOwnProperty.call(requestData, key)); return { orderIds: normalizeOrderIds(requestData), forbiddenWarehouseKeys, }; } /** * 订单储位分配公共服务。 * 负责订单、库存、库位的分配编排,并写入 wms_picking。 */ class OrderStorageAllocationService extends MainService { /** * 按订单批量分配储位。 * * 入参支持以下字段: * - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage` * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` * * 分配规则: * - 先过滤掉已经完成储位分配的订单 * - 允许时优先使用存储储位,再使用分拣储位 * - FIFO 先按生产日期,再按入库时间 * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 * * @param {Object} data 请求体。 * @return {Promise} 分配结果。 */ async allocatePicking(data = {}) { const { ctx, app } = this; const requestData = this.isPlainObject(data) ? data : {}; const progressCallback = typeof requestData.progress_callback === 'function' ? requestData.progress_callback : null; const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); const orderIds = normalizeOrderIds(requestData); const allowStorageLocation = normalizeBooleanFlag( requestData.allow_storage_location ?? requestData.allowStorageLocation ?? requestData.is_allow_storage ?? requestData.isAllowStorage ); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 入口入参', { requestData, warehouseId, orderIds, allowStorageLocation, }); if (warehouseId <= 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 缺少仓库上下文,直接返回', { requestData, warehouseId, orderIds, allowStorageLocation, }); return { code: 400, message: '缺少仓库上下文', data: null, }; } if (orderIds.length === 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单ID为空,直接返回', { requestData, warehouseId, orderIds, allowStorageLocation, }); return { code: 400, message: '订单ID不能为空', data: null, }; } const transaction = await ctx.model.transaction(); const { Op } = app.Sequelize; const now = new Date(); const notifyProgress = async payload => { if (typeof progressCallback !== 'function') { return; } try { await progressCallback(payload); } catch (error) { if (ctx.logger && typeof ctx.logger.warn === 'function') { ctx.logger.warn('[OrderStorageAllocationService.allocatePicking] 上报进度回调失败: %s', error && error.message ? error.message : error); } } }; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务已创建', { warehouseId, orderIds, allowStorageLocation, }); try { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 模型加载完成', { warehouseId, hasOrderModel: Boolean(orderModel), hasOrderItemModel: Boolean(orderItemModel), hasPickingModel: Boolean(pickingModel), }); if (!pickingModel || typeof pickingModel.bulkCreate !== 'function') { throw new Error('wms_picking 模型不可用'); } const orderRows = await orderModel.findAll({ where: { id: { [Op.in]: orderIds, }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单主表查询完成', { warehouseId, requestedOrderCount: orderIds.length, requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderRowCount: Array.isArray(orderRows) ? orderRows.length : 0, }); const orderMap = new Map(); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { const plainOrder = toPlainRecord(orderRow); if (!plainOrder || !Number(plainOrder.id)) { continue; } orderMap.set(Number(plainOrder.id), plainOrder); } const pendingOrderIds = []; const skippedOrders = []; for (const orderId of orderIds) { const orderRow = orderMap.get(orderId); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单前', { orderId, hasOrderRow: Boolean(orderRow), storageStatus: orderRow ? orderRow.storage_status : null, }); if (!orderRow) { skippedOrders.push({ order_id: orderId, status: 'skipped', skipped_reason: 'not_found', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { orderId, skippedReason: 'not_found', }); continue; } if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) { skippedOrders.push({ order_id: orderId, status: 'skipped', storage_status: orderRow.storage_status, skipped_reason: 'already_allocated', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { orderId, skippedReason: 'already_allocated', }); continue; } pendingOrderIds.push(orderId); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', { orderId, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单过滤完成', { requestedOrderCount: orderIds.length, pendingOrderCount: pendingOrderIds.length, skippedOrderCount: skippedOrders.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); if (pendingOrderIds.length === 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无需分配的订单,准备提交事务', { warehouseId, skippedOrderCount: skippedOrders.length, skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); await transaction.commit(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { warehouseId, requestedOrderCount: orderIds.length, pendingOrderCount: pendingOrderIds.length, skippedOrderCount: skippedOrders.length, requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); return { code: 200, message: '没有需要分配的订单', data: { warehouse_id: warehouseId, allow_storage_location: allowStorageLocation, requested_order_ids: orderIds, pending_order_ids: [], skipped_orders: skippedOrders, orders: skippedOrders, picking_count: 0, }, }; } const orderItemRows = await orderItemModel.findAll({ where: { order_id: { [Op.in]: pendingOrderIds, }, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细查询完成', { warehouseId, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderItemRowCount: Array.isArray(orderItemRows) ? orderItemRows.length : 0, }); const orderItemsByOrderId = new Map(); const stockIdSet = new Set(); for (const orderItemRow of Array.isArray(orderItemRows) ? orderItemRows : []) { const plainItem = toPlainRecord(orderItemRow); if (!plainItem || !Number(plainItem.order_id)) { continue; } const orderId = Number(plainItem.order_id); const orderItems = orderItemsByOrderId.get(orderId) || []; orderItems.push(plainItem); orderItemsByOrderId.set(orderId, orderItems); const stockId = Number(plainItem.stock_id || 0); if (stockId > 0) { stockIdSet.add(stockId); } } const stockIds = Array.from(stockIdSet); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细归集完成', { warehouseId, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), stockIdCount: stockIds.length, stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); if (stockIds.length > 0) { await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: stockIds, }, warehouse_id: warehouseId, is_valid: 'Y', deleted_at: null, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录预锁定完成', { warehouseId, stockIdCount: stockIds.length, stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); const storageRows = stockIds.length > 0 ? await ctx.model.Storage.findAll({ where: { warehouse_id: warehouseId, stock_id: { [Op.in]: stockIds, }, is_enabled: 1, delete_at: null, available_quantity: { [Op.gt]: 0, }, }, include: [ { model: ctx.model.LocationSpace, as: 'space', required: true, attributes: [ 'id', 'space_code', 'custom_name', 'pick_sequence', 'pick_priority' ], include: [ { model: ctx.model.LocationType, as: 'locationType', required: true, attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ], where: { allow_allocation: 1, is_active: 1, }, }, ], }, ], transaction, lock: transaction.LOCK.UPDATE, order: [[ 'id', 'ASC' ]], }) : []; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 可分配库存查询完成', { warehouseId, stockIdCount: stockIds.length, stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0, }); const storageRowsByStockId = new Map(); for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { const plainStorage = toPlainRecord(storageRow); if (!plainStorage || !Number(plainStorage.id) || !Number(plainStorage.stock_id)) { continue; } const space = toPlainRecord(plainStorage.space) || {}; const locationType = toPlainRecord(space.locationType) || {}; const normalizedStorage = { ...plainStorage, quantity: toNumber(plainStorage.quantity, 0), locked_quantity: toNumber(plainStorage.locked_quantity, 0), available_quantity: toNumber(plainStorage.available_quantity, 0), production_date: plainStorage.production_date || null, inbound_time: plainStorage.inbound_time || null, space, locationType, space_name: String(space.custom_name || space.space_code || '').trim(), }; const stockId = Number(normalizedStorage.stock_id); const currentStorageRows = storageRowsByStockId.get(stockId) || []; currentStorageRows.push(normalizedStorage); storageRowsByStockId.set(stockId, currentStorageRows); } for (const [ stockId, storageRowsForStock ] of storageRowsByStockId.entries()) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存可分配摘要', summarizeStorageRows(stockId, storageRowsForStock)); } const policyCache = new Map(); const shortageReasonCache = new Map(); const pickingRows = []; const stockAllocationMap = new Map(); const storageAllocationMap = new Map(); const orderResults = []; const totalCount = pendingOrderIds.length; let processedCount = 0; await notifyProgress({ status: 'running', total_count: totalCount, processed_count: processedCount, }); for (const orderId of pendingOrderIds) { const orderRow = orderMap.get(orderId); if (!orderRow) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 处理订单时发现订单缺失', { orderId, }); continue; } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始处理订单', { orderId, orderRow, }); const orderItems = (orderItemsByOrderId.get(orderId) || []) .slice() .sort((left, right) => { const leftLineNo = toNumber(left.order_line_no, 0); const rightLineNo = toNumber(right.order_line_no, 0); if (leftLineNo !== rightLineNo) { return leftLineNo - rightLineNo; } return toNumber(left.id, 0) - toNumber(right.id, 0); }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细准备完成', { orderId, orderItemCount: orderItems.length, orderItemIds: orderItems.map(item => toNumber(item.id, 0)), }); const shortageItems = []; let allocatedQuantityForOrder = 0; for (const orderItem of orderItems) { const stockId = toNumber(orderItem.stock_id, 0); const requiredQuantity = toNumber(orderItem.plan_qty ?? orderItem.planQty ?? orderItem.count ?? 0, 0); if (stockId <= 0 || requiredQuantity <= 0) { shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity > 0 ? requiredQuantity : 0, allocated_quantity: 0, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细无效或缺少库存,记为缺货', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, }); continue; } const policyEntry = policyCache.has(stockId) ? policyCache.get(stockId) : await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction); policyCache.set(stockId, policyEntry); const storageSeparationEnabled = normalizeBooleanFlag(policyEntry?.policyConfig?.storage_separation, true); const allowStorageSpace = allowStorageLocation || !storageSeparationEnabled; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 读取库存策略完成', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, policyEntry, storage_separation: policyEntry?.policyConfig?.storage_separation, allowStorageLocation, storageSeparationEnabled, allowStorageSpace, }); const storageRowsForStock = storageRowsByStockId.get(stockId) || []; const candidateStorageRows = storageRowsForStock .slice() .sort((left, right) => compareStorageRows(left, right)); let shortageReason = ''; let shortageDiagnostics = null; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 计算候选库存完成', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageRowCountBeforeFilter: storageRowsForStock.length, candidateStorageRowCountAfterFilter: candidateStorageRows.length, allowStorageSpace, candidateStorageIds: candidateStorageRows.map(storageRow => storageRow.id), }); if (candidateStorageRows.length === 0) { shortageDiagnostics = await diagnoseStorageTypeRestriction({ ctx, Op, warehouseId, stockId, transaction, cache: shortageReasonCache, }); shortageReason = String(shortageDiagnostics.reason || '').trim(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无候选库位,标记缺货原因', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, policyEntry: { storage_separation: policyEntry?.policyConfig?.storage_separation, allow_storage_location: policyEntry?.policyConfig?.allow_storage_location, }, storageRowsSummary: summarizeStorageRows(stockId, storageRowsForStock), allowStorageSpace, shortageDiagnostics, shortageReason, }); } let remainingQuantity = requiredQuantity; let allocatedQuantityForItem = 0; for (const storageRow of candidateStorageRows) { if (remainingQuantity <= 0) { break; } const currentAvailable = toNumber(storageRow.available_quantity, 0); if (currentAvailable <= 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 候选库存已无可用数量,跳过', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageId: storageRow.id, currentAvailable, }); continue; } const allocationQuantity = Math.min(remainingQuantity, currentAvailable); if (allocationQuantity <= 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 计算出的分配数量无效,跳过', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageId: storageRow.id, currentAvailable, remainingQuantity, }); continue; } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备锁定库存', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageId: storageRow.id, storageRowSummary: { storageId: storageRow.id, spaceId: toNumber(storageRow.space_id, 0) || 0, availableQuantity: currentAvailable, lockedQuantity: toNumber(storageRow.locked_quantity, 0), productionDate: storageRow.production_date || null, inboundTime: storageRow.inbound_time || null, }, allocationQuantity, remainingQuantity, currentAvailable, }); await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageId: storageRow.id, allocationQuantity, }); storageRow.available_quantity = currentAvailable - allocationQuantity; storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) + allocationQuantity; remainingQuantity -= allocationQuantity; allocatedQuantityForItem += allocationQuantity; allocatedQuantityForOrder += allocationQuantity; storageAllocationMap.set(storageRow.id, (storageAllocationMap.get(storageRow.id) || 0) + allocationQuantity); stockAllocationMap.set(stockId, (stockAllocationMap.get(stockId) || 0) + allocationQuantity); pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), storage_id: storageRow.id, quantity: allocationQuantity, space_id: toNumber(storageRow.space_id, 0) || null, space_name: String(storageRow.space_name || '').trim(), status: 'pending', created_at: now, updated_at: now, }); } if (remainingQuantity > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, allocatedQuantity: allocatedQuantityForItem, remainingQuantity, candidateCount: candidateStorageRows.length, }); shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity, allocated_quantity: allocatedQuantityForItem, reason: shortageReason, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, allocatedQuantityForItem, remainingQuantity, shortageReason, }); } } const shortageMessage = buildShortageMessage(shortageItems); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { orderId, shortageItems, shortageMessage, }); const orderUpdateValues = shortageMessage ? { storage_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, order_flag: shortageMessage, updated_at: now, } : { storage_status: STORAGE_STATUS_FIN, order_flag: '', updated_at: now, }; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备更新订单状态', { orderId, orderUpdateValues, allocatedQuantityForOrder, }); await orderModel.update(orderUpdateValues, { where: { id: orderId, warehouse_id: warehouseId, }, transaction, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单状态更新完成', { orderId, orderUpdateValues, }); orderResults.push({ order_id: orderId, storage_status: orderUpdateValues.storage_status, allocated_quantity: allocatedQuantityForOrder, shortage_message: shortageMessage || '', status: shortageMessage ? 'error' : 'success', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 当前订单处理结束', { orderId, orderResult: orderResults[orderResults.length - 1], }); processedCount += 1; await notifyProgress({ status: 'running', total_count: totalCount, processed_count: processedCount, }); } const stockLockEntries = Array.from(stockAllocationMap.entries()) .map(([ stockId, quantity ]) => ({ stockId: toNumber(stockId, 0), quantity: toNumber(quantity, 0), })) .filter(item => item.stockId > 0 && item.quantity > 0); if (stockLockEntries.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备批量更新库存主表锁定数量', { warehouseId, stockLockEntries, }); const lockStockIds = stockLockEntries.map(item => item.stockId); const existingStockRows = await ctx.model.StockWarehouse.findAll({ attributes: [ 'id' ], where: { id: { [Op.in]: lockStockIds, }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const existingStockIdSet = new Set( (Array.isArray(existingStockRows) ? existingStockRows : []) .map(row => toNumber(row && row.id, 0)) .filter(stockId => stockId > 0) ); const missingStockEntry = stockLockEntries.find(item => !existingStockIdSet.has(item.stockId)); if (missingStockEntry) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录缺失,准备抛错', { warehouseId, stockId: missingStockEntry.stockId, quantity: missingStockEntry.quantity, }); throw new Error(`库存主记录不存在: ${missingStockEntry.stockId}`); } const updateSqlReplacements = { warehouseId, stockIds: lockStockIds, }; const caseSqlSegments = []; stockLockEntries.forEach((item, index) => { const stockIdKey = `stockId_${index}`; const quantityKey = `quantity_${index}`; updateSqlReplacements[stockIdKey] = item.stockId; updateSqlReplacements[quantityKey] = item.quantity; caseSqlSegments.push(`WHEN :${stockIdKey} THEN :${quantityKey}`); }); const updateStockLockSql = ` UPDATE wms_stock_warehouse SET locked_quantity = locked_quantity + CASE id ${caseSqlSegments.join('\n ')} ELSE 0 END WHERE warehouse_id = :warehouseId AND id IN (:stockIds) `; await ctx.model.query(updateStockLockSql, { replacements: updateSqlReplacements, transaction, }); const updatedStockRows = await ctx.model.StockWarehouse.findAll({ attributes: [ 'id', 'locked_quantity' ], where: { id: { [Op.in]: lockStockIds, }, warehouse_id: warehouseId, }, transaction, raw: true, }); const updatedLockedQuantityMap = new Map( (Array.isArray(updatedStockRows) ? updatedStockRows : []).map(row => [ toNumber(row && row.id, 0), toNumber(row && row.locked_quantity, 0), ]) ); for (const item of stockLockEntries) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', { warehouseId, stockId: item.stockId, quantity: item.quantity, locked_quantity: toNumber(updatedLockedQuantityMap.get(item.stockId), 0), }); } } if (pickingRows.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 写入 picking 明细', { warehouseId, pickingCount: pickingRows.length, }); await pickingModel.bulkCreate(pickingRows, { transaction, }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备提交事务', { warehouseId, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderCount: skippedOrders.length, skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderResultSummary: summarizeArrayForLog(orderResults), stockLockSummary: summarizeArrayForLog(Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ stock_id: stockId, locked_quantity: quantity, }))), storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, }))), }); await transaction.commit(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', { warehouseId, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderCount: skippedOrders.length, skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), orderResultSummary: summarizeArrayForLog(orderResults), }); const errorOrderResults = orderResults.filter(item => item.status === 'error'); const successOrderResults = orderResults.filter(item => item.status === 'success'); const successOrderIds = successOrderResults .map(item => toNumber(item.order_id, 0)) .filter(orderId => orderId > 0); if (successOrderIds.length > 0) { try { await ctx.service.systems.orderPendingException.reversePendingException({ ids: successOrderIds, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 待处理异常清理完成', { warehouseId, successOrderIds, }); } catch (reverseError) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 待处理异常清理失败,仅记录日志', { warehouseId, successOrderIds, error: reverseError, }); if (ctx.logger && typeof ctx.logger.error === 'function') { ctx.logger.error('[OrderStorageAllocationService.allocatePicking] reversePendingException failed', { warehouseId, successOrderIds, error: reverseError, }); } } } const shortageMessages = errorOrderResults .map(item => item.shortage_message) .filter(Boolean); const responseData = { warehouse_id: warehouseId, allow_storage_location: allowStorageLocation, requested_order_ids: orderIds, pending_order_ids: pendingOrderIds, allocated_order_ids: successOrderResults.map(item => item.order_id), shortage_order_ids: errorOrderResults.map(item => item.order_id), skipped_orders: skippedOrders, orders: [ ...skippedOrders, ...orderResults ], picking_count: pickingRows.length, stock_lock_summary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({ stock_id: stockId, locked_quantity: quantity, })), storage_lock_summary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({ storage_id: storageId, locked_quantity: quantity, })), shortage_messages: shortageMessages, }; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 最终返回摘要', { code: 200, message: shortageMessages.length > 0 ? '储位分配完成,部分订单库存不足' : '储位分配完成', responseDataSummary: { requestedOrderIds: summarizeArrayForLog(responseData.requested_order_ids), pendingOrderIds: summarizeArrayForLog(responseData.pending_order_ids), allocatedOrderIds: summarizeArrayForLog(responseData.allocated_order_ids), shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids), skippedOrders: summarizeArrayForLog(responseData.skipped_orders), orders: summarizeArrayForLog(responseData.orders), stockLockSummary: summarizeArrayForLog(responseData.stock_lock_summary), storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary), shortageMessages: summarizeArrayForLog(responseData.shortage_messages), pickingCount: responseData.picking_count, }, }); return { code: 200, message: shortageMessages.length > 0 ? '储位分配完成,部分订单库存不足' : '储位分配完成', data: responseData, }; } catch (error) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 发生异常,准备回滚事务', { warehouseId, orderIds, error, }); await transaction.rollback(); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务回滚完成', { warehouseId, orderIds, error, }); throw error; } } /** * 兼容旧调用名称的储位分配入口。 * * @param {Object} data 请求体。 * @return {Promise} 分配结果。 */ async allocateStorage(data = {}) { writeAllocationTextLog('[OrderStorageAllocationService.allocateStorage] 入口入参', data); const result = await this.allocatePicking(data); writeAllocationTextLog('[OrderStorageAllocationService.allocateStorage] 返回结果', result); return result; } /** * 待处理订单同步入口。 * * 先完成订单查询、过滤与分组,再按 `create_channel` 路由到 * `orderAsync.syncQmOrders`、`orderAsync.syncManualOrders`、`orderAsync.syncApiOrders` 三个处理入口。 * * @param {Object} data 请求体。 * @return {Promise} 同步结果。 */ async syncOrderIds(data = {}) { const { ctx } = this; const unallocatedPostStatus = 'none'; const fastFailReason = '快递状态未分配,禁止同步'; const snBatchForbiddenReason = 'SN订单不支持批量回传,请改用单订单回传'; const requestData = data && typeof data === 'object' ? data : {}; const normalizeNumber = (value, defaultValue = 0) => { const numericValue = Number(value); return Number.isFinite(numericValue) ? numericValue : defaultValue; }; const normalizeOrderIds = request => { const rawValues = []; if (Array.isArray(request.order_ids)) { rawValues.push(...request.order_ids); } else if (Array.isArray(request.orderIds)) { rawValues.push(...request.orderIds); } else if (Array.isArray(request.ids)) { rawValues.push(...request.ids); } else if (typeof request.order_ids === 'string') { rawValues.push(...request.order_ids.split(',')); } else if (typeof request.orderIds === 'string') { rawValues.push(...request.orderIds.split(',')); } else if (typeof request.ids === 'string') { rawValues.push(...request.ids.split(',')); } else if (request.order_ids !== undefined && request.order_ids !== null && request.order_ids !== '') { rawValues.push(request.order_ids); } else if (request.orderIds !== undefined && request.orderIds !== null && request.orderIds !== '') { rawValues.push(request.orderIds); } else if (request.ids !== undefined && request.ids !== null && request.ids !== '') { rawValues.push(request.ids); } else if (request.order_id !== undefined && request.order_id !== null && request.order_id !== '') { rawValues.push(request.order_id); } else if (request.orderId !== undefined && request.orderId !== null && request.orderId !== '') { rawValues.push(request.orderId); } else if (request.id !== undefined && request.id !== null && request.id !== '') { rawValues.push(request.id); } const orderIds = rawValues .map(value => Number(String(value).trim())) .filter(value => Number.isFinite(value) && value > 0); return Array.from(new Set(orderIds)); }; const normalizeCreateChannel = value => String(value || '').trim().toUpperCase() || 'MANUAL'; const toPlainRecord = record => { if (!record) { return null; } if (typeof record.get === 'function') { return record.get({ plain: true }); } return record; }; const groupOrdersByCreateChannel = orders => { const groupedOrderMap = new Map(); for (const order of Array.isArray(orders) ? orders : []) { if (!order || typeof order !== 'object') { continue; } const createChannel = normalizeCreateChannel(order.create_channel); let groupedOrder = groupedOrderMap.get(createChannel); if (!groupedOrder) { groupedOrder = { create_channel: createChannel, order_ids: [], order_count: 0, orders: [], }; groupedOrderMap.set(createChannel, groupedOrder); } const orderId = normalizeNumber(order.id, 0); if (orderId > 0) { groupedOrder.order_ids.push(orderId); } groupedOrder.order_count += 1; groupedOrder.orders.push({ id: orderId, delivery_order_code: String(order.delivery_order_code || '').trim(), create_channel: createChannel, sync_status: String(order.sync_status || '').trim() || 'padding', express_code: String(order.express_code || '').trim(), post_status: String(order.post_status || '').trim() || 'none', storage_status: String(order.storage_status || '').trim() || 'none', }); } return Array.from(groupedOrderMap.values()); }; const orderIds = normalizeOrderIds(requestData); const warehouseId = normalizeNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); const now = new Date(); if (warehouseId <= 0) { return { code: 400, message: '缺少仓库上下文', data: null, }; } if (orderIds.length === 0) { return { code: 400, message: '订单ID不能为空', data: null, }; } const transaction = await ctx.model.transaction(); try { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderRows = await orderModel.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: orderIds, }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const orderMap = new Map(); console.log('orderRows', JSON.stringify(orderRows)); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { const plainOrder = toPlainRecord(orderRow); if (!plainOrder || !Number(plainOrder.id)) { continue; } orderMap.set(Number(plainOrder.id), plainOrder); } // SN 管理订单不允许走批量回传:通过订单明细 stock_id 反查 stock_warehouse.is_sn_mgmt。 const snOrderIdSet = new Set(); const existingOrderIds = Array.from(orderMap.keys()); if (existingOrderIds.length > 0) { try { const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const stockModel = ctx.model.StockWarehouse; if (orderItemModel && typeof orderItemModel.findAll === 'function' && stockModel && typeof stockModel.findAll === 'function') { const orderItemRows = await orderItemModel.findAll({ where: { order_id: { [ctx.app.Sequelize.Op.in]: existingOrderIds, }, }, attributes: [ 'order_id', 'stock_id' ], raw: true, }); const stockIds = [ ...new Set((Array.isArray(orderItemRows) ? orderItemRows : []) .map(row => Number(row && row.stock_id || 0)) .filter(stockId => Number.isFinite(stockId) && stockId > 0)) ]; if (stockIds.length > 0) { const stockRows = await stockModel.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: stockIds, }, warehouse_id: warehouseId, }, attributes: [ 'id', 'is_sn_mgmt' ], raw: true, }); const snStockIdSet = new Set((Array.isArray(stockRows) ? stockRows : []) .filter(row => String(row && row.is_sn_mgmt || '').trim().toUpperCase() === 'Y') .map(row => Number(row && row.id || 0)) .filter(stockId => Number.isFinite(stockId) && stockId > 0)); for (const row of (Array.isArray(orderItemRows) ? orderItemRows : [])) { const orderId = Number(row && row.order_id || 0); const stockId = Number(row && row.stock_id || 0); if (snStockIdSet.has(stockId) && orderId > 0) { snOrderIdSet.add(orderId); } } } } } catch (snDetectError) { ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] SN订单检测失败', { warehouseId, orderIds: existingOrderIds, message: snDetectError && snDetectError.message, }); throw snDetectError; } } if (snOrderIdSet.size > 0) { const forbiddenOrderIds = Array.from(snOrderIdSet).sort((a, b) => a - b); await transaction.rollback(); return { code: 400, message: snBatchForbiddenReason, data: { warehouse_id: warehouseId, requested_order_ids: orderIds, forbidden_order_ids: forbiddenOrderIds, }, }; } const skippedOrders = []; const fastFailedOrders = []; const syncableOrders = []; for (const orderId of orderIds) { const orderRow = orderMap.get(orderId); if (!orderRow) { skippedOrders.push({ order_id: orderId, status: 'skipped', skipped_reason: 'not_found', }); continue; } if (String(orderRow.sync_status || '').trim() === 'fin') { skippedOrders.push({ order_id: orderId, status: 'skipped', create_channel: normalizeCreateChannel(orderRow.create_channel), skipped_reason: 'already_synced', }); continue; } const normalizedPostStatus = String(orderRow.post_status || '').trim() || unallocatedPostStatus; if (normalizedPostStatus === unallocatedPostStatus) { fastFailedOrders.push({ order_id: orderId, status: 'failed', create_channel: normalizeCreateChannel(orderRow.create_channel), post_status: normalizedPostStatus, failed_reason: 'express_unallocated', message: fastFailReason, }); continue; } syncableOrders.push(orderRow); } const expressFastFailedOrderIds = fastFailedOrders .filter(order => String(order && order.failed_reason || '').trim() === 'express_unallocated') .map(order => normalizeNumber(order.order_id, 0)) .filter(orderId => orderId > 0); const syncableOrderIds = syncableOrders .map(order => normalizeNumber(order.id, 0)) .filter(orderId => orderId > 0); const createChannelGroups = groupOrdersByCreateChannel(syncableOrders); if (syncableOrderIds.length > 0) { await orderModel.update({ sync_status: 'padding', sync_message: '', updated_at: now, }, { where: { id: { [ctx.app.Sequelize.Op.in]: syncableOrderIds, }, warehouse_id: warehouseId, }, transaction, }); } if (expressFastFailedOrderIds.length > 0) { await orderModel.update({ sync_status: 'error', sync_message: fastFailReason, inspection_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, order_flag: fastFailReason, updated_at: now, }, { where: { id: { [ctx.app.Sequelize.Op.in]: expressFastFailedOrderIds, }, warehouse_id: warehouseId, }, transaction, }); ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快递状态未分配快速失败,已阻断同步派发', { warehouseId, orderIds: expressFastFailedOrderIds, reason: fastFailReason, }); } await transaction.commit(); const routeContext = { warehouseId, requestedOrderIds: orderIds, pendingOrderIds: syncableOrderIds, }; const orderAsyncService = this.ctx.service.systems.orderAsync; const dispatchResults = []; for (const groupedOrder of createChannelGroups) { const createChannel = normalizeCreateChannel(groupedOrder.create_channel); let result; if (createChannel === 'QM') { result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); } else if (createChannel === 'API') { result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); } else { result = await orderAsyncService.syncManualOrders(groupedOrder, routeContext); } const dispatchStatus = result && result.status ? String(result.status).trim() || 'success' : (result && result.success === false ? 'failed' : 'success'); dispatchResults.push({ ...result, status: dispatchStatus, }); } const responseData = { warehouse_id: warehouseId, requested_order_ids: orderIds, pending_order_ids: syncableOrderIds, skipped_orders: skippedOrders, create_channel_groups: createChannelGroups, dispatch_results: dispatchResults, failed_orders: fastFailedOrders, orders: [ ...skippedOrders, ...fastFailedOrders, ...syncableOrders.map(order => ({ order_id: normalizeNumber(order.id, 0), delivery_order_code: String(order.delivery_order_code || '').trim(), create_channel: normalizeCreateChannel(order.create_channel), express_code: String(order.express_code || '').trim(), sync_status: 'padding', status: 'pending', })), ], pending_count: syncableOrderIds.length, skipped_count: skippedOrders.length, failed_count: fastFailedOrders.length, create_channel_count: createChannelGroups.length, dispatch_count: dispatchResults.length, dispatch_success_count: dispatchResults.filter(item => item.status === 'success').length, dispatch_failed_count: dispatchResults.filter(item => item.status === 'failed').length, }; return { code: 200, message: syncableOrderIds.length > 0 ? '同步已受理,已生成按来源分组的同步计划' : (fastFailedOrders.length > 0 ? '同步失败:存在不允许批量回传的订单' : '没有需要同步的订单'), data: responseData, }; } catch (error) { await transaction.rollback(); throw error; } } /** * 取消待处理订单的储位分配,并回滚相关库存锁定。 * * 入参仅支持订单 ID 相关字段: * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` * * 取消分配时仅处理当前用户仓库中已完成储位分配的订单; * 未分配订单或非完成状态订单会进入 skipped_orders。 * * @param {Object} data 请求体。 * @return {Promise} 取消分配结果。 */ async cancelAllocateStorage(data = {}) { const { ctx, app } = this; const { orderIds, forbiddenWarehouseKeys } = normalizeCancelStorageAllocationRequest(data); const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 规范化入参', { warehouseId, orderIds, forbiddenWarehouseKeys, }); if (forbiddenWarehouseKeys.length > 0) { throw new Error('待处理订单储位取消分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文'); } if (warehouseId <= 0) { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 缺少仓库上下文,直接返回', { warehouseId, orderIds, }); return { code: 400, message: '缺少仓库上下文', data: null, }; } if (orderIds.length === 0) { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 订单ID为空,直接返回', { warehouseId, orderIds, }); return { code: 400, message: '订单ID不能为空', data: null, }; } const transaction = await ctx.model.transaction(); const { Op } = app.Sequelize; const now = new Date(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', { warehouseId, orderIds, }); try { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; const storageModel = ctx.model.Storage; const stockModel = ctx.model.StockWarehouse; if (!pickingModel || typeof pickingModel.findAll !== 'function' || typeof pickingModel.destroy !== 'function') { throw new Error('wms_picking 模型不可用'); } if (!storageModel || typeof storageModel.findAll !== 'function') { throw new Error('wms_storage 模型不可用'); } if (!stockModel || typeof stockModel.findByPk !== 'function') { throw new Error('wms_stock_warehouse 模型不可用'); } const orderRows = await orderModel.findAll({ where: { id: { [Op.in]: orderIds, }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const orderMap = new Map(); for (const orderRow of Array.isArray(orderRows) ? orderRows : []) { const plainOrder = toPlainRecord(orderRow); if (!plainOrder || !Number(plainOrder.id)) { continue; } orderMap.set(Number(plainOrder.id), plainOrder); } const skippedOrders = []; const eligibleOrderIds = []; for (const orderId of orderIds) { const orderRow = orderMap.get(orderId); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 过滤订单前', { orderId, hasOrderRow: Boolean(orderRow), storageStatus: orderRow ? orderRow.storage_status : null, }); if (!orderRow) { skippedOrders.push({ order_id: orderId, status: 'skipped', skipped_reason: 'not_found', }); continue; } if (String(orderRow.storage_status || 'none') !== STORAGE_STATUS_FIN) { skippedOrders.push({ order_id: orderId, status: 'skipped', storage_status: orderRow.storage_status, skipped_reason: 'not_allocated', }); continue; } eligibleOrderIds.push(orderId); } writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 订单过滤完成', { requestedOrderIds: orderIds, eligibleOrderIds, skippedOrders, }); if (eligibleOrderIds.length === 0) { await transaction.commit(); return { code: 200, message: '没有需要取消分配的订单', data: { warehouse_id: warehouseId, requested_order_ids: orderIds, cancellable_order_ids: [], skipped_orders: skippedOrders, orders: skippedOrders, picking_count: 0, storage_unlock_summary: [], stock_unlock_summary: [], }, }; } const pickingRows = await pickingModel.findAll({ where: { order_id: { [Op.in]: eligibleOrderIds, }, status: { [Op.ne]: 'cancel', }, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const pickingRowsByOrderId = new Map(); const storageQuantityMap = new Map(); const storageIdSet = new Set(); for (const pickingRow of Array.isArray(pickingRows) ? pickingRows : []) { const plainPicking = toPlainRecord(pickingRow); const orderId = toNumber(plainPicking?.order_id, 0); const storageId = toNumber(plainPicking?.storage_id, 0); const quantity = toNumber(plainPicking?.quantity, 0); if (orderId <= 0 || storageId <= 0 || quantity <= 0) { continue; } const orderPickingRows = pickingRowsByOrderId.get(orderId) || []; orderPickingRows.push(plainPicking); pickingRowsByOrderId.set(orderId, orderPickingRows); storageIdSet.add(storageId); storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity); } const cancellableOrderIds = []; for (const orderId of eligibleOrderIds) { if (pickingRowsByOrderId.has(orderId)) { cancellableOrderIds.push(orderId); continue; } skippedOrders.push({ order_id: orderId, status: 'skipped', storage_status: 'fin', skipped_reason: 'no_allocation', }); } if (cancellableOrderIds.length === 0) { await transaction.commit(); return { code: 200, message: '没有需要取消分配的订单', data: { warehouse_id: warehouseId, requested_order_ids: orderIds, cancellable_order_ids: [], skipped_orders: skippedOrders, orders: skippedOrders, picking_count: 0, storage_unlock_summary: [], stock_unlock_summary: [], }, }; } const storageRows = await storageModel.findAll({ where: { id: { [Op.in]: Array.from(storageIdSet), }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const storageMap = new Map(); for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { const plainStorage = toPlainRecord(storageRow); if (!plainStorage || !Number(plainStorage.id)) { continue; } storageMap.set(Number(plainStorage.id), plainStorage); } const storageUnlockSummary = []; const stockUnlockSummary = []; for (const [ storageId, quantity ] of storageQuantityMap.entries()) { if (quantity <= 0) { continue; } const storageRow = storageMap.get(storageId); if (!storageRow) { throw new Error(`库存记录不存在: ${storageId}`); } const stockId = toNumber(storageRow.stock_id, 0); if (stockId <= 0) { throw new Error(`库存记录缺少 stock_id: ${storageId}`); } await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction, }); storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity, }); if (typeof stockModel.update === 'function') { const decrementResult = await stockModel.update({ locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`), update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { id: stockId, locked_quantity: { [Op.gte]: Number(quantity), }, }, transaction, }); if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) { throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); } } else { const stockRecord = await stockModel.findByPk(stockId, { transaction, }); if (!stockRecord) { throw new Error(`库存主记录不存在: ${stockId}`); } const currentLocked = toNumber(stockRecord.locked_quantity, 0); if (currentLocked < Number(quantity)) { throw new Error(`库存主记录锁定数量不足,无法释放: ${stockId}`); } await stockRecord.increment('locked_quantity', { by: -quantity, transaction, silent: true, }); } stockUnlockSummary.push({ stock_id: stockId, unlocked_quantity: quantity, }); } const cancelPickingIds = []; for (const orderId of cancellableOrderIds) { const orderPickingRows = pickingRowsByOrderId.get(orderId) || []; cancelPickingIds.push(...orderPickingRows.map(row => toNumber(row.id, 0)).filter(pickingId => pickingId > 0)); } if (cancelPickingIds.length > 0) { await pickingModel.destroy({ where: { id: { [Op.in]: cancelPickingIds, }, }, transaction, }); } const cancelOrderWhere = { id: { [Op.in]: cancellableOrderIds, }, warehouse_id: warehouseId, }; await orderModel.update({ storage_status: 'none', order_flag: '', updated_at: now, }, { where: cancelOrderWhere, transaction, }); const updatedOrders = await orderModel.findAll({ where: cancelOrderWhere, transaction, raw: true, }); const updatedOrderMap = new Map(); for (const updatedOrder of Array.isArray(updatedOrders) ? updatedOrders : []) { const plainOrder = toPlainRecord(updatedOrder); if (!plainOrder || !Number(plainOrder.id)) { continue; } updatedOrderMap.set(Number(plainOrder.id), plainOrder); } const orderResults = cancellableOrderIds .map(orderId => updatedOrderMap.get(orderId)) .filter(Boolean) .map(order => ({ order_id: order.id, storage_status: order.storage_status, order_flag: order.order_flag || '', status: 'success', })); const responseData = { warehouse_id: warehouseId, requested_order_ids: orderIds, cancellable_order_ids: cancellableOrderIds, skipped_orders: skippedOrders, orders: [ ...skippedOrders, ...orderResults ], picking_count: cancelPickingIds.length, storage_unlock_summary: storageUnlockSummary, stock_unlock_summary: stockUnlockSummary, }; await transaction.commit(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', { warehouseId, requestedOrderIds: orderIds, cancellableOrderIds, skippedOrders, }); return { code: 200, message: '取消分配完成', data: responseData, }; } catch (error) { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { warehouseId, orderIds, error, }); await transaction.rollback(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { warehouseId, orderIds, error, }); throw error; } } } module.exports = OrderStorageAllocationService;