'use strict'; const MainService = require('../main'); const STORAGE_STATUS_FIN = 'fin'; const STORAGE_STATUS_ERROR = 'error'; const ORDER_STEP_EXCEPTION = 3; /** * 将输入值规范化为布尔值。 * * @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 {Object} left 左侧库存。 * @param {Object} right 右侧库存。 * @param {boolean} prioritizeStorage 是否优先使用存储储位。 * @return {number} 排序结果。 */ function compareStorageRows(left, right, prioritizeStorage) { const leftPickPriority = prioritizeStorage ? (left.is_preferred_pick ? 1 : 0) : 0; const rightPickPriority = prioritizeStorage ? (right.is_preferred_pick ? 1 : 0) : 0; if (leftPickPriority !== rightPickPriority) { return leftPickPriority - rightPickPriority; } 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 {Array} shortageItems 缺货条目。 * @return {string} 提示文本。 */ function buildShortageMessage(shortageItems = []) { const parts = shortageItems .filter(item => item && Number(item.stock_id) > 0) .map(item => `sku(${item.stock_id}),数量:${item.required_quantity},库位数量:${item.allocated_quantity}`); 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)); } /** * 订单储位分配公共服务。 * 负责订单、库存、库位的分配编排,并写入 wms_picking。 */ class OrderStorageAllocationService extends MainService { /** * 按订单批量分配储位。 * * 入参支持以下字段: * - `allow_storage_location` / `allowStorageLocation` / `is_allow_storage` / `isAllowStorage` * - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id` * - `warehouse_id` / `warehouseId`(可选,默认使用当前上下文仓库) * * 分配规则: * - 先过滤掉已经完成储位分配的订单 * - 允许时优先使用存储储位,再使用分拣储位 * - FIFO 先按生产日期,再按入库时间 * - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常 * * @param {Object} data 请求体。 * @return {Promise} 分配结果。 */ async allocatePicking(data = {}) { const { ctx, app } = this; const requestData = this.isPlainObject(data) ? data : {}; const warehouseId = toNumber(requestData.warehouse_id ?? requestData.warehouseId ?? ctx.user?.store_id, 0); const orderIds = normalizeOrderIds(requestData); const allowStorageLocation = normalizeBooleanFlag( requestData.allow_storage_location ?? requestData.allowStorageLocation ?? requestData.is_allow_storage ?? requestData.isAllowStorage ); 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(); const { Op } = app.Sequelize; const now = new Date(); try { const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const pickingModel = ctx.model.Picking; 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, }); 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); 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: 'already_allocated', }); continue; } pendingOrderIds.push(orderId); } if (pendingOrderIds.length === 0) { await transaction.commit(); 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, }); 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); 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, }); } 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', 'is_preferred_pick', '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' ]], }) : []; 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(), is_preferred_pick: normalizeBooleanFlag(space.is_preferred_pick), }; const stockId = Number(normalizedStorage.stock_id); const currentStorageRows = storageRowsByStockId.get(stockId) || []; currentStorageRows.push(normalizedStorage); storageRowsByStockId.set(stockId, currentStorageRows); } const policyCache = new Map(); const pickingRows = []; const stockAllocationMap = new Map(); const storageAllocationMap = new Map(); const orderResults = []; for (const orderId of pendingOrderIds) { const orderRow = orderMap.get(orderId); if (!orderRow) { continue; } 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); }); 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, }); 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; const candidateStorageRows = (storageRowsByStockId.get(stockId) || []) .filter(storageRow => allowStorageSpace || storageRow.is_preferred_pick) .slice() .sort((left, right) => compareStorageRows(left, right, allowStorageSpace)); 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) { continue; } const allocationQuantity = Math.min(remainingQuantity, currentAvailable); if (allocationQuantity <= 0) { continue; } await ctx.service.systems.storage.lockQuantity(storageRow.id, allocationQuantity, { 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); 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) { shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity, allocated_quantity: allocatedQuantityForItem, }); } } const shortageMessage = buildShortageMessage(shortageItems); 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, }; await orderModel.update(orderUpdateValues, { where: { id: orderId, warehouse_id: warehouseId, }, transaction, }); orderResults.push({ order_id: orderId, storage_status: orderUpdateValues.storage_status, allocated_quantity: allocatedQuantityForOrder, shortage_message: shortageMessage || '', status: shortageMessage ? 'error' : 'success', }); } for (const [ stockId, quantity ] of stockAllocationMap.entries()) { if (quantity <= 0) { continue; } const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, { transaction, }); if (!stockRecord) { throw new Error(`库存主记录不存在: ${stockId}`); } await stockRecord.increment('locked_quantity', { by: quantity, transaction, silent: true, }); await stockRecord.reload({ transaction }); } if (pickingRows.length > 0) { await pickingModel.bulkCreate(pickingRows, { transaction, }); } await transaction.commit(); const errorOrderResults = orderResults.filter(item => item.status === 'error'); const successOrderResults = orderResults.filter(item => item.status === 'success'); const shortageMessages = errorOrderResults .map(item => item.shortage_message) .filter(Boolean); return { code: 200, message: shortageMessages.length > 0 ? '储位分配完成,部分订单库存不足' : '储位分配完成', data: { 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, }, }; } catch (error) { await transaction.rollback(); throw error; } } /** * 兼容旧调用名称的储位分配入口。 * * @param {Object} data 请求体。 * @return {Promise} 分配结果。 */ async allocateStorage(data = {}) { return await this.allocatePicking(data); } } module.exports = OrderStorageAllocationService;