186 lines
6.6 KiB
JavaScript
186 lines
6.6 KiB
JavaScript
'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;
|