WMS_MAIN/app/service/systems/stock_warehouse.js
liufumingren 95067aeb8a feat(wms): 工作台成员、波次范围、库存明细与报表修复等多项更新
- workbench: 工作台成员拆分 wms_workbench_member 表,下线 barcode 字段,新增绑定/移除成员接口

- order: 订单配送新增 wave_scope 波次范围字段与历史回填,自动分配快递排除备注与储位分配限制修复

- storage.transaction.list: 重写为 wms_storage_transaction 逐条明细查询,消除聚合慢查询

- stock.report: 分页默认生效、排序白名单扩充、where.stock_id 数组兼容修复

- storage.entry: quickInbound/commit 新增 noNeedNotice 通知开关

- storage.inventory.list: stock_query 支持数组多关键字并集匹配

- store: 手工单回传通知策略 notify_manual_sync

- docs: 同步接口文档与变更记录、路由表;test: 补充快递排除与储位分配限制测试
2026-09-05 22:43:38 +08:00

241 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;
/** 缓存读取并发批大小 */
const CACHE_READ_BATCH_SIZE = 200;
/** 缓存写入并发批大小 */
const CACHE_WRITE_BATCH_SIZE = 100;
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, need_recheck: 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;
// 用 !== undefined 代替 != null:显式传 null 表示跳过 warehouse 过滤(如货主侧查询)
const warehouseId = options.warehouseId !== undefined ? 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 = [];
// 第一步:分批并发查缓存(避免逐个串行 await 叠加 N 次 Redis 往返延迟)
for (let i = 0; i < uniqueStockIds.length; i += CACHE_READ_BATCH_SIZE) {
const batch = uniqueStockIds.slice(i, i + CACHE_READ_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(async stockId => {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
const cached = await app.getCacheAsync(cacheKey);
return { stockId, cached, hit: cached !== null && cached !== undefined };
} catch {
// 缓存读取异常时降级为查数据库
return { stockId, cached: null, hit: false };
}
}));
for (const item of batchResults) {
if (item.hit) {
cacheHits.set(item.stockId, item.cached);
} else {
missedStockIds.push(item.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', 'need_recheck',
'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,
}],
order: [[ 'display_order', 'ASC' ]],
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)) {
imageUrlMap.set(sid, []);
}
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
if (url) {
imageUrlMap.get(sid).push(url);
}
}
// 组装每个 stock 的完整详情,并收集缓存写入任务
const cacheWriteTasks = [];
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',
need_recheck: row.need_recheck || 'Y',
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);
// 第三步:写入缓存(收集任务,稍后统一分批并发执行)
cacheWriteTasks.push({
key: this._buildStockDetailCacheKey(warehouseId, row.id),
value: detail,
ttl: cacheTTL,
});
}
// 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透
for (const stockId of missedStockIds) {
if (!dbResults.has(stockId)) {
cacheWriteTasks.push({
key: this._buildStockDetailCacheKey(warehouseId, stockId),
value: null,
// 用较短的 TTL 缓存空结果,避免缓存穿透
ttl: Math.min(cacheTTL, 60),
});
}
}
// 分批并发写缓存(缓存写入失败不影响主流程)
for (let i = 0; i < cacheWriteTasks.length; i += CACHE_WRITE_BATCH_SIZE) {
const batch = cacheWriteTasks.slice(i, i + CACHE_WRITE_BATCH_SIZE);
await Promise.all(batch.map(task => app.setCacheAsync(task.key, task.value, task.ttl).catch(() => {})));
}
}
// 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序
const result = [];
for (const stockId of uniqueStockIds) {
if (cacheHits.has(stockId)) {
const cached = cacheHits.get(stockId);
// 空标记(防穿透缓存)跳过
if (cached !== null && cached !== undefined) {
// 兼容旧缓存格式:image_url 可能是字符串,统一转为数组
if (cached && typeof cached.image_url === 'string') {
cached.image_url = cached.image_url ? [ cached.image_url ] : [];
}
if (cached && !Array.isArray(cached.image_url)) {
cached.image_url = [];
}
// 兼容旧缓存:无 need_recheck 时补默认(需要复核)
if (cached && cached.need_recheck == null) {
cached.need_recheck = 'Y';
}
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;