'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}>>} 商品详情列表 */ 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} */ 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', 'pick_requirements', 'recheck_requirements', 'merge_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 || '', pick_requirements: (row.merge_requirements || 'Y') === 'Y' ? (row.packing_requirements || '') : (row.pick_requirements || ''), recheck_requirements: (row.merge_requirements || 'Y') === 'Y' ? (row.packing_requirements || '') : (row.recheck_requirements || ''), merge_requirements: row.merge_requirements || 'Y', 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'; } // 兼容旧缓存:无要求合并开关时按默认合并处理;无拣货/复核要求时按合并规则回退为打包要求 if (cached && cached.merge_requirements == null) { cached.merge_requirements = 'Y'; } if (cached && cached.pick_requirements == null) { cached.pick_requirements = (cached.merge_requirements || 'Y') === 'Y' ? (cached.packing_requirements || '') : ''; } if (cached && cached.recheck_requirements == null) { cached.recheck_requirements = (cached.merge_requirements || 'Y') === 'Y' ? (cached.packing_requirements || '') : ''; } 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 { // 删除缓存失败不影响主流程 } } /** * 读取商品库存预警数量(内部方法)。 * * 优先级: * 1. 商品单独设置了预警数量(warning_quantity > 0)→ 取商品设置数; * 2. 货主(stock.store_id 对应 wms_store)开启库存预警(stock_warning_enabled) * 且配置了预警数量(stock_warning_quantity > 0)→ 取货主设置数; * 3. 以上均不满足 → 返回 0(不预警)。 * * @param {number|string} stockId 仓库商品ID(wms_stock_warehouse.id)。 * @return {Promise} 库存预警数量(非负整数),读取异常时返回 0。 */ async getStockWarningQuantity(stockId) { const { ctx } = this; const normalizedStockId = Number(stockId || 0); if (!Number.isFinite(normalizedStockId) || normalizedStockId <= 0) { return 0; } try { const stockModel = ctx.model && ctx.model.StockWarehouse; if (!stockModel || typeof stockModel.findOne !== 'function') { return 0; } const stock = await stockModel.findOne({ where: { id: normalizedStockId, is_valid: 'Y', deleted_at: null }, attributes: [ 'id', 'store_id', 'warning_quantity' ], raw: true, }); if (!stock) { return 0; } // 商品单独设置优先 const productWarningQuantity = Number(stock.warning_quantity || 0); if (Number.isInteger(productWarningQuantity) && productWarningQuantity > 0) { return productWarningQuantity; } // 货主配置:开启且数量 > 0 才生效 const storeId = Number(stock.store_id || 0); if (storeId > 0) { const storeModel = ctx.model && ctx.model.Store; if (storeModel && typeof storeModel.findByPk === 'function') { const store = await storeModel.findByPk(storeId, { attributes: [ 'id', 'subject_config' ], raw: true, }); const subjectConfig = store && store.subject_config ? store.subject_config : {}; const enabled = subjectConfig.stock_warning_enabled === true || subjectConfig.stock_warning_enabled === 1 || String(subjectConfig.stock_warning_enabled || '').trim().toLowerCase() === 'true'; const storeWarningQuantity = Number(subjectConfig.stock_warning_quantity || 0); if (enabled && Number.isInteger(storeWarningQuantity) && storeWarningQuantity > 0) { return storeWarningQuantity; } } } return 0; } catch (err) { ctx.logger && ctx.logger.warn && ctx.logger.warn( `[stockWarehouse.getStockWarningQuantity] 读取库存预警数量失败 stockId=${normalizedStockId}: ${err && err.message}` ); return 0; } } /** * 查询静态商品列表(仓库级)。 * * 静态判定:商品最后一个收(INBOUND)/发(OUTBOUND)流水时间超过阈值小时数 * 即视为进入静态;无收发流水记录的商品以创建时间(create_at)为基准。 * 阈值优先取入参 hours,缺省读仓库配置 subject_config.stock_static_hours(默认 168 小时)。 * * @param {Object} [options={}] 选项。 * @param {number} [options.warehouseId] 仓库ID,缺省取 ctx.user.store_id。 * @param {number} [options.hours] 静态时间阈值(小时),缺省读仓库配置。 * @param {number} [options.page=1] 页码。 * @param {number} [options.pageSize=20] 每页条数。 * @return {Promise<{list: Array, pagination: {page:number, pageSize:number, total:number, totalPages:number}}>} * list 每项含 id/item_code/item_name/sku_property/stock_unit/store_id/quantity/locked_quantity/ * gross_weight/warning_quantity/create_at/last_flow_at/static_hours/is_static。 */ async getStaticStockList(options = {}) { const { ctx } = this; const requestData = options && typeof options === 'object' ? options : {}; const warehouseId = Number(requestData.warehouseId || (ctx.user && ctx.user.store_id) || 0); const page = Number(requestData.page || 1) > 0 ? Math.floor(Number(requestData.page)) : 1; const pageSize = Number(requestData.pageSize || 20) > 0 ? Math.min(500, Math.floor(Number(requestData.pageSize))) : 20; const emptyPagination = { page, pageSize, total: 0, totalPages: 0, }; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { return { list: [], pagination: emptyPagination }; } // 阈值小时数:入参优先,否则仓库配置(默认 168) let staticHours = Number(requestData.hours); if (!Number.isFinite(staticHours) || staticHours <= 0) { staticHours = 168; try { const storeModel = ctx.model && ctx.model.Store; if (storeModel && typeof storeModel.findByPk === 'function') { const store = await storeModel.findByPk(warehouseId, { attributes: [ 'id', 'subject_config' ], raw: true, }); const subjectConfig = store && store.subject_config ? store.subject_config : {}; const configHours = Number(subjectConfig.stock_static_hours || 0); if (Number.isFinite(configHours) && configHours > 0) { staticHours = configHours; } } } catch (err) { ctx.logger && ctx.logger.warn && ctx.logger.warn( `[stockWarehouse.getStaticStockList] 读取仓库静态时间配置失败,按默认 168 小时: ${err && err.message}` ); } } const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); const fromSql = ` FROM wms_stock_warehouse sw LEFT JOIN ( SELECT stock_id, MAX(last_flow_at) AS last_flow_at FROM ( SELECT stock_id, MAX(created_at) AS last_flow_at FROM wms_stock_transaction WHERE warehouse_id = :warehouseId AND transaction_type = 'INBOUND' GROUP BY stock_id UNION ALL SELECT stock_id, MAX(created_at) AS last_flow_at FROM wms_stock_transaction WHERE warehouse_id = :warehouseId AND transaction_type = 'OUTBOUND' GROUP BY stock_id ) flow_union GROUP BY stock_id ) t ON t.stock_id = sw.id WHERE sw.warehouse_id = :warehouseId AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff `; const listSql = ` SELECT sw.id, sw.item_code, sw.item_name, sw.sku_property, sw.stock_unit, sw.store_id, sw.quantity, sw.locked_quantity, sw.gross_weight, sw.warning_quantity, sw.create_at, t.last_flow_at ${fromSql} ORDER BY COALESCE(t.last_flow_at, sw.create_at) ASC LIMIT :limit OFFSET :offset `; const countSql = ` SELECT COUNT(1) AS total ${fromSql} `; const { QueryTypes } = ctx.model; const baseReplacements = { warehouseId, cutoff, }; const offset = (page - 1) * pageSize; const [ countRows, listRows ] = await Promise.all([ ctx.model.query(countSql, { replacements: baseReplacements, type: QueryTypes.SELECT, }), ctx.model.query(listSql, { replacements: { ...baseReplacements, limit: pageSize, offset }, type: QueryTypes.SELECT, }), ]); const total = Number( (Array.isArray(countRows) && countRows.length > 0 ? countRows[0].total : 0) || 0 ); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ id: Number(row && row.id || 0), item_code: String(row && row.item_code || '').trim(), item_name: String(row && row.item_name || '').trim(), sku_property: String(row && row.sku_property || '').trim(), stock_unit: String(row && row.stock_unit || '').trim(), store_id: row && row.store_id != null ? Number(row.store_id) : 0, quantity: Number(row && row.quantity || 0), locked_quantity: Number(row && row.locked_quantity || 0), gross_weight: Number(row && row.gross_weight || 0), warning_quantity: Number(row && row.warning_quantity || 0), create_at: row && row.create_at ? row.create_at : null, last_flow_at: row && row.last_flow_at ? row.last_flow_at : null, static_hours: staticHours, is_static: true, })); return { list, pagination: { page, pageSize, total, totalPages, }, }; } } module.exports = StockWarehouseService;