'use strict'; const MainService = require('../main'); const { isInterceptedOrderStatus } = require('../../lib/intercept_guard'); const { isLockedOrderStatus } = require('../../lib/lock_guard'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; const ORDER_STATUS_CANCEL = 'cancel'; 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; // 优先使用调用方显式传入的仓库ID(Qimen 等无登录用户上下文的链路 ctx.user 为空) const warehouseId = toNumber( requestData.warehouse_id ?? requestData.warehouseId ?? 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 = []; const errorRetryOrderIds = []; 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.status || '').trim() === ORDER_STATUS_CANCEL) { skippedOrders.push({ order_id: orderId, status: 'skipped', order_status: orderRow.status, skipped_reason: 'order_cancelled', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { orderId, skippedReason: 'order_cancelled', }); continue; } if (isInterceptedOrderStatus(orderRow && orderRow.intercept_status)) { skippedOrders.push({ order_id: orderId, status: 'skipped', intercept_status: orderRow.intercept_status, skipped_reason: 'intercepted', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { orderId, interceptStatus: orderRow.intercept_status, skippedReason: 'intercepted', }); continue; } if (isLockedOrderStatus(orderRow && orderRow.lock_status)) { skippedOrders.push({ order_id: orderId, status: 'skipped', lock_status: orderRow.lock_status, skipped_reason: 'locked', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', { orderId, lockStatus: orderRow.lock_status, skippedReason: 'locked', }); 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); if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_ERROR) { errorRetryOrderIds.push(orderId); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', { orderId, storageStatus: orderRow.storage_status, pendingOrderCount: pendingOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单过滤完成', { requestedOrderCount: orderIds.length, pendingOrderCount: pendingOrderIds.length, skippedOrderCount: skippedOrders.length, errorRetryOrderCount: errorRetryOrderIds.length, pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT), errorRetryOrderSampleIds: errorRetryOrderIds.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' ], ...(allowStorageLocation ? {} : { 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, allowStorageLocation, }); 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 storageAllocationMap = new Map(); const orderResults = []; const totalCount = pendingOrderIds.length; let processedCount = 0; // 按订单维度跟踪已锁定的库存记录,用于缺货订单的原子回滚。 // Map> const orderLockRecords = new Map(); // 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存 if (errorRetryOrderIds.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', { warehouseId, errorRetryOrderIds, errorRetryOrderCount: errorRetryOrderIds.length, }); const oldPickingRecords = await pickingModel.findAll({ where: { order_id: { [Op.in]: errorRetryOrderIds }, status: 'pending', }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 查询到旧的 picking 记录', { warehouseId, oldPickingCount: Array.isArray(oldPickingRecords) ? oldPickingRecords.length : 0, }); if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) { for (const record of oldPickingRecords) { const storageId = toNumber(record.storage_id, 0); const quantity = toNumber(record.quantity, 0); if (storageId > 0 && quantity > 0) { await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', { warehouseId, orderId: toNumber(record.order_id, 0), storageId, quantity, }); } } await pickingModel.destroy({ where: { order_id: { [Op.in]: errorRetryOrderIds }, status: 'pending', }, transaction, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已删除旧的 picking 记录', { warehouseId, errorRetryOrderIds, deletedCount: oldPickingRecords.length, }); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] error 订单旧数据清理完成', { warehouseId, errorRetryOrderIds, }); } 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 = []; const storageRowErrors = []; 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 = allowStorageLocation ? null : await diagnoseStorageTypeRestriction({ ctx, Op, warehouseId, stockId, transaction, cache: shortageReasonCache, }); shortageReason = shortageDiagnostics ? 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, }); const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); 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, }); // 写入储位锁定流水 await ctx.model.StorageTransaction.create({ transaction_type: 'LOCK', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: stockId, storage_id: storageRow.id, space_id: storageRow.space_id, quantity: allocationQuantity, before_quantity: storageRow.quantity, after_quantity: storageRow.quantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity + allocationQuantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'PICKING_LOCK', order_no: String(orderId), order_id: orderId, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '分配储位(库存锁定)', }, { transaction }); 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); const spaceId = toNumber(storageRow.space_id, 0); if (!spaceId) { storageRowErrors.push({ storage_id: storageRow.id, reason: '库位未设置' }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,跳过该库存行', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, storageId: storageRow.id, spaceId: storageRow.space_id, }); // 释放刚才 lockQuantity 加的锁,防止 locked_quantity 泄漏 await ctx.service.systems.storage.index.unlockQuantity( storageRow.id, allocationQuantity, { transaction } ); // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity storageRow.available_quantity = currentAvailable; storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; // 回退 remainingQuantity:未分配成功的数量加回去 remainingQuantity += allocationQuantity; // 回退 allocatedQuantityForItem allocatedQuantityForItem -= allocationQuantity; // 回退 allocatedQuantityForOrder allocatedQuantityForOrder -= allocationQuantity; // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; const newStorageQty = prevStorageQty - allocationQuantity; if (newStorageQty <= 0) { storageAllocationMap.delete(storageRow.id); } else { storageAllocationMap.set(storageRow.id, newStorageQty); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退内存计数器', { orderId, storageId: storageRow.id, allocationQuantity, prevStorageQty, newStorageQty, rollback: { remainingQuantity, allocatedQuantityForItem, allocatedQuantityForOrder, storageAvailableQuantity: storageRow.available_quantity, storageLockedQuantity: storageRow.locked_quantity, }, }); continue; } // 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚 const orderLockList = orderLockRecords.get(orderId) || []; orderLockList.push({ storageId: storageRow.id, stockId: storageRow.stock_id, quantity: allocationQuantity }); orderLockRecords.set(orderId, orderLockList); pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), warehouse_id: warehouseId, storage_id: storageRow.id, stock_id: toNumber(storageRow.stock_id, 0) || null, 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) { // 确保每个明细的缺货原因独立计算,避免候选库位为空时的诊断原因 // 被错误地复用到候选库位非空但仍不足的明细上 const finalShortageReason = candidateStorageRows.length === 0 ? shortageReason : (shortageReason || '库存不足'); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, allocatedQuantity: allocatedQuantityForItem, remainingQuantity, candidateCount: candidateStorageRows.length, shortageReason, finalShortageReason, }); shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity, allocated_quantity: allocatedQuantityForItem, reason: finalShortageReason, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', { orderId, orderItemId: toNumber(orderItem.id, 0), stockId, requiredQuantity, allocatedQuantityForItem, remainingQuantity, shortageReason, finalShortageReason, }); } } const shortageMessage = buildShortageMessage(shortageItems); const spaceErrorMessage = storageRowErrors.length > 0 && shortageMessage ? `库位未设置(storage_id:${storageRowErrors.map(e => e.storage_id).join(',')})` : ''; const finalShortageMessage = [ shortageMessage, spaceErrorMessage ].filter(Boolean).join('|'); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单缺货信息汇总', { orderId, shortageItems, storageRowErrors, shortageMessage, finalShortageMessage, }); // 单订单原子性分配:如果本订单有缺货,回滚该订单所有已成功锁定的库存, // 并从 pickingRows 中移除该订单的所有记录,确保同一事务内该订单不留任何 locked_quantity。 if (finalShortageMessage) { const orderLocks = orderLockRecords.get(orderId); if (Array.isArray(orderLocks) && orderLocks.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始回滚订单已锁定库存', { orderId, orderLockCount: orderLocks.length, orderLocks, }); for (const lockRecord of orderLocks) { await ctx.service.systems.storage.index.unlockQuantity( lockRecord.storageId, lockRecord.quantity, { transaction } ); // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; const newStorageQty = prevStorageQty - lockRecord.quantity; if (newStorageQty <= 0) { storageAllocationMap.delete(lockRecord.storageId); } else { storageAllocationMap.set(lockRecord.storageId, newStorageQty); } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已回滚单条库存锁定', { orderId, storageId: lockRecord.storageId, quantity: lockRecord.quantity, prevStorageQty, newStorageQty, }); } // 回退订单级别的已分配数量计数器 allocatedQuantityForOrder = 0; writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单锁定库存回滚完成,已重置 allocatedQuantityForOrder', { orderId, }); } // 从 pickingRows 中移除该订单的所有记录。 // 使用反向遍历 + splice 避免索引漂移,保持 pickingRows 顺序。 for (let pickIdx = pickingRows.length - 1; pickIdx >= 0; pickIdx -= 1) { if (pickingRows[pickIdx].order_id === orderId) { pickingRows.splice(pickIdx, 1); } } writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已从 pickingRows 移除缺货订单记录', { orderId, remainingPickingCount: pickingRows.length, }); } const orderUpdateValues = finalShortageMessage ? { storage_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, order_flag: finalShortageMessage, 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, status: { [ctx.app.Sequelize.Op.ne]: 'cancel', }, }, transaction, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单状态更新完成', { orderId, orderUpdateValues, }); orderResults.push({ order_id: orderId, storage_status: orderUpdateValues.storage_status, allocated_quantity: allocatedQuantityForOrder, shortage_message: finalShortageMessage || '', status: finalShortageMessage ? 'error' : 'success', }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 当前订单处理结束', { orderId, orderResult: orderResults[orderResults.length - 1], }); processedCount += 1; await notifyProgress({ status: 'running', total_count: totalCount, processed_count: processedCount, }); } 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: [], 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: [], 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: [], 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`、 * `orderAsync.syncStockoutOrders` 四个处理入口。 * * @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); // 优先使用调用方传入的 warehouse_id(异步模式下 ctx.user 可能失效), // 兜底从 ctx.user 或 requestData 中读取 const warehouseId = normalizeNumber( requestData.warehouse_id ?? ctx.user?.store_id ?? ctx.user?.warehouse_id, 0 ); const now = new Date(); // 请求ID(用于 Redis 进度缓存) const requestId = String(requestData.request_id || requestData.requestId || '').trim(); 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, // 排除已同步完成的订单,防止重复提交 // 注意:不能排除 padding,因为 padding 是新订单的默认值(模型 defaultValue) sync_status: { [ctx.app.Sequelize.Op.notIn]: [ 'fin' ], }, // 排除已取消的订单,防止已取消订单被回传 status: { [ctx.app.Sequelize.Op.notIn]: [ 'cancel' ], }, }, 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; } } 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; } // SN 管理订单不允许走批量回传,标记为跳过,不阻断其他订单 if (snOrderIdSet.has(orderId)) { fastFailedOrders.push({ order_id: orderId, status: 'failed', create_channel: normalizeCreateChannel(orderRow.create_channel), failed_reason: 'sn_batch_forbidden', message: snBatchForbiddenReason, }); 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); } // SN 订单和快递未分配订单分开设置 sync_message const snFailIds = fastFailedOrders .filter(o => String(o && o.failed_reason || '').trim() === 'sn_batch_forbidden') .map(o => normalizeNumber(o.order_id, 0)) .filter(id => id > 0); const expressFailIds = fastFailedOrders .filter(o => String(o && o.failed_reason || '').trim() === 'express_unallocated') .map(o => normalizeNumber(o.order_id, 0)) .filter(id => id > 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 (snFailIds.length > 0) { await orderModel.update({ sync_status: 'error', sync_message: snBatchForbiddenReason, inspection_status: STORAGE_STATUS_ERROR, step: ORDER_STEP_EXCEPTION, order_flag: snBatchForbiddenReason, updated_at: now, }, { where: { id: { [ctx.app.Sequelize.Op.in]: snFailIds }, warehouse_id: warehouseId, status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, }, transaction, }); } if (expressFailIds.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]: expressFailIds }, warehouse_id: warehouseId, status: { [ctx.app.Sequelize.Op.ne]: 'cancel' }, }, transaction, }); } if (snFailIds.length > 0 || expressFailIds.length > 0) { ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 命中快速失败,已阻断同步派发', { warehouseId, snFailIds, expressFailIds, }); } await transaction.commit(); // ── 写初始进度到 Redis(dispatch handler 内部会递增 processed_count)── if (requestId) { const progressCacheKey = `order:pending:sync_order_ids:request:${requestId}`; try { await ctx.app.setCacheAsync(progressCacheKey, { status: 'running', total_count: syncableOrderIds.length, processed_count: 0, progress: 0, warehouse_id: warehouseId, update_time: Date.now(), }, 7200); } catch (cacheErr) { ctx.logger.warn('[OrderStorageAllocationService.syncOrderIds] 初始化进度缓存失败', { error: cacheErr && cacheErr.message, }); } } const routeContext = { warehouseId, requestedOrderIds: orderIds, pendingOrderIds: syncableOrderIds, request_id: requestId, }; const orderAsyncService = this.ctx.service.systems.orderAsync; // 并行派发各渠道分组(每个分组独立 try/catch,单渠道异常不阻塞其他渠道) const dispatchResults = await Promise.all( createChannelGroups.map(async groupedOrder => { const createChannel = normalizeCreateChannel(groupedOrder.create_channel); const groupOrderCount = Number(groupedOrder.order_count || groupedOrder.order_ids?.length || 0); try { let result; if (createChannel === 'QM') { result = await orderAsyncService.syncQmOrders(groupedOrder, routeContext); } else if (createChannel === 'API') { result = await orderAsyncService.syncApiOrders(groupedOrder, routeContext); } else if (createChannel === 'STOCKOUT') { // 出库单转订单渠道:回传时把快递编码/运单号写回出库单并通知外部, // 成功后才完成订单同步 result = await orderAsyncService.syncStockoutOrders(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'); return { ...result, status: dispatchStatus, }; } catch (channelError) { // 单渠道异常不影响其他渠道 ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 渠道派发异常,已隔离', { createChannel, warehouseId, orderCount: groupOrderCount, error: channelError && channelError.message ? channelError.message : channelError, }); return { create_channel: createChannel, order_ids: Array.isArray(groupedOrder.order_ids) ? groupedOrder.order_ids : [], order_count: groupOrderCount, warehouse_id: warehouseId, handler: 'syncOrderIds', sync_target: createChannel === 'QM' ? 'qimen' : 'internal', status: 'failed', message: channelError && channelError.message ? channelError.message : '渠道派发异常', success_count: 0, failed_count: groupOrderCount, route_state: 'rejected', }; } }) ); // 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,避免重复 // 派发完成后,将成功渠道的订单 sync_status 更新为 fin,防止重复同步 const dispatchedOrderIds = []; for (let i = 0; i < dispatchResults.length; i++) { const dr = dispatchResults[i]; if (dr && String(dr.status || '').trim() === 'success') { const group = createChannelGroups[i]; if (group && Array.isArray(group.order_ids)) { for (const oid of group.order_ids) { dispatchedOrderIds.push(Number(oid)); } } } } if (dispatchedOrderIds.length > 0) { try { await orderModel.update({ sync_status: 'fin', sync_message: '', updated_at: new Date(), }, { where: { id: { [ctx.app.Sequelize.Op.in]: dispatchedOrderIds }, warehouse_id: warehouseId, }, }); ctx.logger.info('[OrderStorageAllocationService.syncOrderIds] 同步完成,已更新 sync_status=fin', { warehouseId, dispatchedCount: dispatchedOrderIds.length, }); } catch (finUpdateErr) { ctx.logger.error('[OrderStorageAllocationService.syncOrderIds] 更新 sync_status=fin 失败', { warehouseId, dispatchedCount: dispatchedOrderIds.length, error: finUpdateErr && finUpdateErr.message, }); } } 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` * - `interceptMode`(可选,布尔值):拦截确认模式,默认 false。 * - false(普通取消):pending 行解除锁定(可用数量 +q)、fin 行返还实物(可用数量 +q),既有行为不变; * - true(拦截确认):pending 行作业锁迁移为拦截锁(locked -q、intercept +q、available 不变), * fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为 * INTERCEPT_LOCK 且记录 order_id 与 before/after_intercept_locked_quantity 快照。 * * 取消分配时仅处理当前用户仓库中已完成储位分配的订单; * 未分配订单或非完成状态订单会进入 skipped_orders。 * * @param {Object} data 请求体。 * @param {boolean} [data.interceptMode] 拦截确认模式开关。 * @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); const interceptMode = normalizeBooleanFlag(data && data.interceptMode, false); 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 externalTransaction = data && data.transaction ? data.transaction : null; const transaction = externalTransaction || await ctx.model.transaction(); const { Op } = app.Sequelize; const now = new Date(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务已创建', { warehouseId, orderIds, hasExternalTransaction: Boolean(externalTransaction), }); try { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; const storageModel = ctx.model.Storage; 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 模型不可用'); } 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) { if (!externalTransaction) { 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: [], storage_return_summary: [], stock_unlock_summary: [], }, }; } const pickingRows = await pickingModel.findAll({ where: { order_id: { [Op.in]: eligibleOrderIds, }, warehouse_id: warehouseId, status: { [Op.ne]: 'cancel', }, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const pickingRowsByOrderId = new Map(); const pendingStorageQuantityMap = new Map(); const finStorageQuantityMap = new Map(); const storageIdSet = new Set(); // 拦截模式(interceptMode)按 (order_id, storage_id) 维度记录数量,供拦截锁迁移与按单回落使用 const interceptPendingQuantityMap = new Map(); const interceptFinQuantityMap = new Map(); // 拦截模式拣货行元信息(space_id/stock_id),供缺行补建 storage 使用 const interceptPickingMetaMap = new Map(); 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); // 按状态分流:pending 记录解除锁定(实物不动); // fin 记录(已拣货)返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 const pickingStatus = String(plainPicking?.status || '').trim(); const interceptPairKey = `${orderId}:${storageId}`; if (!interceptPickingMetaMap.has(interceptPairKey)) { interceptPickingMetaMap.set(interceptPairKey, { space_id: toNumber(plainPicking?.space_id, 0), stock_id: toNumber(plainPicking?.stock_id, 0), }); } if (pickingStatus === 'fin') { finStorageQuantityMap.set(storageId, (finStorageQuantityMap.get(storageId) || 0) + quantity); interceptFinQuantityMap.set(interceptPairKey, (interceptFinQuantityMap.get(interceptPairKey) || 0) + quantity); } else { pendingStorageQuantityMap.set(storageId, (pendingStorageQuantityMap.get(storageId) || 0) + quantity); interceptPendingQuantityMap.set(interceptPairKey, (interceptPendingQuantityMap.get(interceptPairKey) || 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) { if (!externalTransaction) { 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: [], storage_return_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 storageReturnSummary = []; if (interceptMode) { // ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ── const interceptUnlockSummaryMap = new Map(); const interceptReturnSummaryMap = new Map(); // 按 storage 累计本批次已迁移的锁定/拦截锁定/实物数量变化,保证同库存多订单时流水快照准确 const interceptLockedDeltaMap = new Map(); const interceptLockedChangeMap = new Map(); const interceptQuantityChangeMap = new Map(); // 仓库默认库位(缺行补建时使用):优先仓库配置 default_location_id,未设置兜底 1 let fallbackDefaultSpaceId = 1; try { const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder; const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function' ? await deliveryOrderService.getStoreSubjectConfig(warehouseId) : null; const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0); if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) { fallbackDefaultSpaceId = configuredLocationId; } } catch (defaultSpaceErr) { ctx.logger.warn( `[order_storage_allocation.cancelAllocateStorage] 读取仓库默认库位失败,兜底库位 1: ${defaultSpaceErr.message}` ); } // pending 记录:作业锁迁移为拦截锁(locked -q、intercept +q、quantity 不变、available 不变) for (const [ pairKey, quantity ] of interceptPendingQuantityMap.entries()) { if (quantity <= 0) { continue; } const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0)); if (orderId <= 0 || storageId <= 0) { continue; } let storageRow = storageMap.get(storageId); const orderRow = orderMap.get(orderId) || {}; const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim() || 'INTERCEPT_CONFIRM'; const pickingMeta = interceptPickingMetaMap.get(pairKey) || {}; if (!storageRow) { // 拦截确认缺行补建:货物在库,直接以拦截锁定入账(quantity=q、intercept=q、available=0) const created = await storageModel.create({ warehouse_id: warehouseId, store_id: toNumber(orderRow.store_id, 0) || null, space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, stock_id: toNumber(pickingMeta.stock_id, 0) || 0, batch_no: String(orderNo).slice(0, 100), inventory_type: 'ZP', quantity, locked_quantity: 0, intercept_locked_quantity: quantity, available_quantity: 0, inbound_time: now, inbound_order_no: String(orderNo).slice(0, 100), is_enabled: 1, created_at: now, updated_at: now, }, { transaction }); const plainCreated = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; storageMap.set(Number(plainCreated.id), plainCreated); storageRow = plainCreated; writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行', { orderId, storageId, createdStorageId: plainCreated.id, quantity, spaceId: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, }); // 直接写拦截锁定流水(补建行:before=0 → after=quantity) await ctx.model.StorageTransaction.create({ transaction_type: 'LOCK', warehouse_id: warehouseId, store_id: plainCreated.store_id, stock_id: plainCreated.stock_id, storage_id: plainCreated.id, space_id: plainCreated.space_id, quantity, before_quantity: quantity, after_quantity: quantity, before_locked_quantity: 0, after_locked_quantity: 0, before_intercept_locked_quantity: 0, after_intercept_locked_quantity: quantity, batch_no: plainCreated.batch_no, inventory_type: 'ZP', order_type: 'INTERCEPT_LOCK', order_no: orderNo, order_id: orderId, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '拦截确认(缺行补建并拦截锁定)', }, { transaction }); interceptUnlockSummaryMap.set(Number(plainCreated.id), (interceptUnlockSummaryMap.get(Number(plainCreated.id)) || 0) + quantity); continue; // 补建行已直接入账,跳过既有迁移逻辑 } const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0) + (interceptLockedDeltaMap.get(storageId) || 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) + (interceptLockedChangeMap.get(storageId) || 0); await ctx.service.systems.storage.index.interceptLockQuantity(storageId, quantity, { transaction, }); interceptLockedDeltaMap.set(storageId, (interceptLockedDeltaMap.get(storageId) || 0) - quantity); interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + quantity); // 写入拦截锁定流水(作业锁迁移为拦截锁,记录拦截快照) await ctx.model.StorageTransaction.create({ transaction_type: 'LOCK', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: storageRow.stock_id, storage_id: storageId, space_id: storageRow.space_id, quantity, before_quantity: storageRow.quantity, after_quantity: storageRow.quantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity - quantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity + quantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'INTERCEPT_LOCK', order_no: orderNo, order_id: orderId, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '拦截确认(作业锁迁移为拦截锁)', }, { transaction }); interceptUnlockSummaryMap.set(storageId, (interceptUnlockSummaryMap.get(storageId) || 0) + quantity); } // fin 记录(已拣货):实物返还并拦截锁定(quantity +q、intercept +q、available 不变) for (const [ pairKey, returnQuantity ] of interceptFinQuantityMap.entries()) { if (returnQuantity <= 0) { continue; } const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0)); if (orderId <= 0 || storageId <= 0) { continue; } let storageRow = storageMap.get(storageId); const orderRow = orderMap.get(orderId) || {}; const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim() || 'INTERCEPT_CONFIRM'; const pickingMeta = interceptPickingMetaMap.get(pairKey) || {}; if (!storageRow) { // 拦截确认缺行补建:实物返还并拦截锁定(quantity=q、intercept=q、available=0) const created = await storageModel.create({ warehouse_id: warehouseId, store_id: toNumber(orderRow.store_id, 0) || null, space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId, stock_id: toNumber(pickingMeta.stock_id, 0) || 0, batch_no: String(orderNo).slice(0, 100), inventory_type: 'ZP', quantity: returnQuantity, locked_quantity: 0, intercept_locked_quantity: returnQuantity, available_quantity: 0, inbound_time: now, inbound_order_no: String(orderNo).slice(0, 100), is_enabled: 1, created_at: now, updated_at: now, }, { transaction }); const plainCreated = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; storageMap.set(Number(plainCreated.id), plainCreated); storageRow = plainCreated; writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行(fin)', { orderId, storageId, createdStorageId: plainCreated.id, returnQuantity, }); // 直接写拦截锁定流水(补建行:before=0 → after=returnQuantity) await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: plainCreated.store_id, stock_id: plainCreated.stock_id, storage_id: plainCreated.id, space_id: plainCreated.space_id, quantity: returnQuantity, before_quantity: returnQuantity, after_quantity: returnQuantity, before_locked_quantity: 0, after_locked_quantity: 0, before_intercept_locked_quantity: 0, after_intercept_locked_quantity: returnQuantity, batch_no: plainCreated.batch_no, inventory_type: 'ZP', order_type: 'INTERCEPT_LOCK', order_no: orderNo, order_id: orderId, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '拦截确认(缺行补建实物返还并拦截锁定)', }, { transaction }); interceptReturnSummaryMap.set(Number(plainCreated.id), (interceptReturnSummaryMap.get(Number(plainCreated.id)) || 0) + returnQuantity); continue; // 补建行已直接入账,跳过既有返还逻辑 } const beforeQuantity = toNumber(storageRow.quantity, 0) + (interceptQuantityChangeMap.get(storageId) || 0); const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) + (interceptLockedChangeMap.get(storageId) || 0); await ctx.service.systems.storage.index.interceptReceiveQuantity(storageId, returnQuantity, { transaction, }); interceptQuantityChangeMap.set(storageId, (interceptQuantityChangeMap.get(storageId) || 0) + returnQuantity); interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + returnQuantity); // 写入拦截锁定流水(实物返还并拦截锁定,记录拦截快照) await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: storageRow.stock_id, storage_id: storageId, space_id: storageRow.space_id, quantity: returnQuantity, before_quantity: beforeQuantity, after_quantity: beforeQuantity + returnQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity + returnQuantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'INTERCEPT_LOCK', order_no: orderNo, order_id: orderId, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '拦截确认(已拣货实物返还并拦截锁定)', }, { transaction }); interceptReturnSummaryMap.set(storageId, (interceptReturnSummaryMap.get(storageId) || 0) + returnQuantity); } for (const [ storageId, quantity ] of interceptUnlockSummaryMap.entries()) { storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity }); } for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) { storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity }); } } else { // ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ── // pending 记录:解除锁定,实物库存不动 for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) { if (quantity <= 0) { continue; } const storageRow = storageMap.get(storageId); if (!storageRow) { throw new Error(`库存记录不存在: ${storageId}`); } const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction, }); // 写入储位解锁流水 await ctx.model.StorageTransaction.create({ transaction_type: 'UNLOCK', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: storageRow.stock_id, storage_id: storageId, space_id: storageRow.space_id, quantity, before_quantity: storageRow.quantity, after_quantity: storageRow.quantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity - quantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'PICKING_UNLOCK', order_no: 'CANCEL_BATCH', order_id: 0, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '取消分配储位(库存解锁)', }, { transaction }); storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity, }); } // fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除 for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) { if (returnQuantity <= 0) { continue; } const storageRow = storageMap.get(storageId); if (!storageRow) { throw new Error(`库存记录不存在: ${storageId}`); } const beforeQuantity = toNumber(storageRow.quantity, 0); const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0); await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, { transaction, }); // 写入库存返还流水(实物数量增加,锁定不变) await ctx.model.StorageTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: storageRow.stock_id, storage_id: storageId, space_id: storageRow.space_id, quantity: returnQuantity, before_quantity: beforeQuantity, after_quantity: beforeQuantity + returnQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'PICK_RETURN', order_no: 'CANCEL_BATCH', order_id: 0, operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''), operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '', remark: '取消分配储位(已拣货返还库存)', }, { transaction }); storageReturnSummary.push({ storage_id: storageId, returned_quantity: returnQuantity, }); } } 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, storage_return_summary: storageReturnSummary, stock_unlock_summary: [], }; if (!externalTransaction) { await transaction.commit(); } writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务提交完成', { warehouseId, requestedOrderIds: orderIds, cancellableOrderIds, skippedOrders, }); return { code: 200, message: '取消分配完成', data: responseData, }; } catch (error) { if (!externalTransaction) { writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 发生异常,准备回滚事务', { warehouseId, orderIds, error, }); await transaction.rollback(); writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 事务回滚完成', { warehouseId, orderIds, error, }); } throw error; } } /** * 按订单 ID 释放拦截锁定数量(拦截锁回落到可用数量)。 * * 依据 wms_storage_transaction 中 order_type='INTERCEPT_LOCK' 与 * order_type='INTERCEPT_UNLOCK' 的流水按 (storage_id, order_id) 汇总净拦截量, * 净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁: * `intercept_locked_quantity -q`、`available_quantity +q`,`quantity` 与 `locked_quantity` 不变, * 并写入 INTERCEPT_UNLOCK 流水记录拦截快照(order_id 与订单对应)。 * 释放量与流水均以订单维度记录,重复调用幂等(净量归零后不再释放)。 * * 使用场景: * - 批量解除拦截(batchUnintercept 后台任务); * - 退货登记完成(return_received.create)。 * * @param {Array} orderIds 订单 ID 数组。 * @param {Object} [options={}] 执行上下文参数。 * @param {number|string} [options.warehouseId] 仓库 ID,缺省取当前用户仓库上下文。 * @param {Object} [options.transaction] 外部事务对象,缺省内部创建事务。 * @param {string} [options.scene='INTERCEPT_UNLOCK'] 释放场景标识(写入流水 order_no)。 * @param {string} [options.remark='解除拦截(拦截锁回落到可用数量)'] 流水备注。 * @param {string} [options.operatorId] 操作人工号 ID,缺省取当前用户上下文。 * @param {string} [options.operatorName] 操作人名称,缺省取当前用户上下文。 * @return {Promise} 释放结果,含 order_ids、released_quantity、storage_release_summary。 */ async releaseInterceptLocksByOrderIds(orderIds = [], options = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const normalizedOrderIds = Array.from(new Set( (Array.isArray(orderIds) ? orderIds : []) .map(orderId => toNumber(orderId, 0)) .filter(orderId => orderId > 0) )); if (normalizedOrderIds.length === 0) { return { order_ids: [], released_quantity: 0, storage_release_summary: [], }; } const warehouseId = toNumber(options.warehouseId, 0) > 0 ? toNumber(options.warehouseId, 0) : toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); if (warehouseId <= 0) { throw new Error('缺少仓库上下文'); } const scene = String(options.scene || 'INTERCEPT_UNLOCK').trim() || 'INTERCEPT_UNLOCK'; const remark = String(options.remark || '解除拦截(拦截锁回落到可用数量)').trim(); const operatorId = String(options.operatorId ?? ctx.user?.employees_id ?? ctx.user?.id ?? ''); const operatorName = String( options.operatorName ?? ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '' ); const externalTransaction = options.transaction || null; const transaction = externalTransaction || await ctx.model.transaction(); try { const groupAttributes = [ 'storage_id', 'order_id', [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], ]; // 汇总本批次订单的拦截锁定流水(按 storage_id + order_id 分组) const lockRows = await ctx.model.StorageTransaction.findAll({ attributes: groupAttributes, where: { warehouse_id: warehouseId, order_type: 'INTERCEPT_LOCK', order_id: { [Op.in]: normalizedOrderIds }, }, group: [ 'storage_id', 'order_id' ], transaction, raw: true, }); const netQuantityMap = new Map(); for (const row of Array.isArray(lockRows) ? lockRows : []) { const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`; netQuantityMap.set(pairKey, toNumber(row.total_quantity, 0)); } if (netQuantityMap.size === 0) { if (!externalTransaction) { await transaction.commit(); } return { order_ids: normalizedOrderIds, released_quantity: 0, storage_release_summary: [], }; } const storageIdSet = new Set(); for (const pairKey of netQuantityMap.keys()) { const storageId = toNumber(pairKey.split(':')[1], 0); if (storageId > 0) { storageIdSet.add(storageId); } } // 汇总已释放的拦截解锁流水(同一订单维度),净量 = 锁定 - 已释放,保证幂等 const unlockRows = await ctx.model.StorageTransaction.findAll({ attributes: groupAttributes, where: { warehouse_id: warehouseId, order_type: 'INTERCEPT_UNLOCK', order_id: { [Op.in]: normalizedOrderIds }, storage_id: { [Op.in]: Array.from(storageIdSet) }, }, group: [ 'storage_id', 'order_id' ], transaction, raw: true, }); for (const row of Array.isArray(unlockRows) ? unlockRows : []) { const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`; netQuantityMap.set(pairKey, (netQuantityMap.get(pairKey) || 0) - toNumber(row.total_quantity, 0)); } // 行锁查询库存,并维护每库存行的剩余可释放拦截量,防止多订单同库存行超释 const storageRows = await ctx.model.Storage.findAll({ where: { id: { [Op.in]: Array.from(storageIdSet) }, warehouse_id: warehouseId, }, transaction, lock: transaction.LOCK.UPDATE, raw: true, }); const storageMap = new Map(); const remainingInterceptByStorage = new Map(); for (const row of Array.isArray(storageRows) ? storageRows : []) { const storageId = toNumber(row.id, 0); storageMap.set(storageId, row); remainingInterceptByStorage.set(storageId, toNumber(row.intercept_locked_quantity, 0)); } const storageReleaseSummary = []; let releasedQuantity = 0; // 已释放拦截量(按 storage 累计),保证同库存行多订单时流水 before/after 快照准确 const releasedInterceptByStorage = new Map(); for (const [ pairKey, netQuantity ] of netQuantityMap.entries()) { if (netQuantity <= 0) { continue; } const pairParts = pairKey.split(':'); const orderId = toNumber(pairParts[0], 0); const storageId = toNumber(pairParts[1], 0); if (orderId <= 0 || storageId <= 0) { continue; } const storageRow = storageMap.get(storageId); if (!storageRow) { continue; } const storageRemaining = remainingInterceptByStorage.get(storageId) || 0; const releaseQuantity = Math.min(netQuantity, storageRemaining); if (releaseQuantity <= 0) { continue; } const beforeQuantity = toNumber(storageRow.quantity, 0); const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0); const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0) - (releasedInterceptByStorage.get(storageId) || 0); await ctx.service.systems.storage.index.interceptUnlockQuantity(storageId, releaseQuantity, { transaction, }); // 写入拦截解锁流水(记录拦截快照,order_id 与订单对应) await ctx.model.StorageTransaction.create({ transaction_type: 'UNLOCK', warehouse_id: warehouseId, store_id: storageRow.store_id, stock_id: storageRow.stock_id, storage_id: storageId, space_id: storageRow.space_id, quantity: releaseQuantity, before_quantity: beforeQuantity, after_quantity: beforeQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: beforeLockedQuantity, before_intercept_locked_quantity: beforeInterceptLockedQuantity, after_intercept_locked_quantity: beforeInterceptLockedQuantity - releaseQuantity, batch_no: storageRow.batch_no, inventory_type: storageRow.inventory_type, order_type: 'INTERCEPT_UNLOCK', order_no: scene, order_id: orderId, operator_id: operatorId, operator_name: operatorName, remark, }, { transaction }); remainingInterceptByStorage.set(storageId, storageRemaining - releaseQuantity); releasedInterceptByStorage.set(storageId, (releasedInterceptByStorage.get(storageId) || 0) + releaseQuantity); releasedQuantity += releaseQuantity; storageReleaseSummary.push({ storage_id: storageId, order_id: orderId, released_quantity: releaseQuantity, }); } if (!externalTransaction) { await transaction.commit(); } return { order_ids: normalizedOrderIds, released_quantity: releasedQuantity, storage_release_summary: storageReleaseSummary, }; } catch (error) { if (!externalTransaction) { await transaction.rollback(); } throw error; } } /** * 分拣缺货补货需求计算。 * * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, * 计算每个 SKU 在分拣区与存货区的可用库存对比, * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 * * 入参: * - `warehouse_id`(可选):仓库 ID,不传则使用当前用户上下文 * * @param {Object} data 请求体。 * @return {Promise} 补货需求明细与汇总信息。 * `list` 每项包含 `is_true_shortage`(两区均无库存时为 true), * `summary` 包含 `total_true_shortage_skus`(真正缺货的 SKU 数量)。 */ } module.exports = OrderStorageAllocationService;