- stock/warehouse: 新增 externalList/externalExport(外仓/货主维度查询) - storeWarehouse/store: 新增货主侧接口(list/get 等) - stock_store: getWarehouseStock 支持 externalWarehouseId/externalStoreId - store_warehouse: 合同关系改为单向维度查询(不再 OR 两边) - storage/report: 库存报表支持 store 维度 + stockIds/keyword 精确筛选 - stock/transaction: storeList/exportStore store_id 从 ctx 获取防越权 - stock_warehouse: getStockDetails 支持显式传 null 跳过仓库过滤 - storage/management: 储位分配待处理排除待审核(step=1)订单
349 lines
12 KiB
JavaScript
349 lines
12 KiB
JavaScript
'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。
|
||
* @return {Promise<Object>} 补货需求明细、汇总与分页信息。
|
||
*/
|
||
async replenishmentDemand(options = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
|
||
// 仓库上下文:从用户上下文获取
|
||
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' ],
|
||
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, {
|
||
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' ],
|
||
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, {
|
||
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' ],
|
||
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, {
|
||
stock_code: String(row.item_code || ''),
|
||
stock_name: String(row.item_name || ''),
|
||
});
|
||
}
|
||
}
|
||
|
||
// 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}` };
|
||
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,
|
||
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;
|