'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}>>} 商品详情列表 */ 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 = []; // 第一步:逐个查缓存 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} */ 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 的完整详情 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); // 第三步:写入缓存 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) { // 兼容旧缓存格式: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} */ async invalidateStockDetailCache(stockId, warehouseId) { const { app } = this; const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId); try { await app.delCacheAsync(cacheKey); } catch { // 删除缓存失败不影响主流程 } } } module.exports = StockWarehouseService;