'use strict'; const Service = require('egg').Service; /** * 将输入值转换为有限数字。 * * @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; } /** * 库存管理服务层。 * 负责库存分布分析、补货需求计算等库存管理相关业务逻辑。 */ class StorageManagementService extends Service { /** * 分拣缺货补货需求计算。 * * 仓库级别的计算,针对当前仓库所有未完成储位分配的订单, * 计算每个 SKU 在分拣区与存货区的可用库存对比, * 输出分拣区缺口及建议补货量,供仓库人员决策移库。 * * 仓库 ID 从用户上下文(ctx.user.store_id / ctx.user.warehouse_id)自动获取,无需显式传入。 * * @param {Object} [options={}] 可选项。 * @param {Object} [options.pagination] 分页参数。 * @param {number} [options.pagination.page=1] 页码,默认 1。 * @param {number} [options.pagination.pageSize=20] 每页大小,默认 20。 * @param {Object} [options.sort] 排序参数。 * @param {string} [options.sort.sortField='shortage'] 排序字段,默认 shortage。 * @param {string} [options.sort.sortOrder='DESC'] 排序方向,ASC/DESC。 * @param {number[]} [options.storeIds] 货主筛选:仅返回指定货主的 SKU,空数组表示不筛选。 * @return {Promise} 补货需求明细、汇总与分页信息。 */ async replenishmentDemand(options = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; // 货主筛选集合(空数组 = 不筛选) const storeIds = Array.isArray(options.storeIds) ? options.storeIds : []; const storeFilterSet = storeIds.length > 0 ? new Set(storeIds) : null; // 仓库上下文:从用户上下文获取 const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0); if (warehouseId <= 0) { throw new Error('缺少仓库上下文'); } // 1) 获取订单模型和明细模型 const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId); const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); // 2) 查询当前仓库所有未完成储位分配的订单(排除待审核 step=1) const pendingOrders = await orderModel.findAll({ where: { warehouse_id: warehouseId, storage_status: { [Op.ne]: 'fin' }, step: { [Op.ne]: 1 }, delete_at: null, }, attributes: [ 'id' ], raw: true, }); const targetOrderIds = (Array.isArray(pendingOrders) ? pendingOrders : []) .map(row => toNumber(row && row.id, 0)) .filter(id => id > 0); if (targetOrderIds.length === 0) { return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; } // 3) 查询订单明细,汇总每个 SKU 的需求量 const itemRows = await orderItemModel.findAll({ where: { order_id: { [Op.in]: targetOrderIds }, }, attributes: [ 'stock_id', 'plan_qty' ], raw: true, }); const demandByStockId = new Map(); const stockIdSet = new Set(); for (const row of Array.isArray(itemRows) ? itemRows : []) { const stockId = toNumber(row.stock_id, 0); const qty = toNumber(row.plan_qty, 0); if (stockId <= 0 || qty <= 0) continue; demandByStockId.set(stockId, (demandByStockId.get(stockId) || 0) + qty); stockIdSet.add(stockId); } const allStockIds = Array.from(stockIdSet); if (allStockIds.length === 0) { return { list: [], summary: { total_skus: 0, total_shortage_skus: 0, total_replenishment_needed: 0, total_true_shortage_skus: 0 } }; } // 4) 查询 SKU 基础信息(先严格,漏掉的宽松兜底) const stockWarehouseRows = allStockIds.length > 0 ? await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: allStockIds }, warehouse_id: warehouseId, is_valid: 'Y', deleted_at: null, }, attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }) : []; const stockInfoMap = new Map(); const hitStockIds = new Set(); for (const row of Array.isArray(stockWarehouseRows) ? stockWarehouseRows : []) { const stockId = toNumber(row.id, 0); if (stockId <= 0) continue; stockInfoMap.set(stockId, { store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); hitStockIds.add(stockId); } // 宽松兜底:查询未命中的 SKU(去掉 is_valid 和 warehouse_id 限制) const missedStockIds = allStockIds.filter(id => !hitStockIds.has(id)); if (missedStockIds.length > 0) { const fallbackRows = await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: missedStockIds }, deleted_at: null, }, attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); for (const row of Array.isArray(fallbackRows) ? fallbackRows : []) { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); } } // 终极兜底:连已删除的也查 const stillMissedStockIds = allStockIds.filter(id => !stockInfoMap.has(id)); if (stillMissedStockIds.length > 0) { const finalFallbackRows = await ctx.model.StockWarehouse.findAll({ where: { id: { [Op.in]: stillMissedStockIds }, }, attributes: [ 'id', 'item_code', 'item_name', 'store_id' ], raw: true, }); for (const row of Array.isArray(finalFallbackRows) ? finalFallbackRows : []) { const stockId = toNumber(row.id, 0); if (stockId <= 0 || stockInfoMap.has(stockId)) continue; stockInfoMap.set(stockId, { store_id: toNumber(row.store_id, 0), stock_code: String(row.item_code || ''), stock_name: String(row.item_name || ''), }); } } // 4.5) 查询货主名称与 SKU 条码 const ownerStoreIds = Array.from( new Set( Array.from(stockInfoMap.values()) .map(info => toNumber(info.store_id, 0)) .filter(id => id > 0) ) ); const [ storeWarehouseRows, storeRows, barcodeRows ] = await Promise.all([ ownerStoreIds.length > 0 ? ctx.model.StoreWarehouse.findAll({ where: { store_id: { [Op.in]: ownerStoreIds }, warehouse_id: warehouseId, }, attributes: [ 'store_id', 'store_remask' ], raw: true, }) : [], ownerStoreIds.length > 0 ? ctx.model.Store.findAll({ where: { id: { [Op.in]: ownerStoreIds } }, attributes: [ 'id', 'company_name' ], raw: true, }) : [], ctx.model.StockBarcode.findAll({ where: { stock_id: { [Op.in]: allStockIds } }, attributes: [ 'id', 'stock_id', 'barcode' ], raw: true, }), ]); // 货主名称:签约表备注名 store_remask 优先,商家表 company_name 兜底 const storeNameMap = new Map(); for (const row of Array.isArray(storeRows) ? storeRows : []) { const storeId = toNumber(row.id, 0); if (storeId > 0) storeNameMap.set(storeId, String(row.company_name || '')); } for (const row of Array.isArray(storeWarehouseRows) ? storeWarehouseRows : []) { const storeId = toNumber(row.store_id, 0); const remask = String(row.store_remask || '').trim(); if (storeId > 0 && remask) storeNameMap.set(storeId, remask); } // SKU 条码按 stock_id 分组 const barcodeMap = new Map(); for (const row of Array.isArray(barcodeRows) ? barcodeRows : []) { const stockId = toNumber(row.stock_id, 0); if (stockId <= 0) continue; const barcodeList = barcodeMap.get(stockId) || []; barcodeList.push({ id: toNumber(row.id, 0), barcode: String(row.barcode || ''), }); barcodeMap.set(stockId, barcodeList); } // 5) 查询所有可用库存(不区分分拣/存货区),再按库位类型分类汇总 const storageRows = allStockIds.length > 0 ? await ctx.model.Storage.findAll({ where: { warehouse_id: warehouseId, stock_id: { [Op.in]: allStockIds }, is_enabled: 1, delete_at: null, available_quantity: { [Op.gt]: 0 }, }, attributes: [ 'stock_id', 'available_quantity', 'space_id' ], include: [ { model: ctx.model.LocationSpace, as: 'space', required: true, attributes: [ 'id', 'space_code', 'custom_name' ], include: [ { model: ctx.model.LocationType, as: 'locationType', required: true, attributes: [ 'id', 'allow_allocation', 'is_active' ], }, ], }, ], }) : []; // 按 SKU 汇总分拣区与存货区可用库存 const pickZoneQtyByStockId = new Map(); const storageZoneQtyByStockId = new Map(); // 存货区库位明细(用于补货库位推荐) const storageZoneLocationsByStockId = new Map(); for (const storageRow of Array.isArray(storageRows) ? storageRows : []) { const plainStorage = toPlainRecord(storageRow); if (!plainStorage) continue; const stockId = toNumber(plainStorage.stock_id, 0); const availableQty = toNumber(plainStorage.available_quantity, 0); if (stockId <= 0 || availableQty <= 0) continue; const space = toPlainRecord(plainStorage.space) || {}; const locationType = toPlainRecord(space.locationType) || {}; const allowAllocation = toNumber(locationType.allow_allocation, 0); const isActive = toNumber(locationType.is_active, 0); if (allowAllocation === 1 && isActive === 1) { // 分拣区 pickZoneQtyByStockId.set(stockId, (pickZoneQtyByStockId.get(stockId) || 0) + availableQty); } else { // 存货区 storageZoneQtyByStockId.set(stockId, (storageZoneQtyByStockId.get(stockId) || 0) + availableQty); // 收集存货区库位明细 const locationList = storageZoneLocationsByStockId.get(stockId) || []; locationList.push({ space_code: String(space.space_code || ''), space_name: String(space.custom_name || space.space_code || ''), available_quantity: availableQty, }); storageZoneLocationsByStockId.set(stockId, locationList); } } // 6) 组装输出 const list = []; let totalShortageSkus = 0; let totalReplenishmentNeeded = 0; let totalTrueShortageSkus = 0; for (const stockId of allStockIds) { const info = stockInfoMap.get(stockId) || { stock_code: `SKU#${stockId}`, stock_name: `商品#${stockId}` }; // 货主筛选:仅返回指定货主的 SKU if (storeFilterSet && !storeFilterSet.has(info.store_id || 0)) continue; const totalDemand = demandByStockId.get(stockId) || 0; const pickZoneQty = pickZoneQtyByStockId.get(stockId) || 0; const storageZoneQty = storageZoneQtyByStockId.get(stockId) || 0; const shortage = Math.max(0, totalDemand - pickZoneQty); const replenishmentNeeded = Math.min(shortage, storageZoneQty); const replenishmentStatus = storageZoneQty >= shortage ? 'replenishable' : 'true_shortage'; // 补货库位信息:按可用库存降序取前 5 条 const rawLocations = storageZoneLocationsByStockId.get(stockId) || []; rawLocations.sort((a, b) => (b.available_quantity - a.available_quantity)); const replenishmentLocations = rawLocations.slice(0, 5); if (shortage > 0) { list.push({ stock_id: stockId, stock_code: info.stock_code, stock_name: info.stock_name, store_id: info.store_id || 0, store_name: storeNameMap.get(info.store_id) || '', barcodes: barcodeMap.get(stockId) || [], pick_zone_quantity: pickZoneQty, storage_zone_quantity: storageZoneQty, total_demand: totalDemand, shortage, replenishment_needed: replenishmentNeeded, replenishment_status: replenishmentStatus, replenishment_locations: replenishmentLocations, }); totalShortageSkus += 1; totalReplenishmentNeeded += replenishmentNeeded; if (replenishmentStatus === 'true_shortage') { totalTrueShortageSkus += 1; } } } // 7) 排序 const paginationInput = options.pagination || {}; const sortInput = options.sort || options.order || {}; const sortField = String(sortInput.sortField || sortInput.field || 'shortage').trim(); const sortOrderRaw = String(sortInput.sortOrder || sortInput.direction || 'DESC').toUpperCase().trim(); const sortOrder = sortOrderRaw === 'ASC' ? 1 : -1; const allowedSortFields = new Set([ 'stock_id', 'pick_zone_quantity', 'storage_zone_quantity', 'total_demand', 'shortage', 'replenishment_needed', ]); const effectiveSortField = allowedSortFields.has(sortField) ? sortField : 'shortage'; list.sort((a, b) => { const aVal = a[effectiveSortField] ?? 0; const bVal = b[effectiveSortField] ?? 0; return (aVal - bVal) * sortOrder; }); // 8) 内存分页 const page = Math.max(1, toNumber(paginationInput.page, 1)); const pageSize = Math.max(1, toNumber(paginationInput.pageSize, 20)); const total = list.length; const totalPages = Math.ceil(total / pageSize); const startIndex = (page - 1) * pageSize; const pagedList = list.slice(startIndex, startIndex + pageSize); return { list: pagedList, pagination: { page, pageSize, total, totalPages, }, summary: { total_skus: totalShortageSkus, total_shortage_skus: totalShortageSkus, total_replenishment_needed: totalReplenishmentNeeded, total_true_shortage_skus: totalTrueShortageSkus, }, }; } } module.exports = StorageManagementService;