This commit is contained in:
liufumingren 2026-06-24 07:36:43 +08:00
parent 77435aeb79
commit 569a25390f
17 changed files with 1075 additions and 386 deletions

View File

@ -68,6 +68,49 @@ module.exports = app => {
],
});
/**
* 商品详情缓存 key 前缀。
* 与 app/service/systems/stock_warehouse.js 中保持一致。
*/
const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail';
/**
* 构建商品详情缓存 key。
* @param {number} warehouseId 仓库ID
* @param {number} stockId 仓库商品ID
* @return {string} 缓存 key
*/
function buildStockDetailCacheKey(warehouseId, stockId) {
return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`;
}
/**
* 条码变更后自动清除关联的商品详情缓存。
* 直接在 hook 中使用 async/await,缓存删除很快不会阻塞主流程。
* @param {Object} instance Sequelize 模型实例
* @return {Promise<void>}
*/
async function invalidateStockDetailCacheForBarcode(instance) {
try {
const warehouseId = instance.get('warehouse_id');
const stockId = instance.get('stock_id');
if (warehouseId && stockId) {
const cacheKey = buildStockDetailCacheKey(warehouseId, stockId);
if (typeof app.delCacheAsync === 'function') {
await app.delCacheAsync(cacheKey);
app.logger.info(`[StockBarcode] 已清除商品详情缓存: ${cacheKey}`);
}
}
} catch (err) {
app.logger.error(`[StockBarcode] 清除商品详情缓存失败: ${err.message}`);
}
}
// 注册 hooks:条码新增/更新/删除时自动清除关联商品详情缓存
StockBarcode.addHook('afterCreate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode);
StockBarcode.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode);
StockBarcode.addHook('afterDestroy', 'invalidateStockDetailCache', invalidateStockDetailCacheForBarcode);
// 定义关联关系
StockBarcode.associate = function() {
const { StockWarehouse } = app.model;

View File

@ -242,6 +242,47 @@ module.exports = app => {
],
});
/**
* 商品详情缓存 key 前缀。
* 与 app/service/systems/stock_warehouse.js 中保持一致。
*/
const STOCK_DETAIL_CACHE_PREFIX = 'cache:stock_detail';
/**
* 构建商品详情缓存 key。
* @param {number} warehouseId 仓库ID
* @param {number} stockId 仓库商品ID
* @return {string} 缓存 key
*/
function buildStockDetailCacheKey(warehouseId, stockId) {
return `${STOCK_DETAIL_CACHE_PREFIX}:${warehouseId}:${stockId}`;
}
/**
* 资料变更后自动清除商品详情缓存。
* 直接在 afterUpdate hook 中使用 async/await,缓存删除很快不会阻塞主流程。
* @param {Object} instance Sequelize 模型实例
* @return {Promise<void>}
*/
async function invalidateStockDetailCacheAfterUpdate(instance) {
try {
const warehouseId = instance.get('warehouse_id');
const stockId = instance.get('id');
if (warehouseId && stockId) {
const cacheKey = buildStockDetailCacheKey(warehouseId, stockId);
if (typeof app.delCacheAsync === 'function') {
await app.delCacheAsync(cacheKey);
app.logger.info(`[StockWarehouse.afterUpdate] 已清除商品详情缓存: ${cacheKey}`);
}
}
} catch (err) {
app.logger.error(`[StockWarehouse.afterUpdate] 清除商品详情缓存失败: ${err.message}`);
}
}
// 注册 afterUpdate hook:商品资料更新时自动清除详情缓存
StockWarehouse.addHook('afterUpdate', 'invalidateStockDetailCache', invalidateStockDetailCacheAfterUpdate);
StockWarehouse.associate = function() {
const { StoreWarehouse, StockBarcode, ProhibitedType, StockStore, Storage } = app.model;
// store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。

View File

@ -573,18 +573,12 @@ class PendingOrderService extends OrderBaseService {
) ];
const stockMap = new Map();
if (stockIds.length > 0) {
const StockWarehouse = this.ctx.model.StockWarehouse;
if (StockWarehouse) {
const stockWarehouseRows = await StockWarehouse.findAll({
where: {
id: { [this.app.Sequelize.Op.in]: stockIds },
warehouse_id: warehouseId,
},
raw: true,
});
for (const row of stockWarehouseRows) {
stockMap.set(row.id, row);
}
const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{ warehouseId }
);
for (const detail of stockDetails) {
stockMap.set(detail.id, detail);
}
}
@ -5242,39 +5236,8 @@ class PendingOrderService extends OrderBaseService {
});
if (!Array.isArray(pickingRows) || pickingRows.length === 0) {
// 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
if (!orderItemsModel) {
ctx.logger.warn('[PendingOrderService.releaseCreationLockForCancel] OrderItems 模型不可用,跳过库存释放');
await transaction.rollback();
return;
}
const orderItems = await orderItemsModel.findAll({
where: { order_id: { [Op.in]: orderIds } },
attributes: [ 'stock_id', 'plan_qty' ],
raw: true,
transaction,
});
for (const item of orderItems) {
const stockId = Number(item.stock_id || 0);
const qty = Number(item.plan_qty || 0);
if (stockId <= 0 || qty <= 0) continue;
await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: { id: stockId, locked_quantity: { [Op.gte]: qty } },
transaction,
}
);
}
await transaction.commit();
// 无储位分配记录:picking 已被 cancelAllocateStorage 处理完毕,无需再次释放
await transaction.rollback();
return;
}

View File

@ -1271,41 +1271,26 @@ class RecheckOrderService extends OrderBaseService {
.filter(Boolean)
) ];
// 3. 批量查询库存信息
// 3. 批量查询库存信息(复用 getStockDetails,含条码与图片)
const stockMap = new Map();
if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockWarehouse) {
const stockRows = await this.ctx.model.StockWarehouse.findAll({
where: {
id: { [this.app.Sequelize.Op.in]: stockIds },
warehouse_id: warehouseId,
},
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'packing_requirements' ],
raw: true,
});
for (const row of (Array.isArray(stockRows) ? stockRows : [])) {
stockMap.set(Number(row.id), row);
}
}
// 4. 批量查询条码
const barcodeMap = new Map();
if (stockIds.length > 0 && this.ctx.model && this.ctx.model.StockBarcode) {
const barcodeRows = await this.ctx.model.StockBarcode.findAll({
where: {
stock_id: { [this.app.Sequelize.Op.in]: stockIds },
warehouse_id: warehouseId,
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const row of (Array.isArray(barcodeRows) ? barcodeRows : [])) {
const sid = Number(row.stock_id);
const barcodeVal = String(row.barcode || '').trim();
if (!barcodeMap.has(sid)) {
barcodeMap.set(sid, []);
const imagesByStockId = new Map();
if (stockIds.length > 0) {
const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{ warehouseId }
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
stockMap.set(sid, detail);
// 从 getStockDetails 提取条码
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean));
}
if (barcodeVal) {
barcodeMap.get(sid).push(barcodeVal);
// 从 getStockDetails 提取图片 URL
const detailImageUrl = String(detail.image_url || '').trim();
if (detailImageUrl) {
imagesByStockId.set(sid, [ detailImageUrl ]);
}
}
}
@ -1338,10 +1323,7 @@ class RecheckOrderService extends OrderBaseService {
}
}
// 6. 批量查询图片
const imagesByStockId = await this.getOrderItemImagesByStockIds(itemsArray);
// 7. 按 order_id 分组商品明细
// 6. 按 order_id 分组商品明细
const itemsByOrderId = new Map();
for (const item of itemsArray) {
const oid = Number(item.order_id);
@ -1351,7 +1333,7 @@ class RecheckOrderService extends OrderBaseService {
itemsByOrderId.get(oid).push(item);
}
// 8. 为每个订单构建 stock 数组
// 7. 为每个订单构建 stock 数组
return orderList.map(order => {
const oid = Number(order.order_id || 0);
const items = itemsByOrderId.get(oid) || [];
@ -1624,6 +1606,10 @@ class RecheckOrderService extends OrderBaseService {
now,
});
// 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成,
// 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失
await this._tryCompleteWaveIfAllOrdersRechecked(orderId, order.wave_id, warehouseId, operator, now);
return {
order_id: orderId,
waybill_no: waybillNo,
@ -3930,6 +3916,154 @@ class RecheckOrderService extends OrderBaseService {
now,
transaction,
});
// 散单复核完成后,在事务内检查订单所属波次下所有订单是否均已复核完成,
// 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失
await this._tryCompleteWaveInTransaction(orderId, order.wave_id, warehouseId, operator, now, transaction);
}
/**
* 散单复核完成后,检查订单所属波次下所有订单是否均已复核完成,
* 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成),
* 使该波次从 batchList 中自然消失。
*
* @param {number} orderId 当前复核的订单ID。
* @param {number|string|null} waveId 订单所属波次ID。
* @param {number} warehouseId 仓库ID。
* @param {{ id: string|null, name: string }} operator 操作人信息。
* @param {Date} now 当前时间。
* @return {Promise<void>} 无返回值。
*/
async _tryCompleteWaveIfAllOrdersRechecked(orderId, waveId, warehouseId, operator, now) {
const { ctx } = this;
const normalizedWaveId = Number(waveId);
if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) {
return;
}
// 查询波次下是否还有未复核的订单(recheck_status != 'fin')
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const unreviewedCount = await orderModel.count({
where: {
wave_id: normalizedWaveId,
warehouse_id: warehouseId,
recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' },
},
});
if (unreviewedCount > 0) {
return;
}
// 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态
const processedCount = await orderModel.count({
where: {
wave_id: normalizedWaveId,
warehouse_id: warehouseId,
recheck_status: 'fin',
},
});
const operatorName = String(operator.name || operator.id || '').trim();
await ctx.model.query(
`UPDATE wms_wave_batch
SET wave_status = 5,
check_operator = :operatorName,
check_time = :now,
processed_orders = :processedCount,
update_time = :now
WHERE wave_id = :waveId
AND warehouse_id = :warehouseId`,
{
replacements: {
waveId: normalizedWaveId,
warehouseId,
operatorName,
processedCount,
now,
},
type: ctx.model.QueryTypes.UPDATE,
}
);
ctx.logger.info(
`[confirmRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}`
);
}
/**
* 在事务内检查订单所属波次下所有订单是否均已复核完成,
* 若全部完成则更新 wms_wave_batch.wave_status = 5(复核完成)。
* 用于批量快捷复核(batchQuickRecheck)事务内的散单路径。
*
* @param {number} orderId 当前复核的订单ID。
* @param {number|string|null} waveId 订单所属波次ID。
* @param {number} warehouseId 仓库ID。
* @param {{ id: string|null, name: string }} operator 操作人信息。
* @param {Date} now 当前时间。
* @param {Object} transaction Sequelize 事务对象。
* @return {Promise<void>} 无返回值。
*/
async _tryCompleteWaveInTransaction(orderId, waveId, warehouseId, operator, now, transaction) {
const { ctx } = this;
const normalizedWaveId = Number(waveId);
if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) {
return;
}
// 在事务内查询波次下是否还有未复核的订单(recheck_status != 'fin')
const orderModel = await this.getOrderModel('order', warehouseId);
const unreviewedCount = await orderModel.count({
where: {
wave_id: normalizedWaveId,
warehouse_id: warehouseId,
recheck_status: { [this.app.Sequelize.Op.ne]: 'fin' },
},
transaction,
});
if (unreviewedCount > 0) {
return;
}
// 波次下所有订单均已复核完成,查询已完成订单数并更新波次状态
const processedCount = await orderModel.count({
where: {
wave_id: normalizedWaveId,
warehouse_id: warehouseId,
recheck_status: 'fin',
},
transaction,
});
const operatorName = String(operator.name || operator.id || '').trim();
await ctx.model.query(
`UPDATE wms_wave_batch
SET wave_status = 5,
check_operator = :operatorName,
check_time = :now,
processed_orders = :processedCount,
update_time = :now
WHERE wave_id = :waveId
AND warehouse_id = :warehouseId`,
{
replacements: {
waveId: normalizedWaveId,
warehouseId,
operatorName,
processedCount,
now,
},
type: ctx.model.QueryTypes.UPDATE,
transaction,
}
);
ctx.logger.info(
`[batchQuickRecheck] 波次复核完成, waveId=${normalizedWaveId}, orderId=${orderId}, processedCount=${processedCount}`
);
}
/**

View File

@ -155,27 +155,35 @@ class entryService extends MainService {
const entryOrder = entryResult.data.entryOrder;
const items = Array.isArray(entryOrder.items) ? entryOrder.items : [];
// 查询商品条码(批量)
// 查询商品条码和图片(复用 getStockDetails 缓存)
const barcodeMap = new Map();
const imageMap = new Map();
try {
const stockIds = items
.map(item => Number(item.stock_id || 0))
.filter(sid => sid > 0);
if (stockIds.length > 0 && ctx.model.StockBarcode) {
const barcodeRows = await ctx.model.StockBarcode.findAll({
where: { stock_id: { [ctx.app.Sequelize.Op.in]: stockIds } },
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const row of barcodeRows) {
if (!barcodeMap.has(row.stock_id)) {
barcodeMap.set(row.stock_id, []);
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{}
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
// 提取条码
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
barcodeMap.set(
sid,
detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)
);
}
// 提取图片(有图片标记但实际 URL 需要额外查询)
if (detail.is_images === 'Y') {
imageMap.set(sid, '');
}
barcodeMap.get(row.stock_id).push(row.barcode);
}
}
} catch (err) {
ctx.logger.warn('[entry.getPrintData] 查询条码失败: %s', err.message);
ctx.logger.warn('[entry.getPrintData] 查询商品详情失败: %s', err.message);
}
const printData = {
@ -199,6 +207,7 @@ class entryService extends MainService {
items_col4: item.count || 0,
items_col5: item.received_quantity || 0,
items_col6: item.inventory_type || '',
items_col7: imageMap.get(Number(item.stock_id)) || '',
})),
};

View File

@ -83,6 +83,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
{ header: '详细地址', key: 'receiver_detail', width: 30 },
{ header: '仓库商品名称', key: 'item_name', width: 30 },
{ header: '商品条码', key: 'item_barcode', width: 24 },
{ header: '商品图片', key: 'item_image', width: 40 },
{ header: '数量', key: 'item_quantity', width: 10 },
{ header: '物流公司', key: 'logistics_name', width: 18 },
{ header: '运单号', key: 'waybill_code', width: 30 },
@ -329,6 +330,7 @@ class OrderExportService extends OrderBaseService {
* @param {Map<number, string>} [context.storeRemarkMap] 货主ID → 货主备注的映射。
* @param {Map<number, string>} [context.stockNameMap] stockId → 仓库商品名称的映射。
* @param {Map<number, string>} [context.barcodeMap] stockId → 商品条码(逗号拼接)的映射。
* @param {Map<number, string>} [context.imageUrlMap] stockId → 商品图片URL的映射。
* @param {Map<number, Array<Object>>} [context.expressMap] 订单ID → 运单行列表的映射。
* @param {Map<number, string>} [context.packageMaterialMap] package_material_id → 包材编码的映射。
* @param {string} [mode='waybill'] 导出模式:'waybill' 或 'item'。
@ -336,7 +338,7 @@ class OrderExportService extends OrderBaseService {
*/
mapOrderExportRow(orderRow = {}, context = {}, mode = 'waybill') {
const safeOrderRow = this.isPlainObject(orderRow) ? orderRow : {};
const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap } = context;
const { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap } = context;
const safeItemsMap = itemsMap instanceof Map ? itemsMap : new Map();
const safeStoreRemarkMap = storeRemarkMap instanceof Map ? storeRemarkMap : new Map();
const safeExpressMap = expressMap instanceof Map ? expressMap : new Map();
@ -377,6 +379,7 @@ class OrderExportService extends OrderBaseService {
const items = safeItemsMap.get(orderId) || [];
const safeStockNameMap = stockNameMap instanceof Map ? stockNameMap : new Map();
const safeBarcodeMap = barcodeMap instanceof Map ? barcodeMap : new Map();
const safeImageUrlMap = imageUrlMap instanceof Map ? imageUrlMap : new Map();
const itemsDetail = Array.isArray(items) && items.length > 0
? items.map(item => {
const stockId = Number(item.stock_id || 0);
@ -440,6 +443,7 @@ class OrderExportService extends OrderBaseService {
...commonFields,
item_name: '',
item_barcode: '',
item_image: '',
item_quantity: '',
business_type: businessType,
logistics_interface_name: this.normalizeExportCellValue(interfaceName),
@ -458,6 +462,7 @@ class OrderExportService extends OrderBaseService {
...commonFields,
item_name: (sid > 0 ? safeStockNameMap.get(sid) : '') || item.item_name || '',
item_barcode: sid > 0 ? (safeBarcodeMap.get(sid) || '') : '',
item_image: sid > 0 ? (safeImageUrlMap.get(sid) || '') : '',
item_quantity: item.plan_qty || 1,
business_type: businessType,
logistics_interface_name: this.normalizeExportCellValue(interfaceName),
@ -691,8 +696,10 @@ class OrderExportService extends OrderBaseService {
}
}
// 批量查询仓库商品名称(wms_stock_warehouse.item_name)
// 批量查询仓库商品名称、条码与图片(复用 getStockDetails 缓存)
const stockNameMap = new Map();
const barcodeMap = new Map();
const imageUrlMap = new Map();
if (itemsMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockWarehouse) {
try {
const stockIds = [
@ -704,22 +711,30 @@ class OrderExportService extends OrderBaseService {
),
];
if (stockIds.length > 0) {
const swRows = await this.ctx.model.StockWarehouse.findAll({
where: {
id: { [this.app.Sequelize.Op.in]: stockIds },
},
attributes: [ 'id', 'item_name' ],
raw: true,
});
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
const sid = Number(sw.id || 0);
if (sid > 0 && !stockNameMap.has(sid)) {
stockNameMap.set(sid, String(sw.item_name || '').trim());
const stockDetails = await this.ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{ warehouseId }
);
for (const detail of stockDetails) {
const sid = Number(detail.id || 0);
if (sid > 0) {
stockNameMap.set(sid, String(detail.item_name || '').trim());
// 从 getStockDetails 的 barcodes 中提取条码并转为逗号拼接
const barcodesRaw = Array.isArray(detail.barcodes)
? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)
: [];
if (barcodesRaw.length > 0) {
barcodeMap.set(sid, [ ...new Set(barcodesRaw) ].join(', '));
}
// 图片字段(有图片标记但实际 URL 需要额外查询)
if (detail.is_images === 'Y') {
imageUrlMap.set(sid, '');
}
}
}
}
} catch (err) {
this.app.logger.warn(`[order_export] 批量查询仓库商品名称失败: ${err.message}`);
this.app.logger.warn(`[order_export] 批量查询商品详情失败: ${err.message}`);
}
}
@ -782,34 +797,6 @@ class OrderExportService extends OrderBaseService {
}
}
// 批量查询商品条码(wms_stock_barcodes)
const barcodeMap = new Map();
if (stockNameMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.StockBarcode) {
try {
const stockIdsForBarcode = [ ...stockNameMap.keys() ];
if (stockIdsForBarcode.length > 0) {
const bcRows = await this.ctx.model.StockBarcode.findAll({
where: { stock_id: { [this.app.Sequelize.Op.in]: stockIdsForBarcode } },
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const bc of (Array.isArray(bcRows) ? bcRows : [])) {
const sid = Number(bc.stock_id || 0);
if (sid > 0) {
if (!barcodeMap.has(sid)) barcodeMap.set(sid, []);
barcodeMap.get(sid).push(String(bc.barcode || '').trim());
}
}
// 转为逗号拼接
for (const [ sid, codes ] of barcodeMap) {
barcodeMap.set(sid, [ ...new Set(codes.filter(Boolean)) ].join(', '));
}
}
} catch (err) {
this.app.logger.warn(`[order_export] 批量查询商品条码失败: ${err.message}`);
}
}
// 批量查询包材编码(wms_package_material),按 package_material_id 分组
const packageMaterialMap = new Map();
if (expressMap.size > 0 && this.ctx && this.ctx.model && this.ctx.model.PackageMaterial) {
@ -840,7 +827,7 @@ class OrderExportService extends OrderBaseService {
}
}
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, expressMap, packageMaterialMap };
const exportContext = { itemsMap, storeRemarkMap, stockNameMap, barcodeMap, imageUrlMap, expressMap, packageMaterialMap };
for (const row of normalizedRows) {
const exportRows = this.mapOrderExportRow(row, exportContext, mode);

View File

@ -1911,33 +1911,23 @@ class stockStoreService extends Service {
const hasPrevious = page > 1;
const hasNext = page < totalPages;
// 批量查询条码信息
// 批量查询条码和图片信息(复用 getStockDetails 缓存)
const stockIds = data.map(item => item.id);
let barcodes = [];
let images = [];
const stockDetailsMap = new Map();
if (stockIds.length > 0) {
barcodes = await ctx.model.StockBarcode.findAll({
where: {
stock_id: {
[Op.in]: stockIds,
},
},
raw: true,
});
images = await ctx.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: {
[Op.in]: stockIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{ warehouseId: ctx.user.store_id }
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
stockDetailsMap.set(sid, {
barcodes: Array.isArray(detail.barcodes)
? detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)
: [],
images: detail.is_images === 'Y' ? [] : [],
});
}
}
// 处理数据,添加一些计算字段
@ -1946,13 +1936,10 @@ class stockStoreService extends Service {
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(
2) : 0;
// 过滤该商品的条码
const itemBarcodes = barcodes
.filter(barcode => barcode.stock_id === item.id)
.map(barcode => barcode.barcode);
const itemImages = images
.filter(images => parseInt(images.business_id) === item.id)
.map(images => images.file.file_url);
// 从 getStockDetails 获取该商品的条码和图片
const stockDetail = stockDetailsMap.get(item.id);
const itemBarcodes = stockDetail ? stockDetail.barcodes : [];
const itemImages = stockDetail ? stockDetail.images : [];
return {
...item,
barcodes: itemBarcodes,

View File

@ -0,0 +1,208 @@
'use strict';
const Service = require('egg').Service;
/**
* 仓库商品详情缓存的 key 前缀模板。
* 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId}
*/
const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail';
/** 仓库商品详情缓存默认 TTL(秒) */
const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300;
class StockWarehouseService extends Service {
/**
* 构建仓库商品详情缓存的 Redis key。
* @param {number} warehouseId 仓库ID
* @param {number} stockId 仓库商品ID
* @return {string} 缓存 key
*/
_buildStockDetailCacheKey(warehouseId, stockId) {
return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`;
}
/**
* 批量获取仓库商品详情(带缓存)。
* 先按 stockId 逐个查缓存,未命中的批量查数据库,
* 然后将数据库结果写入缓存后合并返回。
* 作为通用公共服务,所有模块均可调用。
*
* @param {number[]} stockIds 要查询的 StockWarehouse ID 列表
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string, barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options;
const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id;
if (!Array.isArray(stockIds) || stockIds.length === 0) {
return [];
}
const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ];
const cacheHits = new Map();
const missedStockIds = [];
// 第一步:逐个查缓存
for (const stockId of uniqueStockIds) {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
const cached = await app.getCacheAsync(cacheKey);
if (cached !== null && cached !== undefined) {
cacheHits.set(stockId, cached);
} else {
missedStockIds.push(stockId);
}
} catch {
// 缓存读取异常时降级为查数据库
missedStockIds.push(stockId);
}
}
// 第二步:批量查数据库(只查未命中的 stockId)
/** @type {Map<number, Object>} */
const dbResults = new Map();
if (missedStockIds.length > 0) {
const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' };
if (warehouseId != null) {
stockWhere.warehouse_id = warehouseId;
}
// 并行查询三表:库存主表、条码、图片(避免 N×M 笛卡尔积膨胀,在应用层做 join)
const [ stockRows, barcodeRows, imageRows ] = await Promise.all([
ctx.model.StockWarehouse.findAll({
where: stockWhere,
attributes: [
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'is_images',
'store_id', 'packing_requirements', 'stock_unit',
],
raw: true,
}),
ctx.model.StockBarcode.findAll({
where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } },
attributes: [ 'id', 'barcode', 'stock_id' ],
raw: true,
}),
ctx.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: { [app.Sequelize.Op.in]: missedStockIds.map(String) },
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
raw: true,
}),
]);
// 按 stock_id 分组条码
const barcodeMap = new Map();
for (const row of barcodeRows) {
const sid = row.stock_id;
if (!barcodeMap.has(sid)) {
barcodeMap.set(sid, []);
}
barcodeMap.get(sid).push({
id: row.id,
barcode: row.barcode,
});
}
// 按 business_id(即 stock_id)分组图片URL
const imageUrlMap = new Map();
for (const row of imageRows) {
const sid = Number(row.business_id);
if (!imageUrlMap.has(sid)) {
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
imageUrlMap.set(sid, url);
}
}
// 组装每个 stock 的完整详情
for (const row of stockRows) {
const detail = {
id: row.id,
item_code: row.item_code,
item_name: row.item_name,
sku_property: row.sku_property || '',
quantity: row.quantity || 0,
locked_quantity: row.locked_quantity || 0,
is_batch_mgmt: row.is_batch_mgmt || 'N',
is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N',
is_images: row.is_images || 'N',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
stock_unit: row.stock_unit || '',
image_url: imageUrlMap.get(row.id) || '',
barcodes: barcodeMap.get(row.id) || [],
};
dbResults.set(row.id, detail);
// 第三步:写入缓存
const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id);
try {
await app.setCacheAsync(cacheKey, detail, cacheTTL);
} catch {
// 缓存写入失败不影响主流程
}
}
// 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透
for (const stockId of missedStockIds) {
if (!dbResults.has(stockId)) {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
// 用较短的 TTL 缓存空结果,避免缓存穿透
await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60));
} catch {
// 忽略缓存写入失败
}
}
}
}
// 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序
const result = [];
for (const stockId of uniqueStockIds) {
if (cacheHits.has(stockId)) {
const cached = cacheHits.get(stockId);
// 空标记(防穿透缓存)跳过
if (cached !== null && cached !== undefined) {
result.push(cached);
}
} else if (dbResults.has(stockId)) {
result.push(dbResults.get(stockId));
}
}
return result;
}
/**
* 使指定仓库商品的详情缓存失效。
* 在商品资料更新、图片变更、条码变更时调用。
*
* @param {number} stockId 仓库商品ID
* @param {number} warehouseId 仓库ID
* @return {Promise<void>}
*/
async invalidateStockDetailCache(stockId, warehouseId) {
const { app } = this;
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
await app.delCacheAsync(cacheKey);
} catch {
// 删除缓存失败不影响主流程
}
}
}
module.exports = StockWarehouseService;

View File

@ -402,10 +402,18 @@ class EntryService extends Service {
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
/**
* 查询入库单详情,含商品信息、条码、入库进度。
* @param {Object} data 请求参数
* @param {number} [data.id] 入库单主键 ID
* @param {string} [data.entry_order_code] 入库单号
* @return {Promise<Object>} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情
*/
async get(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : '';
const warehouseId = ctx.user.store_id;
if (!id && !entryOrderCode) {
return {
@ -416,7 +424,7 @@ class EntryService extends Service {
}
const where = {
warehouse_id: ctx.user.store_id,
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
};
@ -444,14 +452,7 @@ class EntryService extends Service {
{
model: ctx.model.EntryItems,
as: 'items',
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
required: false,
},
],
attributes: [ 'id', 'order_id', 'out_biz_code', 'order_line_no', 'owner_code', 'item_code', 'item_id', 'count', 'inventory_type', 'stock_id', 'received_quantity', 'confirm_quantity' ],
required: false,
},
{
@ -478,18 +479,76 @@ class EntryService extends Service {
};
}
// 扁平化 items:将外部商品字段重命名,stock 仓库商品字段平铺到 items 层级
const entryOrderJSON = entryOrder.toJSON();
// 收集所有 stock_id,通过 getStockDetails 获取带缓存的商品详情
const stockIdSet = new Set();
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
for (const item of entryOrderJSON.items) {
if (item.stock_id != null) {
stockIdSet.add(Number(item.stock_id));
}
}
}
const stockIds = [ ...stockIdSet ];
/** @type {Map<number, Object>} */
const stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const detail of stockDetails) {
stockDetailMap.set(detail.id, detail);
}
}
// 查询该入库单所有商品的直接入库进度(非收货单途径)
const directInboundMap = {};
if (stockIds.length > 0) {
const directLogRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'stock_id',
[ ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('quantity')), 'total_quantity' ],
],
where: {
entry_order_code: entryOrderJSON.entry_order_code,
stock_id: { [ctx.app.Sequelize.Op.in]: stockIds },
},
group: [ 'stock_id' ],
raw: true,
});
for (const row of directLogRows) {
directInboundMap[row.stock_id] = Number(row.total_quantity) || 0;
}
}
// 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
entryOrderJSON.items = entryOrderJSON.items.map(item => {
const { item_code, item_id, stock, ...rest } = item;
const { item_code, item_id, stock_id: itemStockId, ...rest } = item;
const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null;
const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0;
const receivedQty = Number(rest.received_quantity) || 0;
const totalCount = Number(rest.count) || 0;
const remaining = Math.max(0, totalCount - receivedQty);
return {
...rest,
stock_id: itemStockId,
external_item_code: item_code,
external_item_id: item_id,
warehouse_item_code: (stock && stock.item_code) || '',
warehouse_item_name: (stock && stock.item_name) || '',
warehouse_item_spec: (stock && stock.sku_property) || '',
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
warehouse_quantity: (stockDetail && stockDetail.quantity != null) ? stockDetail.quantity : null,
warehouse_locked_quantity: (stockDetail && stockDetail.locked_quantity != null) ? stockDetail.locked_quantity : null,
warehouse_is_batch_mgmt: (stockDetail && stockDetail.is_batch_mgmt != null) ? stockDetail.is_batch_mgmt : null,
warehouse_is_shelf_life_mgmt: (stockDetail && stockDetail.is_shelf_life_mgmt != null) ? stockDetail.is_shelf_life_mgmt : null,
warehouse_image_url: (stockDetail && stockDetail.is_images === 'Y') ? '' : '',
warehouse_is_images: (stockDetail && stockDetail.is_images != null) ? stockDetail.is_images : null,
barcodes: (stockDetail && stockDetail.barcodes) || [],
direct_inbound_quantity: directInboundQty,
remaining_quantity: remaining,
};
});
}

View File

@ -128,26 +128,9 @@ function toBooleanFlag(value) {
return false;
}
/**
* 将模型查询结果转换为普通对象。
*
* @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;
}
/**
* 批量加载库存商品的条码与图片附属信息。
* 复用 stock_warehouse.getStockDetails 缓存查询。
*
* @param {Object} ctx 当前请求上下文
* @param {number[]} stockIds 商品ID列表
@ -167,86 +150,36 @@ async function loadStockAttachments(ctx, stockIds = []) {
return { barcodesByStockId, imagesByStockId };
}
const hasStockBarcodeModel = ctx.model && ctx.model.StockBarcode && typeof ctx.model.StockBarcode.findAll === 'function';
if (hasStockBarcodeModel) {
try {
const barcodeRows = await ctx.model.StockBarcode.findAll({
where: {
stock_id: {
[ctx.app.Sequelize.Op.in]: uniqueStockIds,
},
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const item of barcodeRows || []) {
const row = toPlainRecord(item);
if (!row) {
continue;
}
const stockId = Number(row.stock_id);
const barcode = row.barcode ? String(row.barcode) : '';
if (!stockId || !barcode) {
continue;
}
if (!barcodesByStockId.has(stockId)) {
barcodesByStockId.set(stockId, []);
}
barcodesByStockId.get(stockId).push(barcode);
try {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
uniqueStockIds,
{}
);
for (const detail of stockDetails) {
const stockId = Number(detail.id);
if (!stockId) {
continue;
}
} catch (error) {
ctx.logger?.warn?.('[storage.inventory] 查询商品条码失败,已降级为空数组', {
error: error.message,
});
}
}
const hasFileReferenceModel = ctx.model && ctx.model.FileReference && typeof ctx.model.FileReference.findAll === 'function';
const hasFileModel = Boolean(ctx.model && ctx.model.File);
if (hasFileReferenceModel && hasFileModel) {
try {
const imageRows = await ctx.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: {
[ctx.app.Sequelize.Op.in]: uniqueStockIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
});
for (const item of imageRows || []) {
const row = toPlainRecord(item);
if (!row) {
continue;
// 提取条码
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
const barcodes = detail.barcodes
.map(bc => String(bc.barcode || '').trim())
.filter(Boolean);
if (barcodes.length > 0) {
barcodesByStockId.set(stockId, barcodes);
}
const stockId = Number(row.business_id);
const imageUrl = (row.file && row.file.file_url) || row.file_url || row.url || row.file_path || '';
if (!stockId || !imageUrl) {
continue;
}
if (!imagesByStockId.has(stockId)) {
imagesByStockId.set(stockId, []);
}
imagesByStockId.get(stockId).push(String(imageUrl));
}
} catch (error) {
ctx.logger?.warn?.('[storage.inventory] 查询商品图片失败,已降级为空数组', {
error: error.message,
});
// 提取图片
if (detail.image_url) {
imagesByStockId.set(stockId, [ String(detail.image_url).trim() ]);
}
}
} catch (error) {
ctx.logger?.warn?.('[storage.inventory] 查询商品附属信息失败,已降级为空数组', {
error: error.message,
});
}
return {

View File

@ -337,16 +337,36 @@ class StorageReportService extends Service {
const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
const [ stockRows, storeRows, spaceRows, barcodeRows ] = await Promise.all([
normalizedStockIds.length > 0
? ctx.model.StockWarehouse.findAll({
where: {
id: normalizedStockIds,
},
attributes: [ 'id', 'item_name', 'item_code' ],
raw: true,
})
: [],
// 从 getStockDetails 获取商品名称、条码信息
const stockMap = new Map();
const barcodeMap = new Map();
if (normalizedStockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
normalizedStockIds,
{}
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
stockMap.set(sid, {
id: sid,
item_name: detail.item_name,
item_code: detail.item_code,
});
// 提取条码
if (includeBarcode && Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
const barcodeSet = new Set();
for (const bc of detail.barcodes) {
const barcode = String(bc.barcode || '').trim();
if (barcode) {
barcodeSet.add(barcode);
}
}
barcodeMap.set(sid, barcodeSet);
}
}
}
const [ storeRows, spaceRows ] = await Promise.all([
normalizedStoreIds.length > 0
? ctx.model.Store.findAll({
where: {
@ -365,34 +385,10 @@ class StorageReportService extends Service {
raw: true,
})
: [],
includeBarcode && normalizedStockIds.length > 0
? ctx.model.StockBarcode.findAll({
where: {
stock_id: normalizedStockIds,
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
})
: [],
]);
const stockMap = new Map((stockRows || []).map(item => [ Number(item.id), item ]));
const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ]));
const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ]));
const barcodeMap = new Map();
for (const row of barcodeRows || []) {
const stockId = Number(row.stock_id);
const barcode = row.barcode ? String(row.barcode).trim() : '';
if (!stockId || !barcode) {
continue;
}
if (!barcodeMap.has(stockId)) {
barcodeMap.set(stockId, new Set());
}
barcodeMap.get(stockId).add(barcode);
}
return {
stockMap,
@ -960,52 +956,47 @@ class StorageReportService extends Service {
const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
const [ stockRows, barcodeRows, storeRows ] = await Promise.all([
stockIds.length > 0
? ctx.model.StockWarehouse.findAll({
where: {
id: stockIds,
},
attributes: [ 'id', 'item_name', 'item_code' ],
raw: true,
})
: [],
stockIds.length > 0
? ctx.model.StockBarcode.findAll({
where: {
stock_id: stockIds,
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
})
: [],
storeIdList.length > 0
? ctx.model.Store.findAll({
where: {
id: storeIdList,
},
attributes: [ 'id', 'company_name' ],
raw: true,
})
: [],
]);
const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
// 复用 getStockDetails 获取商品名称和条码
const stockMap = new Map();
const barcodesByStock = new Map();
for (const row of barcodeRows) {
const stockId = Number(row.stock_id);
const barcode = row.barcode ? String(row.barcode).trim() : '';
if (!stockId || !barcode) {
continue;
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{}
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
stockMap.set(sid, {
id: sid,
item_name: detail.item_name,
item_code: detail.item_code,
});
// 提取条码
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
const barcodeSet = new Set();
for (const bc of detail.barcodes) {
const barcode = String(bc.barcode || '').trim();
if (barcode) {
barcodeSet.add(barcode);
}
}
barcodesByStock.set(sid, barcodeSet);
}
}
if (!barcodesByStock.has(stockId)) {
barcodesByStock.set(stockId, new Set());
}
barcodesByStock.get(stockId).add(barcode);
}
const storeRows = storeIdList.length > 0
? await ctx.model.Store.findAll({
where: {
id: storeIdList,
},
attributes: [ 'id', 'company_name' ],
raw: true,
})
: [];
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
const list = groupedList
.map(item => {
const stock = stockMap.get(item.stock_id) || {};
@ -1171,25 +1162,36 @@ class StorageReportService extends Service {
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
: [];
const [ stockRows, barcodeRows, storeRows, spaceRows ] = await Promise.all([
stockIds.length > 0
? ctx.model.StockWarehouse.findAll({
where: {
id: stockIds,
},
attributes: [ 'id', 'item_name', 'item_code' ],
raw: true,
})
: [],
stockIds.length > 0
? ctx.model.StockBarcode.findAll({
where: {
stock_id: stockIds,
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
})
: [],
// 复用 getStockDetails 获取商品名称和条码
const stockMap = new Map();
const barcodesByStock = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
stockIds,
{}
);
for (const detail of stockDetails) {
const sid = Number(detail.id);
stockMap.set(sid, {
id: sid,
item_name: detail.item_name,
item_code: detail.item_code,
});
// 提取条码
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
const barcodeSet = new Set();
for (const bc of detail.barcodes) {
const barcode = String(bc.barcode || '').trim();
if (barcode) {
barcodeSet.add(barcode);
}
}
barcodesByStock.set(sid, barcodeSet);
}
}
}
const [ storeRows, spaceRows ] = await Promise.all([
storeIdList.length > 0
? ctx.model.Store.findAll({
where: {
@ -1210,22 +1212,8 @@ class StorageReportService extends Service {
: [],
]);
const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ]));
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
const barcodesByStock = new Map();
for (const row of barcodeRows) {
const stockId = Number(row.stock_id);
const barcode = row.barcode ? String(row.barcode).trim() : '';
if (!stockId || !barcode) {
continue;
}
if (!barcodesByStock.has(stockId)) {
barcodesByStock.set(stockId, new Set());
}
barcodesByStock.get(stockId).add(barcode);
}
const list = groupedList
.map(item => {

View File

@ -0,0 +1,185 @@
'use strict';
const Service = require('egg').Service;
/**
* 仓库商品详情缓存的 key 前缀模板。
* 最终 key 格式:cache:stock_detail:{warehouseId}:{stockId}
*/
const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail';
/** 仓库商品详情缓存默认 TTL(秒) */
const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300;
class StockWarehouseService extends Service {
/**
* 构建仓库商品详情缓存的 Redis key。
* @param {number} warehouseId 仓库ID
* @param {number} stockId 仓库商品ID
* @return {string} 缓存 key
*/
_buildStockDetailCacheKey(warehouseId, stockId) {
return `${STOCK_DETAIL_CACHE_KEY_PREFIX}:${warehouseId}:${stockId}`;
}
/**
* 批量获取仓库商品详情(带缓存)。
* 先按 stockId 逐个查缓存,未命中的批量查数据库,
* 然后将数据库结果写入缓存后合并返回。
* 作为通用公共服务,所有模块均可调用。
*
* @param {number[]} stockIds 要查询的 StockWarehouse ID 列表
* @param {Object} [options={}] 选项
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, image_url: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, barcodes: Array<{id: number, barcode: string, sku_property: string}>}>>} 商品详情列表
*/
async getStockDetails(stockIds, options = {}) {
const { ctx, app } = this;
const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options;
const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id;
if (!Array.isArray(stockIds) || stockIds.length === 0) {
return [];
}
const uniqueStockIds = [ ...new Set(stockIds.map(id => Number(id))) ];
const cacheHits = new Map();
const missedStockIds = [];
// 第一步:逐个查缓存
for (const stockId of uniqueStockIds) {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
const cached = await app.getCacheAsync(cacheKey);
if (cached !== null && cached !== undefined) {
cacheHits.set(stockId, cached);
} else {
missedStockIds.push(stockId);
}
} catch {
// 缓存读取异常时降级为查数据库
missedStockIds.push(stockId);
}
}
// 第二步:批量查数据库(只查未命中的 stockId)
/** @type {Map<number, Object>} */
const dbResults = new Map();
if (missedStockIds.length > 0) {
const stockWhere = { id: { [app.Sequelize.Op.in]: missedStockIds }, is_valid: 'Y' };
if (warehouseId != null) {
stockWhere.warehouse_id = warehouseId;
}
const stockRows = await ctx.model.StockWarehouse.findAll({
where: stockWhere,
attributes: [
'id', 'item_code', 'item_name', 'sku_property',
'quantity', 'locked_quantity', 'is_batch_mgmt',
'is_shelf_life_mgmt', 'image_url', 'is_images',
'store_id', 'packing_requirements', 'stock_unit',
],
raw: true,
});
// 批量查询所有未命中 stockId 的条码
const barcodeRows = await ctx.model.StockBarcode.findAll({
where: { stock_id: { [app.Sequelize.Op.in]: missedStockIds } },
attributes: [ 'id', 'barcode', 'sku_property', 'stock_id' ],
raw: true,
});
// 按 stock_id 分组条码
const barcodeMap = new Map();
for (const row of barcodeRows) {
const sid = row.stock_id;
if (!barcodeMap.has(sid)) {
barcodeMap.set(sid, []);
}
barcodeMap.get(sid).push({
id: row.id,
barcode: row.barcode,
sku_property: row.sku_property,
});
}
// 组装每个 stock 的完整详情
for (const row of stockRows) {
const detail = {
id: row.id,
item_code: row.item_code,
item_name: row.item_name,
sku_property: row.sku_property || '',
quantity: row.quantity || 0,
locked_quantity: row.locked_quantity || 0,
is_batch_mgmt: row.is_batch_mgmt || 'N',
is_shelf_life_mgmt: row.is_shelf_life_mgmt || 'N',
image_url: row.image_url || '',
is_images: row.is_images || 'N',
store_id: row.store_id != null ? Number(row.store_id) : 0,
packing_requirements: row.packing_requirements || '',
stock_unit: row.stock_unit || '',
barcodes: barcodeMap.get(row.id) || [],
};
dbResults.set(row.id, detail);
// 第三步:写入缓存
const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id);
try {
await app.setCacheAsync(cacheKey, detail, cacheTTL);
} catch {
// 缓存写入失败不影响主流程
}
}
// 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透
for (const stockId of missedStockIds) {
if (!dbResults.has(stockId)) {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
// 用较短的 TTL 缓存空结果,避免缓存穿透
await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60));
} catch {
// 忽略缓存写入失败
}
}
}
}
// 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序
const result = [];
for (const stockId of uniqueStockIds) {
if (cacheHits.has(stockId)) {
const cached = cacheHits.get(stockId);
// 空标记(防穿透缓存)跳过
if (cached !== null && cached !== undefined) {
result.push(cached);
}
} else if (dbResults.has(stockId)) {
result.push(dbResults.get(stockId));
}
}
return result;
}
/**
* 使指定仓库商品的详情缓存失效。
* 在商品资料更新、图片变更、条码变更时调用。
*
* @param {number} stockId 仓库商品ID
* @param {number} warehouseId 仓库ID
* @return {Promise<void>}
*/
async invalidateStockDetailCache(stockId, warehouseId) {
const { app } = this;
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
await app.delCacheAsync(cacheKey);
} catch {
// 删除缓存失败不影响主流程
}
}
}
module.exports = StockWarehouseService;

View File

@ -0,0 +1,27 @@
# 商品明细缓存公共服务(stock_warehouse.js)
## 文件位置
`app/service/systems/stock_warehouse.js`
## 对外方法
### `getStockDetails(stockIds, options)`
批量获取仓库商品详情(含 StockWarehouse + StockBarcode + 图片),带 Redis 缓存,差量增补。
- **缓存 key**:`cache:stock_detail:{warehouseId}:{stockId}`
- **TTL 默认**:300 秒
- **调用方式**:
```js
ctx.service.systems.stock_warehouse.getStockDetails(stockIds, { warehouseId, cacheTTL })
```
### `invalidateStockDetailCache(stockId, warehouseId)`
清除指定商品缓存。
- **调用时机**:商品资料更新、图片变更、条码变更时调用
### `_buildStockDetailCacheKey(warehouseId, stockId)`
内部工具方法,构建缓存 key。
## 设计思想
作为仓库级公共服务,入库单、出库单、盘点、移库等所有模块都可以复用这个缓存方法,避免各处重复查询 StockWarehouse + StockBarcode。

View File

@ -4082,5 +4082,22 @@
"storage.entry.create / addDetail / deleteDetail / detailChange:systems 层方法已删除,但从未在 system.json 中暴露为 API method,无需文档变更。"
],
"type": "removed"
},
{
"version": "2026.06.23-system-17",
"date": "2026-06-23",
"summary": "storage.entry.get 响应新增仓库库存、条码、入库进度字段",
"methods": [
"storage.entry.get"
],
"notes": [
"items 每项新增 warehouse_quantity(仓库库存总量)、warehouse_locked_quantity(锁定数量)、warehouse_is_batch_mgmt(是否批次管理)、warehouse_is_shelf_life_mgmt(是否效期管理)、warehouse_image_url(商品图片URL)、warehouse_is_images(是否有图片)",
"items 每项新增 barcodes(条码列表,每项含 id/barcode/sku_property)",
"items 每项新增 direct_inbound_quantity(导入/PDA已入库数量)、remaining_quantity(剩余可入库数量)",
"同步更新 response 字段定义,将原有概要描述展开为逐字段说明",
"仅文档同步,不改业务代码"
],
"type": "updated",
"module": "storage.entry"
}
]

View File

@ -19070,7 +19070,115 @@
"name": "entryOrder",
"type": "object",
"required": true,
"description": "入库单详情,包含 items 数组(每项含 external_item_code/external_item_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec 等字段)、receivingBindings(主表级收货单关联数组,每项含 id/receiving_id/receiving,其中 receiving 含 id/receiving_number/status/storage_status/created_at)"
"description": "入库单详情,包含 items 数组和 receivingBindings(主表级收货单关联数组)。items 每项含 external_item_code / external_item_id / warehouse_item_code / warehouse_item_name / warehouse_item_spec / count / received_quantity / confirm_quantity / warehouse_quantity / warehouse_locked_quantity / warehouse_is_batch_mgmt / warehouse_is_shelf_life_mgmt / warehouse_image_url / warehouse_is_images / barcodes / direct_inbound_quantity / remaining_quantity"
},
{
"name": "entryOrder.items[].external_item_code",
"type": "string",
"required": true,
"description": "外部商品编码"
},
{
"name": "entryOrder.items[].external_item_id",
"type": "number",
"required": true,
"description": "外部商品ID"
},
{
"name": "entryOrder.items[].warehouse_item_code",
"type": "string",
"required": true,
"description": "仓库商品编码"
},
{
"name": "entryOrder.items[].warehouse_item_name",
"type": "string",
"required": true,
"description": "仓库商品名称"
},
{
"name": "entryOrder.items[].warehouse_item_spec",
"type": "string",
"required": true,
"description": "仓库商品规格(sku_property)"
},
{
"name": "entryOrder.items[].count",
"type": "number",
"required": true,
"description": "计划入库数量"
},
{
"name": "entryOrder.items[].received_quantity",
"type": "number",
"required": true,
"description": "已收货数量(收货单途径)"
},
{
"name": "entryOrder.items[].confirm_quantity",
"type": "number",
"required": true,
"description": "已确认收货数量"
},
{
"name": "entryOrder.items[].warehouse_quantity",
"type": "number",
"required": true,
"description": "仓库当前库存总量(StockWarehouse.quantity)"
},
{
"name": "entryOrder.items[].warehouse_locked_quantity",
"type": "number",
"required": true,
"description": "仓库锁定数量(StockWarehouse.locked_quantity)"
},
{
"name": "entryOrder.items[].warehouse_is_batch_mgmt",
"type": "string",
"required": true,
"description": "是否批次管理(StockWarehouse.is_batch_mgmt),Y/N"
},
{
"name": "entryOrder.items[].warehouse_is_shelf_life_mgmt",
"type": "string",
"required": true,
"description": "是否效期管理(StockWarehouse.is_shelf_life_mgmt),Y/N"
},
{
"name": "entryOrder.items[].warehouse_image_url",
"type": "string",
"required": true,
"description": "商品图片 URL(StockWarehouse.image_url)"
},
{
"name": "entryOrder.items[].warehouse_is_images",
"type": "number",
"required": true,
"description": "是否有图片(StockWarehouse.is_images),0/1"
},
{
"name": "entryOrder.items[].barcodes",
"type": "array",
"required": true,
"description": "条码列表,每项含 { id, barcode, sku_property }"
},
{
"name": "entryOrder.items[].direct_inbound_quantity",
"type": "number",
"required": true,
"description": "导入/PDA 已入库数量(InboundDirectLog 聚合)"
},
{
"name": "entryOrder.items[].remaining_quantity",
"type": "number",
"required": true,
"description": "剩余可入库数量(count - received_quantity - direct_inbound_quantity,最小为 0)"
},
{
"name": "entryOrder.receivingBindings",
"type": "array",
"required": true,
"description": "主表级收货单关联数组,每项含 id / receiving_id / receiving(receiving 含 id / receiving_number / status / storage_status / created_at)"
}
],
"errors": [

BIN
temp_storage_entry_old.js Normal file

Binary file not shown.

Binary file not shown.