WMS_MAIN/app/service/systems/stock_warehouse.js
liufumingren 510b87632a feat(stock): 库存/仓库模块货主侧查询与报表增强
- stock/warehouse: 新增 externalList/externalExport(外仓/货主维度查询)

- storeWarehouse/store: 新增货主侧接口(list/get 等)

- stock_store: getWarehouseStock 支持 externalWarehouseId/externalStoreId

- store_warehouse: 合同关系改为单向维度查询(不再 OR 两边)

- storage/report: 库存报表支持 store 维度 + stockIds/keyword 精确筛选

- stock/transaction: storeList/exportStore store_id 从 ctx 获取防越权

- stock_warehouse: getStockDetails 支持显式传 null 跳过仓库过滤

- storage/management: 储位分配待处理排除待审核(step=1)订单
2026-07-27 03:48:06 +08:00

221 lines
7.9 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;
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;
// 用 !== 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<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,
}],
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',
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 = [];
}
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;