- 跨仓 bug 修复:order_express 读取强制校验订单所属仓库 id(order.detail 与全部订单列表等 17 处) - recheckOrder 原生 SQL 表名补 wms_ 前缀,修复 queryRecheckOrderSingleList 恒 500 - 同步 methods 文档与变更记录
1732 lines
64 KiB
JavaScript
1732 lines
64 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* 将输入转换为时间戳。
|
||
* @param {string|Date|number|null|undefined} value 时间值
|
||
* @return {number|null} 时间戳,无法解析时返回 null
|
||
*/
|
||
function toTimeMs(value) {
|
||
if (value === undefined || value === null || value === '') {
|
||
return null;
|
||
}
|
||
|
||
const date = value instanceof Date ? value : new Date(value);
|
||
const time = date.getTime();
|
||
return Number.isNaN(time) ? null : time;
|
||
}
|
||
|
||
/**
|
||
* 归一化布尔值。
|
||
* @param {boolean|string|number|null|undefined} value 原始值
|
||
* @return {boolean} 归一化后的布尔值
|
||
*/
|
||
function normalizeBoolean(value) {
|
||
if (typeof value === 'boolean') {
|
||
return value;
|
||
}
|
||
|
||
if (typeof value === 'number') {
|
||
return value === 1;
|
||
}
|
||
|
||
if (typeof value === 'string') {
|
||
const normalized = value.trim().toLowerCase();
|
||
return [ '1', 'true', 'y', 'yes', '是' ].includes(normalized);
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 归一化货主ID数组。
|
||
* @param {Array<number|string>|number|string|null|undefined} rawStoreIds 原始货主ID
|
||
* @return {number[]} 归一化后的货主ID数组
|
||
*/
|
||
function normalizeStoreIds(rawStoreIds) {
|
||
const list = Array.isArray(rawStoreIds) ? rawStoreIds : [ rawStoreIds ];
|
||
return [ ...new Set(
|
||
list
|
||
.map(item => Number(item))
|
||
.filter(item => Number.isInteger(item) && item > 0)
|
||
) ];
|
||
}
|
||
|
||
/**
|
||
* 数值安全转换。
|
||
* @param {unknown} value 原始值
|
||
* @return {number} 数值
|
||
*/
|
||
function toNumber(value) {
|
||
const num = Number(value);
|
||
return Number.isFinite(num) ? num : 0;
|
||
}
|
||
|
||
/**
|
||
* 将时间值格式化为日期令牌。
|
||
* @param {string|Date|number|null|undefined} value 时间值
|
||
* @return {string} yyyymmdd 格式日期,无法解析时返回空字符串
|
||
*/
|
||
function formatDateToken(value) {
|
||
const timeMs = toTimeMs(value);
|
||
if (timeMs === null) {
|
||
return '';
|
||
}
|
||
|
||
const date = new Date(timeMs);
|
||
const year = String(date.getFullYear());
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
return `${year}${month}${day}`;
|
||
}
|
||
|
||
/**
|
||
* 将时间值格式化为统一可读字符串。
|
||
* @param {string|Date|number|null|undefined} value 时间值
|
||
* @return {string} yyyy-mm-dd hh:mm:ss 格式字符串
|
||
*/
|
||
function formatDateTime(value) {
|
||
const timeMs = toTimeMs(value);
|
||
if (timeMs === null) {
|
||
return '';
|
||
}
|
||
|
||
const date = new Date(timeMs);
|
||
const year = String(date.getFullYear());
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
const hour = String(date.getHours()).padStart(2, '0');
|
||
const minute = String(date.getMinutes()).padStart(2, '0');
|
||
const second = String(date.getSeconds()).padStart(2, '0');
|
||
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
|
||
}
|
||
|
||
/**
|
||
* 将库存流水类型转换为中文显示。
|
||
* @param {string|null|undefined} transactionType 流水类型
|
||
* @return {string} 中文类型,未知值返回去除前后空白后的原始内容
|
||
*/
|
||
function formatTransactionType(transactionType) {
|
||
const rawType = typeof transactionType === 'string' ? transactionType.trim() : String(transactionType || '').trim();
|
||
const normalizedType = rawType.toUpperCase();
|
||
|
||
if (normalizedType === 'INBOUND') {
|
||
return '入库';
|
||
}
|
||
|
||
if (normalizedType === 'OUTBOUND') {
|
||
return '出库';
|
||
}
|
||
|
||
if (normalizedType === 'TRANSFER_OUT') {
|
||
return '移库出';
|
||
}
|
||
|
||
if (normalizedType === 'TRANSFER_IN') {
|
||
return '移库入';
|
||
}
|
||
|
||
if (normalizedType === 'LOCK') {
|
||
return '锁定';
|
||
}
|
||
|
||
return rawType;
|
||
}
|
||
|
||
const SORT_FIELD_WHITE_LIST = new Set([ 'stock_id', 'item_code', 'item_name', 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]);
|
||
|
||
/** 字符串排序字段集合(按字典序比较),其余白名单字段按数值比较 */
|
||
const STRING_SORT_FIELD_SET = new Set([ 'item_code', 'item_name' ]);
|
||
|
||
/**
|
||
* 归一化排序参数。
|
||
* @param {Object|null|undefined} sort 排序入参
|
||
* @param {string} [sort.sortField] 排序字段(白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total)
|
||
* @param {string} [sort.sortOrder] 排序顺序
|
||
* @return {{sortField: string, sortOrder: 'ASC'|'DESC'}|null} 合法排序参数
|
||
*/
|
||
function normalizeSort(sort) {
|
||
if (!sort || typeof sort !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const rawSortField = typeof sort.sortField === 'string' ? sort.sortField.trim() : '';
|
||
const rawSortOrder = typeof sort.sortOrder === 'string' ? sort.sortOrder.trim().toUpperCase() : '';
|
||
if (!SORT_FIELD_WHITE_LIST.has(rawSortField)) {
|
||
return null;
|
||
}
|
||
|
||
if (rawSortOrder !== 'ASC' && rawSortOrder !== 'DESC') {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
sortField: rawSortField,
|
||
sortOrder: rawSortOrder,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 默认排序比较器。
|
||
* @param {Object} a 列表项A
|
||
* @param {Object} b 列表项B
|
||
* @param {boolean} isBySpace 是否按库位输出
|
||
* @return {number} 比较结果
|
||
*/
|
||
function compareByDefaultOrder(a, b, isBySpace) {
|
||
if (a.store_id !== b.store_id) {
|
||
return a.store_id - b.store_id;
|
||
}
|
||
|
||
if (a.stock_id !== b.stock_id) {
|
||
return a.stock_id - b.stock_id;
|
||
}
|
||
|
||
if (!isBySpace) {
|
||
return 0;
|
||
}
|
||
|
||
return Number(a.space_id || 0) - Number(b.space_id || 0);
|
||
}
|
||
|
||
/**
|
||
* 对最终结果做统一排序。
|
||
* @param {Object[]} list 原始结果列表
|
||
* @param {boolean} isBySpace 是否按库位输出
|
||
* @param {Object|null|undefined} sort 排序参数
|
||
* @return {Object[]} 排序后的结果列表
|
||
*/
|
||
function sortReportList(list, isBySpace, sort) {
|
||
const normalizedSort = normalizeSort(sort);
|
||
if (!normalizedSort) {
|
||
return list.sort((a, b) => compareByDefaultOrder(a, b, isBySpace));
|
||
}
|
||
|
||
const { sortField, sortOrder } = normalizedSort;
|
||
const direction = sortOrder === 'DESC' ? -1 : 1;
|
||
const isStringSort = STRING_SORT_FIELD_SET.has(sortField);
|
||
|
||
return list.sort((a, b) => {
|
||
let cmp;
|
||
if (isStringSort) {
|
||
cmp = String(a[sortField] || '').localeCompare(String(b[sortField] || ''));
|
||
} else {
|
||
const aValue = toNumber(a[sortField]);
|
||
const bValue = toNumber(b[sortField]);
|
||
cmp = aValue === bValue ? 0 : aValue - bValue;
|
||
}
|
||
if (cmp !== 0) {
|
||
return cmp * direction;
|
||
}
|
||
return compareByDefaultOrder(a, b, isBySpace);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 根据区间流水构建“首条before、末条after”的快照映射。
|
||
* @param {Object[]} rows 区间流水列表
|
||
* @param {(row: Object) => string|null} resolveKey 键解析函数
|
||
* @return {Map<string, {begin_total: number, end_total: number, has_snapshot: boolean}>} 快照映射
|
||
*/
|
||
function buildIntervalEdgeMap(rows, resolveKey) {
|
||
const edgeMap = new Map();
|
||
const safeRows = Array.isArray(rows) ? rows : [];
|
||
|
||
for (const row of safeRows) {
|
||
const key = resolveKey(row);
|
||
if (!key) {
|
||
continue;
|
||
}
|
||
|
||
const beforeQuantity = toNumber(row.before_quantity);
|
||
const afterQuantity = toNumber(row.after_quantity);
|
||
|
||
if (!edgeMap.has(key)) {
|
||
edgeMap.set(key, {
|
||
begin_total: beforeQuantity,
|
||
end_total: afterQuantity,
|
||
has_snapshot: true,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
const snapshot = edgeMap.get(key);
|
||
snapshot.end_total = afterQuantity;
|
||
}
|
||
|
||
return edgeMap;
|
||
}
|
||
|
||
/**
|
||
* 根据 start_time 之前流水构建“最近一条 after”的期初快照映射。
|
||
* @param {Object[]} rows start_time 之前流水列表
|
||
* @param {(row: Object) => string|null} resolveKey 键解析函数
|
||
* @return {Map<string, number>} 期初快照映射
|
||
*/
|
||
function buildPreStartAfterMap(rows, resolveKey) {
|
||
const latestSnapshotMap = new Map();
|
||
const safeRows = Array.isArray(rows) ? rows : [];
|
||
|
||
for (const row of safeRows) {
|
||
const key = resolveKey(row);
|
||
if (!key) {
|
||
continue;
|
||
}
|
||
|
||
const createdAtMs = toTimeMs(row.created_at);
|
||
const rowId = toNumber(row.id);
|
||
const current = latestSnapshotMap.get(key);
|
||
if (!current) {
|
||
latestSnapshotMap.set(key, {
|
||
after_quantity: toNumber(row.after_quantity),
|
||
created_at_ms: createdAtMs,
|
||
id: rowId,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
const currentCreatedAtMs = current.created_at_ms;
|
||
const shouldReplace = (createdAtMs !== null && currentCreatedAtMs === null)
|
||
|| (createdAtMs !== null && currentCreatedAtMs !== null && createdAtMs > currentCreatedAtMs)
|
||
|| (createdAtMs === currentCreatedAtMs && rowId > current.id);
|
||
|
||
if (shouldReplace) {
|
||
current.after_quantity = toNumber(row.after_quantity);
|
||
current.created_at_ms = createdAtMs;
|
||
current.id = rowId;
|
||
}
|
||
}
|
||
|
||
const snapshotMap = new Map();
|
||
for (const [ key, value ] of latestSnapshotMap.entries()) {
|
||
snapshotMap.set(key, toNumber(value.after_quantity));
|
||
}
|
||
|
||
return snapshotMap;
|
||
}
|
||
|
||
/**
|
||
* 将 SQL WHERE 子句数组中的表别名 t. 重绑定为指定别名,便于在派生表子查询中复用同一组条件。
|
||
* @param {string[]} clauses WHERE 子句数组
|
||
* @param {string} alias 目标表别名
|
||
* @return {string[]} 重绑定后的子句数组
|
||
*/
|
||
function rebindTableAlias(clauses, alias) {
|
||
return clauses.map(clause => String(clause).replace(/\bt\./g, `${alias}.`));
|
||
}
|
||
|
||
/** 默认分页每页条数 */
|
||
const DEFAULT_PAGE_SIZE = 20;
|
||
/** 导出全量分页大小(导出必须全量,避免默认分页截断汇总与明细) */
|
||
const EXPORT_FULL_PAGE_SIZE = 1000000;
|
||
|
||
/**
|
||
* 对已排序的结果列表做内存分页切片。
|
||
* 分页参数未传或非法时回退默认分页:page=1、pageSize=20。
|
||
* @param {Object[]} list 已排序列表
|
||
* @param {Object|null|undefined} pagination 分页参数 { page, pageSize }(兼容 page_size)
|
||
* @return {{items: Object[], meta: {page: number, pageSize: number, total: number, totalPages: number, hasPrevious: boolean, hasNext: boolean}}} 分页结果
|
||
*/
|
||
function paginateList(list, pagination) {
|
||
const hasPagination = pagination && typeof pagination === 'object';
|
||
const rawPage = hasPagination ? Number(pagination.page) : NaN;
|
||
const rawPageSize = hasPagination
|
||
? Number(pagination.pageSize !== undefined ? pagination.pageSize : pagination.page_size)
|
||
: NaN;
|
||
|
||
const page = Number.isInteger(rawPage) && rawPage >= 1 ? rawPage : 1;
|
||
const pageSize = Number.isInteger(rawPageSize) && rawPageSize >= 1 ? rawPageSize : DEFAULT_PAGE_SIZE;
|
||
|
||
const total = Array.isArray(list) ? list.length : 0;
|
||
const totalPages = Math.ceil(total / pageSize) || 1;
|
||
const offset = (page - 1) * pageSize;
|
||
const items = list.slice(offset, offset + pageSize);
|
||
|
||
return {
|
||
items,
|
||
meta: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages,
|
||
hasPrevious: page > 1,
|
||
hasNext: page < totalPages,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取报表流水数据源配置。
|
||
* @param {boolean} isBySpace 是否按库位维度统计
|
||
* @return {{tableName: string, spaceSelectSql: string, spaceGroupSql: string, spaceOrderSql: string}} 配置对象
|
||
*/
|
||
function resolveTransactionSourceConfig(isBySpace) {
|
||
if (isBySpace) {
|
||
return {
|
||
tableName: 'wms_storage_transaction',
|
||
// 历史库位流水可能存在空 space_id,统一回退到 0 作为“未知库位”口径,避免统计漏数。
|
||
spaceSelectSql: 'COALESCE(t.space_id, 0) AS space_id',
|
||
spaceGroupSql: ', COALESCE(t.space_id, 0)',
|
||
spaceOrderSql: ', COALESCE(t.space_id, 0) ASC',
|
||
};
|
||
}
|
||
|
||
return {
|
||
tableName: 'wms_stock_transaction',
|
||
spaceSelectSql: '0 AS space_id',
|
||
spaceGroupSql: '',
|
||
spaceOrderSql: '',
|
||
};
|
||
}
|
||
|
||
class StorageReportService extends Service {
|
||
/**
|
||
* 加载库存报表导出所需的名称映射。
|
||
* @param {Object} options 参数
|
||
* @param {number[]} [options.stockIds=[]] 商品库存ID列表
|
||
* @param {number[]} [options.storeIds=[]] 货主ID列表
|
||
* @param {number[]} [options.spaceIds=[]] 库位ID列表
|
||
* @param {boolean} [options.includeBarcode=false] 是否加载条码映射
|
||
* @param {number[]} [options.entryOrderIds=[]] 入库单ID列表
|
||
* @param {number[]} [options.orderIds=[]] 出库单ID列表
|
||
* @param {number|null} [options.warehouseId=null] 仓库ID
|
||
* @param {Map<number, number>} [options.orderWarehouseMap] 订单ID到仓库ID映射(货主模式跨仓库场景下用于运单同仓校验)
|
||
* @return {Promise<Object>} 映射对象
|
||
*/
|
||
async loadReportReferenceMaps({
|
||
stockIds = [],
|
||
storeIds = [],
|
||
spaceIds = [],
|
||
includeBarcode = false,
|
||
entryOrderIds = [],
|
||
orderIds = [],
|
||
warehouseId = null,
|
||
orderWarehouseMap = null,
|
||
} = {}) {
|
||
const { ctx, app } = this;
|
||
const normalizedStockIds = [ ...new Set((stockIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const normalizedEntryOrderIds = [ ...new Set((entryOrderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const normalizedOrderIds = [ ...new Set((orderIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const normalizedWarehouseId = Number(warehouseId);
|
||
|
||
// 从 getStockDetails 获取商品名称、条码信息
|
||
const stockMap = new Map();
|
||
const barcodeMap = new Map();
|
||
if (normalizedStockIds.length > 0) {
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
normalizedStockIds,
|
||
{ warehouseId } // store 模式下为 null → 跳过 warehouse 过滤
|
||
);
|
||
for (const detail of stockDetails) {
|
||
const sid = Number(detail.id);
|
||
stockMap.set(sid, {
|
||
id: sid,
|
||
item_name: detail.item_name,
|
||
item_code: detail.item_code,
|
||
});
|
||
// 提取条码
|
||
if (includeBarcode && Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
||
const barcodeSet = new Set();
|
||
for (const bc of detail.barcodes) {
|
||
const barcode = String(bc.barcode || '').trim();
|
||
if (barcode) {
|
||
barcodeSet.add(barcode);
|
||
}
|
||
}
|
||
barcodeMap.set(sid, barcodeSet);
|
||
}
|
||
}
|
||
}
|
||
|
||
const [ storeRows, spaceRows, entryOrderRows, orderDeliveryRows, orderExpressRows, storeWarehouseRows ] = await Promise.all([
|
||
normalizedStoreIds.length > 0
|
||
? ctx.model.Store.findAll({
|
||
where: {
|
||
id: normalizedStoreIds,
|
||
},
|
||
attributes: [ 'id', 'company_name' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
normalizedSpaceIds.length > 0
|
||
? ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
id: normalizedSpaceIds,
|
||
},
|
||
attributes: [ 'id', 'custom_name', 'space_code' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
normalizedEntryOrderIds.length > 0
|
||
? ctx.model.query(
|
||
'SELECT id, entry_order_code, express_code, logistics_code, logistics_name, source_type FROM wms_entry_order WHERE id IN (:ids)',
|
||
{
|
||
replacements: { ids: normalizedEntryOrderIds },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
}
|
||
)
|
||
: [],
|
||
normalizedOrderIds.length > 0
|
||
? ctx.model.query(
|
||
'SELECT id, source_order_codes FROM wms_order_delivery WHERE id IN (:ids)',
|
||
{
|
||
replacements: { ids: normalizedOrderIds },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
}
|
||
)
|
||
: [],
|
||
normalizedOrderIds.length > 0
|
||
? (async () => {
|
||
// 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||
// 禁止仅凭订单ID跨仓串读运单号。
|
||
// 仓库模式:直接用当前仓库ID过滤;货主模式:按订单所属仓库分组查询。
|
||
const resultRows = [];
|
||
const querySql = 'SELECT order_id, waybill_code FROM wms_order_express WHERE order_id IN (:ids) AND warehouse_id = :warehouseId';
|
||
if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||
resultRows.push(...await ctx.model.query(
|
||
querySql,
|
||
{
|
||
replacements: { ids: normalizedOrderIds, warehouseId: normalizedWarehouseId },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
}
|
||
));
|
||
} else if (orderWarehouseMap instanceof Map && orderWarehouseMap.size > 0) {
|
||
const idsByWarehouse = new Map();
|
||
for (const orderId of normalizedOrderIds) {
|
||
const orderWarehouseId = Number(orderWarehouseMap.get(orderId));
|
||
if (!Number.isInteger(orderWarehouseId) || orderWarehouseId <= 0) {
|
||
continue;
|
||
}
|
||
if (!idsByWarehouse.has(orderWarehouseId)) {
|
||
idsByWarehouse.set(orderWarehouseId, []);
|
||
}
|
||
idsByWarehouse.get(orderWarehouseId).push(orderId);
|
||
}
|
||
for (const [ orderWarehouseId, warehouseOrderIds ] of idsByWarehouse.entries()) {
|
||
resultRows.push(...await ctx.model.query(
|
||
querySql,
|
||
{
|
||
replacements: { ids: warehouseOrderIds, warehouseId: orderWarehouseId },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
}
|
||
));
|
||
}
|
||
}
|
||
return resultRows;
|
||
})()
|
||
: [],
|
||
normalizedStoreIds.length > 0 && Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||
? ctx.model.StoreWarehouse.findAll({
|
||
where: {
|
||
store_id: { [app.Sequelize.Op.in]: normalizedStoreIds },
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
]);
|
||
|
||
const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ]));
|
||
const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ]));
|
||
|
||
// 入库单映射:entry_order_id → { entry_order_code, express_code, logistics_code, logistics_name, source_type }
|
||
const entryOrderMap = new Map();
|
||
for (const eo of (Array.isArray(entryOrderRows) ? entryOrderRows : [])) {
|
||
entryOrderMap.set(Number(eo.id), eo);
|
||
}
|
||
|
||
// 发货单映射:order_id → source_order_codes
|
||
const orderDeliveryMap = new Map();
|
||
for (const od of (Array.isArray(orderDeliveryRows) ? orderDeliveryRows : [])) {
|
||
orderDeliveryMap.set(Number(od.id), od);
|
||
}
|
||
|
||
// 运单映射:order_id → waybill_code(取第一条)
|
||
const orderExpressMap = new Map();
|
||
for (const oe of (Array.isArray(orderExpressRows) ? orderExpressRows : [])) {
|
||
const oid = Number(oe.order_id);
|
||
if (oid > 0 && !orderExpressMap.has(oid)) {
|
||
orderExpressMap.set(oid, String(oe.waybill_code || '').trim());
|
||
}
|
||
}
|
||
|
||
// 货主自定义名称映射:store_id → store_remask
|
||
const storeWarehouseMap = new Map();
|
||
for (const sw of (Array.isArray(storeWarehouseRows) ? storeWarehouseRows : [])) {
|
||
const sid = Number(sw.store_id);
|
||
if (sid > 0 && !storeWarehouseMap.has(sid)) {
|
||
storeWarehouseMap.set(sid, String(sw.store_remask || '').trim());
|
||
}
|
||
}
|
||
|
||
return {
|
||
stockMap,
|
||
storeMap,
|
||
spaceMap,
|
||
barcodeMap,
|
||
entryOrderMap,
|
||
orderDeliveryMap,
|
||
orderExpressMap,
|
||
storeWarehouseMap,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建库存报表导出文件名。
|
||
* @param {string|Date|null|undefined} startTime 开始时间
|
||
* @param {string|Date|null|undefined} endTime 结束时间
|
||
* @return {string} 导出文件名
|
||
*/
|
||
buildExportFilename(startTime, endTime) {
|
||
const startToken = formatDateToken(startTime);
|
||
const endToken = formatDateToken(endTime);
|
||
const todayToken = formatDateToken(new Date());
|
||
|
||
if (startToken && endToken) {
|
||
return `库存报表_${startToken}_${endToken}.xlsx`;
|
||
}
|
||
|
||
if (startToken) {
|
||
return `库存报表_${startToken}.xlsx`;
|
||
}
|
||
|
||
if (endToken) {
|
||
return `库存报表_${endToken}.xlsx`;
|
||
}
|
||
|
||
return `库存报表_${todayToken}.xlsx`;
|
||
}
|
||
|
||
/**
|
||
* 导出库存流水统计报表。
|
||
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
||
* @param {string|Date|null} endTime 结束时间(闭区间上限)
|
||
* @param {boolean|string|number} [bySpace=false] 是否按库位返回
|
||
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表
|
||
* @param {Object} [sort] 排序参数
|
||
* @param {string} [sort.sortField] 排序字段
|
||
* @param {string} [sort.sortOrder] 排序顺序
|
||
* @param {string} [exportMode] 导出模式(仅仓库侧生效):'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录;货主侧固定只导出出入库流水
|
||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤)
|
||
* @param {string} [keyword=''] 商品关键字(模糊匹配)
|
||
* @return {Promise<Object>} excel 上传结果
|
||
*/
|
||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||
const { ctx, app } = this;
|
||
const isStoreMode = searchMode === 'store';
|
||
// 导出必须全量:显式传大分页,避免默认分页(pageSize=20)截断汇总与明细白名单
|
||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword, { page: 1, pageSize: EXPORT_FULL_PAGE_SIZE });
|
||
if (!searchResult || searchResult.code !== 200) {
|
||
return searchResult;
|
||
}
|
||
|
||
const summaryList = Array.isArray(searchResult.data && searchResult.data.list)
|
||
? searchResult.data.list
|
||
: [];
|
||
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||
const storeId = isStoreMode ? rawPrimaryId : null;
|
||
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||
const startTimeMs = toTimeMs(startTime);
|
||
const endTimeMs = toTimeMs(endTime);
|
||
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
||
const isBySpace = normalizeBoolean(bySpace);
|
||
|
||
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||
const secondaryIds = normalizedStoreIds;
|
||
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||
|
||
const whereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||
const replacements = {
|
||
[primaryDimAlias]: primaryDimVal,
|
||
};
|
||
|
||
if (startTimeMs !== null) {
|
||
whereClauses.push('t.created_at >= :startTime');
|
||
replacements.startTime = startTime;
|
||
}
|
||
|
||
if (endTimeMs !== null) {
|
||
whereClauses.push('t.created_at <= :endTime');
|
||
replacements.endTime = endTime;
|
||
}
|
||
|
||
if (secondaryIds.length > 0) {
|
||
whereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||
replacements[secondaryDimAlias] = secondaryIds;
|
||
}
|
||
|
||
const normalizedExportMode = String(exportMode || '').trim();
|
||
if (isStoreMode) {
|
||
// 货主侧口径:变更记录只包含出入库流水,锁定/解锁(LOCK/UNLOCK)一律不导出,无视 exportMode
|
||
whereClauses.push('t.transaction_type NOT IN (:excludeStoreTypes)');
|
||
replacements.excludeStoreTypes = [ 'LOCK', 'UNLOCK' ];
|
||
} else if (normalizedExportMode !== 'item') {
|
||
whereClauses.push('t.transaction_type != :excludeLockType');
|
||
replacements.excludeLockType = 'LOCK';
|
||
}
|
||
|
||
// 明细商品范围与汇总对齐:keyword/stock_ids 过滤后的汇总 stock 白名单同步作用于明细,
|
||
// 避免导出与汇总无关商品的变更记录
|
||
const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
if (summaryStockIds.length === 0) {
|
||
// 汇总无数据时明细也不应导出任何流水
|
||
whereClauses.push('0 = 1');
|
||
} else {
|
||
whereClauses.push('t.stock_id IN (:detailStockIds)');
|
||
replacements.detailStockIds = summaryStockIds;
|
||
}
|
||
|
||
const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction';
|
||
const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id';
|
||
const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type';
|
||
const detailReceivingIdSelectSql = isBySpace ? 'NULL AS receiving_id' : 't.receiving_id';
|
||
const detailEntryOrderIdSelectSql = isBySpace ? 'NULL AS entry_order_id' : 't.entry_order_id';
|
||
|
||
const detailRows = await ctx.model.query(`
|
||
SELECT
|
||
t.id,
|
||
t.created_at,
|
||
t.transaction_type,
|
||
t.store_id,
|
||
t.warehouse_id,
|
||
t.stock_id,
|
||
${detailSpaceSelectSql},
|
||
t.quantity,
|
||
t.before_quantity,
|
||
t.after_quantity,
|
||
t.before_locked_quantity,
|
||
t.after_locked_quantity,
|
||
t.batch_no,
|
||
${detailInventoryTypeSelectSql},
|
||
t.order_type,
|
||
t.order_no,
|
||
t.order_id,
|
||
${detailReceivingIdSelectSql},
|
||
${detailEntryOrderIdSelectSql},
|
||
t.operator_name,
|
||
t.remark
|
||
FROM ${detailTransactionTable} t
|
||
WHERE ${whereClauses.join(' AND ')}
|
||
ORDER BY t.created_at ASC, t.id ASC
|
||
`, {
|
||
replacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
const safeDetailRows = Array.isArray(detailRows) ? detailRows : [];
|
||
const detailStockIds = [ ...new Set(safeDetailRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const detailStoreIds = [ ...new Set(safeDetailRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const detailSpaceIds = [ ...new Set(safeDetailRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const detailEntryOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const detailOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
|
||
const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
|
||
const summarySpaceIds = isBySpace
|
||
? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]
|
||
: [];
|
||
|
||
// 货主模式:从流水明细按订单ID收集所属仓库,用于运单查询强制同仓校验
|
||
const detailOrderWarehouseMap = new Map();
|
||
for (const item of safeDetailRows) {
|
||
const orderId = Number(item.order_id);
|
||
const rowWarehouseId = Number(item.warehouse_id);
|
||
if (Number.isInteger(orderId) && orderId > 0 && Number.isInteger(rowWarehouseId) && rowWarehouseId > 0) {
|
||
detailOrderWarehouseMap.set(orderId, rowWarehouseId);
|
||
}
|
||
}
|
||
|
||
const maps = await this.loadReportReferenceMaps({
|
||
stockIds: [ ...new Set([ ...summaryStockIds, ...detailStockIds ]) ],
|
||
storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ],
|
||
spaceIds: [ ...new Set([ ...summarySpaceIds, ...detailSpaceIds ]) ],
|
||
includeBarcode: true,
|
||
entryOrderIds: detailEntryOrderIds,
|
||
orderIds: detailOrderIds,
|
||
warehouseId,
|
||
orderWarehouseMap: detailOrderWarehouseMap,
|
||
});
|
||
|
||
const summaryColumns = [
|
||
{ header: '开始时间', key: 'start_time' },
|
||
{ header: '结束时间', key: 'end_time' },
|
||
{ header: '货主ID', key: 'store_id' },
|
||
{ header: '货主名称', key: 'store_name' },
|
||
{ header: '仓库ID', key: 'warehouse_id' },
|
||
{ header: '仓库名称', key: 'warehouse_name' },
|
||
{ header: '商品库存ID', key: 'stock_id' },
|
||
{ header: '商品编码', key: 'item_code' },
|
||
{ header: '商品名称', key: 'item_name' },
|
||
{ header: '条码', key: 'barcode' },
|
||
...(isBySpace
|
||
? [
|
||
{ header: '库位ID', key: 'space_id' },
|
||
{ header: '库位名称', key: 'space_name' },
|
||
]
|
||
: []),
|
||
{ header: '期初', key: 'begin_total' },
|
||
{ header: '入库', key: 'inbound_total' },
|
||
{ header: '出库', key: 'outbound_total' },
|
||
{ header: '期末', key: 'end_total' },
|
||
];
|
||
|
||
const summarySheetRows = summaryList.map(item => ({
|
||
start_time: item.start_time || '',
|
||
end_time: item.end_time || '',
|
||
store_id: toNumber(item.store_id),
|
||
store_name: item.store_name || '',
|
||
warehouse_id: toNumber(item.warehouse_id),
|
||
warehouse_name: item.warehouse_name || '',
|
||
stock_id: toNumber(item.stock_id),
|
||
item_code: item.item_code || '',
|
||
item_name: item.item_name || '',
|
||
barcode: item.barcode || '',
|
||
...(isBySpace
|
||
? {
|
||
space_id: toNumber(item.space_id),
|
||
space_name: item.space_name || '',
|
||
}
|
||
: {}),
|
||
begin_total: toNumber(item.begin_total),
|
||
inbound_total: toNumber(item.inbound_total),
|
||
outbound_total: toNumber(item.outbound_total),
|
||
end_total: toNumber(item.end_total),
|
||
}));
|
||
|
||
const detailSheetRows = safeDetailRows.map(item => {
|
||
const stockId = toNumber(item.stock_id);
|
||
const storeId = toNumber(item.store_id);
|
||
const stock = maps.stockMap.get(stockId) || {};
|
||
const store = maps.storeMap.get(storeId) || {};
|
||
const barcodeSet = maps.barcodeMap.get(stockId);
|
||
|
||
const entryOrderId = toNumber(item.entry_order_id);
|
||
const entryOrder = entryOrderId > 0 ? (maps.entryOrderMap.get(entryOrderId) || {}) : {};
|
||
const isQimenEntry = entryOrder.source_type === 'QM';
|
||
|
||
const orderId = toNumber(item.order_id);
|
||
const orderDelivery = orderId > 0 ? (maps.orderDeliveryMap.get(orderId) || {}) : {};
|
||
const waybillCode = maps.orderExpressMap.get(orderId) || '';
|
||
|
||
// 运单号:出库取 order_express.waybill_code,入库取 entry_order.express_code
|
||
const generalWaybillNo = waybillCode
|
||
|| (entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '');
|
||
|
||
return {
|
||
created_at: formatDateTime(item.created_at),
|
||
transaction_type: formatTransactionType(item.transaction_type),
|
||
store_id: storeId,
|
||
store_name: store.company_name || '',
|
||
store_remask: maps.storeWarehouseMap.get(storeId) || '',
|
||
stock_id: stockId,
|
||
item_code: stock.item_code || '',
|
||
item_name: stock.item_name || '',
|
||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||
quantity: toNumber(item.quantity),
|
||
before_quantity: toNumber(item.before_quantity),
|
||
after_quantity: toNumber(item.after_quantity),
|
||
before_locked_quantity: toNumber(item.before_locked_quantity),
|
||
after_locked_quantity: toNumber(item.after_locked_quantity),
|
||
batch_no: item.batch_no || '',
|
||
inventory_type: item.inventory_type || '',
|
||
order_type: item.order_type || '',
|
||
order_no: item.order_no || '',
|
||
order_id: orderId,
|
||
receiving_id: toNumber(item.receiving_id),
|
||
entry_order_id: entryOrderId,
|
||
operator_name: item.operator_name || '',
|
||
remark: item.remark || '',
|
||
// 新增字段
|
||
qimen_entry_order_code: isQimenEntry ? String(entryOrder.entry_order_code || '').trim() : '',
|
||
platform_trade_no: String(orderDelivery.source_order_codes || item.order_no || '').trim(),
|
||
entry_order_waybill_no: entryOrderId > 0 ? String(entryOrder.express_code || '').trim() : '',
|
||
entry_order_express_company: entryOrderId > 0 ? String(entryOrder.logistics_name || '').trim() : '',
|
||
waybill_no: String(generalWaybillNo || '').trim(),
|
||
};
|
||
});
|
||
|
||
const detailColumns = [
|
||
{ header: '时间', key: 'created_at' },
|
||
{ header: '类型', key: 'transaction_type' },
|
||
{ header: '货主名称', key: 'store_name' },
|
||
{ header: '自定义店铺名称', key: 'store_remask' },
|
||
{ header: '商品库存ID', key: 'stock_id' },
|
||
{ header: '商品编码', key: 'item_code' },
|
||
{ header: '商品名称', key: 'item_name' },
|
||
{ header: '条码', key: 'barcode' },
|
||
{ header: '变动数量', key: 'quantity' },
|
||
{ header: '变更前库存', key: 'before_quantity' },
|
||
{ header: '变更后库存', key: 'after_quantity' },
|
||
{ header: '变更前锁定', key: 'before_locked_quantity' },
|
||
{ header: '变更后锁定', key: 'after_locked_quantity' },
|
||
{ header: '批次号', key: 'batch_no' },
|
||
{ header: '库存类型', key: 'inventory_type' },
|
||
{ header: '单据类型', key: 'order_type' },
|
||
{ header: '单据号', key: 'order_no' },
|
||
{ header: '单据ID', key: 'order_id' },
|
||
{ header: '奇门入库单号', key: 'qimen_entry_order_code' },
|
||
{ header: '平台交易单号', key: 'platform_trade_no' },
|
||
{ header: '运单号', key: 'waybill_no' },
|
||
{ header: '入库单运单号', key: 'entry_order_waybill_no' },
|
||
{ header: '入库单快递公司', key: 'entry_order_express_company' },
|
||
{ header: '收货单ID', key: 'receiving_id' },
|
||
{ header: '入库单ID', key: 'entry_order_id' },
|
||
{ header: '操作人', key: 'operator_name' },
|
||
{ header: '备注', key: 'remark' },
|
||
];
|
||
|
||
return await ctx.service.systems.excel.generateAndUpload({
|
||
filename: this.buildExportFilename(startTime, endTime),
|
||
dir: `exports/storage/report/${warehouseId || storeId || 'common'}`,
|
||
category: 'document',
|
||
sheets: [
|
||
{
|
||
name: '汇总',
|
||
columns: summaryColumns,
|
||
rows: summarySheetRows,
|
||
},
|
||
{
|
||
name: '变更记录',
|
||
columns: detailColumns,
|
||
rows: detailSheetRows,
|
||
},
|
||
],
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 根据关键字解析匹配的 stock_id 列表。
|
||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配。
|
||
* @param {string} keyword 搜索关键字
|
||
* @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id)
|
||
* @param {number} primaryDimVal 主维度值
|
||
* @return {Promise<number[]>} 匹配的 stock_id 列表
|
||
*/
|
||
async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) {
|
||
const { ctx, app } = this;
|
||
const normalizedKeyword = String(keyword || '').trim();
|
||
if (!normalizedKeyword) {
|
||
return [];
|
||
}
|
||
|
||
const likePattern = `%${normalizedKeyword}%`;
|
||
// 如果 keyword 为纯数字,同时支持按 stock_id(SKU ID)精确匹配
|
||
const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null;
|
||
|
||
// 从 wms_stock_warehouse 按 item_code / item_name / goods_code / id(SKU) 模糊匹配
|
||
const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : '';
|
||
const stockRows = await ctx.model.query(`
|
||
SELECT DISTINCT sw.id AS stock_id
|
||
FROM wms_stock_warehouse sw
|
||
WHERE sw.${primaryDimCol} = :primaryDimVal
|
||
AND (
|
||
sw.item_code LIKE :keyword
|
||
OR sw.item_name LIKE :keyword
|
||
OR sw.goods_code LIKE :keyword
|
||
${extraIdCondition}
|
||
)
|
||
`, {
|
||
replacements: { primaryDimVal, keyword: likePattern, exactStockId },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
// 从 wms_stock_barcodes 按 barcode 模糊匹配
|
||
const barcodeRows = await ctx.model.query(`
|
||
SELECT DISTINCT sb.stock_id
|
||
FROM wms_stock_barcodes sb
|
||
INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal
|
||
WHERE sb.barcode LIKE :keyword
|
||
`, {
|
||
replacements: { primaryDimVal, keyword: likePattern },
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
const stockIdSet = new Set();
|
||
for (const row of stockRows) {
|
||
const sid = Number(row.stock_id);
|
||
if (sid > 0) stockIdSet.add(sid);
|
||
}
|
||
for (const row of barcodeRows) {
|
||
const sid = Number(row.stock_id);
|
||
if (sid > 0) stockIdSet.add(sid);
|
||
}
|
||
|
||
return [ ...stockIdSet ];
|
||
}
|
||
|
||
/**
|
||
* 查询库存流水统计报表。
|
||
* 规则:
|
||
* 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。
|
||
* 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。
|
||
* 3) 期末取区间内末条流水的 after_quantity。
|
||
* 4) 若维度键在区间内无流水,期末回退到期初(库存未变动,保持“期末 = 期初 + 入库 - 出库”恒等)。
|
||
* 5) by_space=false 时按 stock_id+store_id 维度输出;by_space=true 时按 stock_id+space_id+store_id 维度输出。
|
||
*
|
||
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
||
* @param {string|Date|null} endTime 结束时间(闭区间上限)
|
||
* @param {boolean|string|number} [bySpace=false] 是否按库位返回
|
||
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表(store模式为仓库ID列表)
|
||
* @param {Object} [sort] 排序参数
|
||
* @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total)
|
||
* @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感)
|
||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥
|
||
* @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥
|
||
* @param {Object|null} [pagination=null] 分页参数 { page, pageSize }(兼容 page_size);未传或非法时默认 page=1、pageSize=20,仅对当前页行加载名称信息
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '', pagination = null) {
|
||
const { ctx, app } = this;
|
||
const isStoreMode = searchMode === 'store';
|
||
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||
const storeId = isStoreMode ? rawPrimaryId : null;
|
||
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||
|
||
if (!isStoreMode && !warehouseId) {
|
||
return {
|
||
code: 400,
|
||
message: '用户未绑定仓库',
|
||
data: { list: [] },
|
||
};
|
||
}
|
||
if (isStoreMode && !storeId) {
|
||
return {
|
||
code: 400,
|
||
message: '用户未绑定货主',
|
||
data: { list: [] },
|
||
};
|
||
}
|
||
|
||
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||
|
||
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||
const secondaryIds = normalizeStoreIds(storeIds);
|
||
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||
|
||
const startTimeMs = toTimeMs(startTime);
|
||
const endTimeMs = toTimeMs(endTime);
|
||
|
||
if (startTime !== undefined && startTime !== null && startTime !== '' && startTimeMs === null) {
|
||
return {
|
||
code: 400,
|
||
message: 'start_time 参数不合法',
|
||
data: { list: [] },
|
||
};
|
||
}
|
||
|
||
if (endTime !== undefined && endTime !== null && endTime !== '' && endTimeMs === null) {
|
||
return {
|
||
code: 400,
|
||
message: 'end_time 参数不合法',
|
||
data: { list: [] },
|
||
};
|
||
}
|
||
|
||
if (startTimeMs !== null && endTimeMs !== null && startTimeMs > endTimeMs) {
|
||
return {
|
||
code: 400,
|
||
message: 'start_time 不能大于 end_time',
|
||
data: { list: [] },
|
||
};
|
||
}
|
||
|
||
const isBySpace = normalizeBoolean(bySpace);
|
||
|
||
// 归一化 stock_ids:优先使用 keyword 解析,其次使用显式传入的 stockIds
|
||
let resolvedStockIds = null;
|
||
const normalizedKeyword = String(keyword || '').trim();
|
||
if (normalizedKeyword) {
|
||
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
|
||
if (resolvedStockIds.length === 0) {
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||
};
|
||
}
|
||
} else if (stockIds !== null && stockIds !== undefined) {
|
||
const rawIds = Array.isArray(stockIds) ? stockIds.flat() : [ stockIds ];
|
||
resolvedStockIds = [ ...new Set(
|
||
rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||
) ];
|
||
if (resolvedStockIds.length === 0) {
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||
};
|
||
}
|
||
}
|
||
|
||
let baseStockRows = [];
|
||
let baseStorageRows = [];
|
||
if (!isBySpace) {
|
||
const baseWhereClauses = [ `sw.${primaryDimCol} = :${primaryDimAlias}` ];
|
||
const baseReplacements = {
|
||
[primaryDimAlias]: primaryDimVal,
|
||
};
|
||
|
||
if (secondaryIds.length > 0) {
|
||
baseWhereClauses.push(`sw.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||
}
|
||
|
||
baseStockRows = await ctx.model.query(`
|
||
SELECT
|
||
sw.id AS stock_id,
|
||
sw.store_id,
|
||
sw.warehouse_id,
|
||
sw.quantity,
|
||
sw.item_code,
|
||
sw.item_name
|
||
FROM wms_stock_warehouse sw
|
||
WHERE ${baseWhereClauses.join(' AND ')}
|
||
`, {
|
||
replacements: baseReplacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||
if (resolvedStockIds !== null) {
|
||
const stockIdSet = new Set(resolvedStockIds);
|
||
baseStockRows = baseStockRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||
}
|
||
|
||
if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) {
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||
};
|
||
}
|
||
} else {
|
||
const baseWhereClauses = [ `s.${primaryDimCol} = :${primaryDimAlias}`, 's.delete_at IS NULL' ];
|
||
const baseReplacements = {
|
||
[primaryDimAlias]: primaryDimVal,
|
||
};
|
||
|
||
if (secondaryIds.length > 0) {
|
||
baseWhereClauses.push(`s.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||
}
|
||
|
||
baseStorageRows = await ctx.model.query(`
|
||
SELECT
|
||
s.stock_id,
|
||
COALESCE(s.space_id, 0) AS space_id,
|
||
s.store_id,
|
||
s.warehouse_id,
|
||
SUM(s.quantity) AS quantity,
|
||
MAX(sw.item_code) AS item_code,
|
||
MAX(sw.item_name) AS item_name
|
||
FROM wms_storage s
|
||
LEFT JOIN wms_stock_warehouse sw ON sw.id = s.stock_id
|
||
WHERE ${baseWhereClauses.join(' AND ')}
|
||
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id
|
||
`, {
|
||
replacements: baseReplacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||
if (resolvedStockIds !== null) {
|
||
const stockIdSet = new Set(resolvedStockIds);
|
||
baseStorageRows = baseStorageRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||
}
|
||
|
||
baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : [];
|
||
}
|
||
|
||
const rangeWhereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||
const rangeReplacements = {
|
||
[primaryDimAlias]: primaryDimVal,
|
||
};
|
||
|
||
if (startTimeMs !== null) {
|
||
rangeWhereClauses.push('t.created_at >= :startTime');
|
||
rangeReplacements.startTime = startTime;
|
||
}
|
||
|
||
if (endTimeMs !== null) {
|
||
rangeWhereClauses.push('t.created_at <= :endTime');
|
||
rangeReplacements.endTime = endTime;
|
||
}
|
||
|
||
if (secondaryIds.length > 0) {
|
||
rangeWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||
rangeReplacements[secondaryDimAlias] = secondaryIds;
|
||
}
|
||
|
||
if (!isBySpace) {
|
||
const baseStockIds = [
|
||
...new Set(baseStockRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)),
|
||
];
|
||
if (baseStockIds.length === 0) {
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||
};
|
||
}
|
||
|
||
rangeWhereClauses.push('t.stock_id IN (:baseStockIds)');
|
||
rangeReplacements.baseStockIds = baseStockIds;
|
||
}
|
||
|
||
const transactionSource = resolveTransactionSourceConfig(isBySpace);
|
||
|
||
const rangeRowsSql = `
|
||
SELECT
|
||
t.stock_id,
|
||
${transactionSource.spaceSelectSql},
|
||
t.store_id,
|
||
SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total,
|
||
SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total
|
||
FROM ${transactionSource.tableName} t
|
||
WHERE ${rangeWhereClauses.join(' AND ')}
|
||
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
|
||
`;
|
||
|
||
const rangeRows = await ctx.model.query(rangeRowsSql, {
|
||
replacements: rangeReplacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : [];
|
||
|
||
// 区间内首/末条快照:在 SQL 端按维度键聚合取极值行,每组仅返回 1 行
|
||
// (before_quantity 取首条、after_quantity 取末条),避免把区间内全部流水明细拉回 Node 内存归并。
|
||
// 兼容 MySQL 5.7:不使用窗口函数,采用派生表聚合 MIN/MAX(created_at) + 标量子查询取极值 id 回表。
|
||
const intervalEdgeRows = await ctx.model.query(`
|
||
SELECT
|
||
g.stock_id,
|
||
g.space_id,
|
||
g.store_id,
|
||
ft.before_quantity,
|
||
lt.after_quantity,
|
||
ft.created_at
|
||
FROM (
|
||
SELECT
|
||
t.stock_id,
|
||
${transactionSource.spaceSelectSql},
|
||
t.store_id,
|
||
MIN(t.created_at) AS _min_ct,
|
||
MAX(t.created_at) AS _max_ct
|
||
FROM ${transactionSource.tableName} t
|
||
WHERE ${rangeWhereClauses.join(' AND ')}
|
||
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
|
||
) g
|
||
LEFT JOIN ${transactionSource.tableName} ft
|
||
ON ft.id = (
|
||
SELECT MIN(t2.id)
|
||
FROM ${transactionSource.tableName} t2
|
||
WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''} AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||
AND t2.created_at = g._min_ct
|
||
)
|
||
LEFT JOIN ${transactionSource.tableName} lt
|
||
ON lt.id = (
|
||
SELECT MAX(t3.id)
|
||
FROM ${transactionSource.tableName} t3
|
||
WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||
AND t3.created_at = g._max_ct
|
||
)
|
||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC
|
||
`, {
|
||
replacements: rangeReplacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
|
||
let preStartSnapshotRows = [];
|
||
if (startTimeMs !== null) {
|
||
const preStartWhereClauses = [
|
||
`t.${primaryDimCol} = :${primaryDimAlias}`,
|
||
't.created_at < :startTime',
|
||
];
|
||
const preStartReplacements = {
|
||
[primaryDimAlias]: primaryDimVal,
|
||
startTime,
|
||
};
|
||
|
||
if (secondaryIds.length > 0) {
|
||
preStartWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||
preStartReplacements[secondaryDimAlias] = secondaryIds;
|
||
}
|
||
|
||
if (!isBySpace) {
|
||
preStartWhereClauses.push('t.stock_id IN (:baseStockIds)');
|
||
preStartReplacements.baseStockIds = rangeReplacements.baseStockIds;
|
||
}
|
||
|
||
// start_time 之前的期初快照:SQL 端按维度键聚合取最新一条流水,每组仅返回 1 行,
|
||
// 避免把全部历史流水明细拉回 Node 内存归并。兼容 MySQL 5.7(聚合 + 标量子查询取极值 id 回表)。
|
||
preStartSnapshotRows = await ctx.model.query(`
|
||
SELECT
|
||
g.stock_id,
|
||
g.space_id,
|
||
g.store_id,
|
||
lt.after_quantity,
|
||
lt.created_at
|
||
FROM (
|
||
SELECT
|
||
t.stock_id,
|
||
${transactionSource.spaceSelectSql},
|
||
t.store_id,
|
||
MAX(t.created_at) AS _max_ct
|
||
FROM ${transactionSource.tableName} t
|
||
WHERE ${preStartWhereClauses.join(' AND ')}
|
||
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
|
||
) g
|
||
LEFT JOIN ${transactionSource.tableName} lt
|
||
ON lt.id = (
|
||
SELECT MAX(t3.id)
|
||
FROM ${transactionSource.tableName} t3
|
||
WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''} AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||
AND t3.created_at = g._max_ct
|
||
)
|
||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC
|
||
`, {
|
||
replacements: preStartReplacements,
|
||
type: app.Sequelize.QueryTypes.SELECT,
|
||
});
|
||
}
|
||
|
||
if (!isBySpace) {
|
||
const edgeByStockStore = buildIntervalEdgeMap(intervalEdgeRows, row => {
|
||
const stockId = Number(row.stock_id);
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
return null;
|
||
}
|
||
return `${stockId}_${storeId}`;
|
||
});
|
||
const preStartAfterByStockStore = buildPreStartAfterMap(preStartSnapshotRows, row => {
|
||
const stockId = Number(row.stock_id);
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
return null;
|
||
}
|
||
return `${stockId}_${storeId}`;
|
||
});
|
||
|
||
const rangeSumByStockStore = new Map();
|
||
for (const row of safeRangeRows) {
|
||
const stockId = Number(row.stock_id);
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
continue;
|
||
}
|
||
const stockStoreKey = `${stockId}_${storeId}`;
|
||
if (!rangeSumByStockStore.has(stockStoreKey)) {
|
||
rangeSumByStockStore.set(stockStoreKey, {
|
||
inbound_total: 0,
|
||
outbound_total: 0,
|
||
});
|
||
}
|
||
const current = rangeSumByStockStore.get(stockStoreKey);
|
||
current.inbound_total += toNumber(row.inbound_total);
|
||
current.outbound_total += toNumber(row.outbound_total);
|
||
}
|
||
|
||
const groupedList = baseStockRows
|
||
.map(row => {
|
||
const stockId = Number(row.stock_id);
|
||
const storeId = Number(row.store_id);
|
||
const whId = Number(row.warehouse_id) || 0;
|
||
const stockStoreKey = `${stockId}_${storeId}`;
|
||
const snapshot = edgeByStockStore.get(stockStoreKey);
|
||
const rangeSum = rangeSumByStockStore.get(stockStoreKey);
|
||
const preStartAfter = preStartAfterByStockStore.get(stockStoreKey);
|
||
const hasSnapshot = snapshot && snapshot.has_snapshot;
|
||
const hasPreStartSnapshot = preStartAfterByStockStore.has(stockStoreKey);
|
||
let beginTotal = 0;
|
||
if (hasPreStartSnapshot) {
|
||
beginTotal = toNumber(preStartAfter);
|
||
} else if (hasSnapshot) {
|
||
beginTotal = toNumber(snapshot && snapshot.begin_total);
|
||
}
|
||
|
||
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
|
||
const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : beginTotal;
|
||
|
||
return {
|
||
start_time: startTime || null,
|
||
end_time: endTime || null,
|
||
stock_id: stockId,
|
||
store_id: storeId,
|
||
warehouse_id: whId,
|
||
begin_total: beginTotal,
|
||
end_total: endTotal,
|
||
inbound_total: toNumber(rangeSum && rangeSum.inbound_total),
|
||
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
|
||
store_name: '',
|
||
warehouse_name: '',
|
||
// item_code/item_name 取快照查询结果,供按 item_code/item_name 排序使用;
|
||
// 最终展示值以 getStockDetails 为准(本字段作为回退)
|
||
item_name: row.item_name || '',
|
||
barcode: '',
|
||
item_code: row.item_code || '',
|
||
};
|
||
})
|
||
.filter(item => item.stock_id > 0 && item.store_id > 0);
|
||
|
||
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,
|
||
// 避免全量 SKU 的商品详情缓存/DB 查询(大数据量下为耗时大头)。
|
||
sortReportList(groupedList, false, sort);
|
||
const pageResult = paginateList(groupedList, pagination);
|
||
const pageItems = pageResult.items;
|
||
|
||
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
|
||
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
|
||
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
|
||
|
||
// 复用 getStockDetails 获取商品名称和条码
|
||
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||
const stockDetailOpts = isStoreMode ? { warehouseId: null } : {};
|
||
const stockMap = new Map();
|
||
const barcodesByStock = new Map();
|
||
if (groupedStockIds.length > 0) {
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
groupedStockIds,
|
||
stockDetailOpts
|
||
);
|
||
for (const detail of stockDetails) {
|
||
const sid = Number(detail.id);
|
||
stockMap.set(sid, {
|
||
id: sid,
|
||
item_name: detail.item_name,
|
||
item_code: detail.item_code,
|
||
});
|
||
// 提取条码
|
||
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
||
const barcodeSet = new Set();
|
||
for (const bc of detail.barcodes) {
|
||
const barcode = String(bc.barcode || '').trim();
|
||
if (barcode) {
|
||
barcodeSet.add(barcode);
|
||
}
|
||
}
|
||
barcodesByStock.set(sid, barcodeSet);
|
||
}
|
||
}
|
||
}
|
||
|
||
const storeRows = storeIdList.length > 0
|
||
? await ctx.model.Store.findAll({
|
||
where: {
|
||
id: storeIdList,
|
||
},
|
||
attributes: [ 'id', 'company_name' ],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||
|
||
const warehouseRows = warehouseIdList.length > 0
|
||
? await ctx.model.Store.findAll({
|
||
where: {
|
||
id: warehouseIdList,
|
||
},
|
||
attributes: [ 'id', 'company_name' ],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||
|
||
const list = pageItems
|
||
.map(item => {
|
||
const stock = stockMap.get(item.stock_id) || {};
|
||
const store = storeMap.get(item.store_id) || {};
|
||
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||
|
||
return {
|
||
...item,
|
||
store_name: store.company_name || '',
|
||
warehouse_name: warehouse.company_name || '',
|
||
item_name: stock.item_name || item.item_name || '',
|
||
item_code: stock.item_code || item.item_code || '',
|
||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||
};
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list, pagination: pageResult.meta },
|
||
};
|
||
}
|
||
|
||
const baseEntryByKey = new Map();
|
||
for (const row of baseStorageRows) {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
const whId = Number(row.warehouse_id) || 0;
|
||
if (!stockId || !storeId) {
|
||
continue;
|
||
}
|
||
|
||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||
baseEntryByKey.set(baseKey, {
|
||
stock_id: stockId,
|
||
space_id: spaceId,
|
||
store_id: storeId,
|
||
warehouse_id: whId,
|
||
quantity: toNumber(row.quantity),
|
||
item_code: row.item_code || '',
|
||
item_name: row.item_name || '',
|
||
});
|
||
}
|
||
|
||
for (const row of safeRangeRows) {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
const whId = Number(row.warehouse_id) || 0;
|
||
if (!stockId || !storeId) {
|
||
continue;
|
||
}
|
||
|
||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||
if (!baseEntryByKey.has(baseKey)) {
|
||
baseEntryByKey.set(baseKey, {
|
||
stock_id: stockId,
|
||
space_id: spaceId,
|
||
store_id: storeId,
|
||
warehouse_id: whId,
|
||
quantity: 0,
|
||
item_code: '',
|
||
item_name: '',
|
||
});
|
||
}
|
||
}
|
||
|
||
const baseEntries = [ ...baseEntryByKey.values() ];
|
||
if (baseEntries.length === 0) {
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list: [], pagination: paginateList([], pagination).meta },
|
||
};
|
||
}
|
||
|
||
const edgeByBaseKey = buildIntervalEdgeMap(intervalEdgeRows, row => {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
return null;
|
||
}
|
||
return `${stockId}_${spaceId}_${storeId}`;
|
||
});
|
||
const preStartAfterByBaseKey = buildPreStartAfterMap(preStartSnapshotRows, row => {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
return null;
|
||
}
|
||
return `${stockId}_${spaceId}_${storeId}`;
|
||
});
|
||
|
||
const rangeByBaseKey = new Map();
|
||
for (const row of safeRangeRows) {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
if (!stockId || !storeId) {
|
||
continue;
|
||
}
|
||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||
rangeByBaseKey.set(baseKey, {
|
||
inbound_total: toNumber(row.inbound_total),
|
||
outbound_total: toNumber(row.outbound_total),
|
||
});
|
||
}
|
||
|
||
const groupedMap = new Map();
|
||
for (const row of baseEntries) {
|
||
const stockId = Number(row.stock_id);
|
||
const spaceId = Number(row.space_id) || 0;
|
||
const storeId = Number(row.store_id);
|
||
const whId = Number(row.warehouse_id) || 0;
|
||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||
const snapshot = edgeByBaseKey.get(baseKey) || {
|
||
begin_total: 0,
|
||
end_total: 0,
|
||
has_snapshot: false,
|
||
};
|
||
const preStartAfter = preStartAfterByBaseKey.get(baseKey);
|
||
const hasPreStartSnapshot = preStartAfterByBaseKey.has(baseKey);
|
||
const rangeSum = rangeByBaseKey.get(baseKey) || {
|
||
inbound_total: 0,
|
||
outbound_total: 0,
|
||
};
|
||
|
||
const targetKey = baseKey;
|
||
|
||
if (!groupedMap.has(targetKey)) {
|
||
groupedMap.set(targetKey, {
|
||
start_time: startTime || null,
|
||
end_time: endTime || null,
|
||
stock_id: stockId,
|
||
store_id: storeId,
|
||
warehouse_id: whId,
|
||
...(isBySpace ? { space_id: spaceId } : {}),
|
||
begin_total: 0,
|
||
end_total: 0,
|
||
inbound_total: 0,
|
||
outbound_total: 0,
|
||
store_name: '',
|
||
warehouse_name: '',
|
||
// item_code/item_name 取库存快照查询结果,供按 item_code/item_name 排序使用
|
||
item_name: row.item_name || '',
|
||
barcode: '',
|
||
item_code: row.item_code || '',
|
||
space_name: '',
|
||
});
|
||
}
|
||
|
||
const current = groupedMap.get(targetKey);
|
||
const beginTotal = hasPreStartSnapshot
|
||
? toNumber(preStartAfter)
|
||
: snapshot.has_snapshot
|
||
? toNumber(snapshot.begin_total)
|
||
: 0;
|
||
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
|
||
const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : beginTotal;
|
||
current.begin_total += beginTotal;
|
||
current.end_total += endTotal;
|
||
current.inbound_total += toNumber(rangeSum.inbound_total);
|
||
current.outbound_total += toNumber(rangeSum.outbound_total);
|
||
}
|
||
|
||
const groupedList = [ ...groupedMap.values() ];
|
||
|
||
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,避免全量 SKU 详情查询
|
||
sortReportList(groupedList, isBySpace, sort);
|
||
const pageResult = paginateList(groupedList, pagination);
|
||
const pageItems = pageResult.items;
|
||
|
||
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
|
||
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
|
||
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
|
||
const spaceIds = isBySpace
|
||
? [ ...new Set(pageItems.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
||
: [];
|
||
|
||
// 复用 getStockDetails 获取商品名称和条码
|
||
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||
const stockDetailOptsSpace = isStoreMode ? { warehouseId: null } : {};
|
||
const stockMap = new Map();
|
||
const barcodesByStock = new Map();
|
||
if (groupedStockIds.length > 0) {
|
||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||
groupedStockIds,
|
||
stockDetailOptsSpace
|
||
);
|
||
for (const detail of stockDetails) {
|
||
const sid = Number(detail.id);
|
||
stockMap.set(sid, {
|
||
id: sid,
|
||
item_name: detail.item_name,
|
||
item_code: detail.item_code,
|
||
});
|
||
// 提取条码
|
||
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
||
const barcodeSet = new Set();
|
||
for (const bc of detail.barcodes) {
|
||
const barcode = String(bc.barcode || '').trim();
|
||
if (barcode) {
|
||
barcodeSet.add(barcode);
|
||
}
|
||
}
|
||
barcodesByStock.set(sid, barcodeSet);
|
||
}
|
||
}
|
||
}
|
||
|
||
const [ storeRows, spaceRows, warehouseRows ] = await Promise.all([
|
||
storeIdList.length > 0
|
||
? ctx.model.Store.findAll({
|
||
where: {
|
||
id: storeIdList,
|
||
},
|
||
attributes: [ 'id', 'company_name' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
isBySpace && spaceIds.length > 0
|
||
? ctx.model.LocationSpace.findAll({
|
||
where: {
|
||
id: spaceIds,
|
||
},
|
||
attributes: [ 'id', 'custom_name', 'space_code' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
warehouseIdList.length > 0
|
||
? ctx.model.Store.findAll({
|
||
where: {
|
||
id: warehouseIdList,
|
||
},
|
||
attributes: [ 'id', 'company_name' ],
|
||
raw: true,
|
||
})
|
||
: [],
|
||
]);
|
||
|
||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||
|
||
const list = pageItems
|
||
.map(item => {
|
||
const stock = stockMap.get(item.stock_id) || {};
|
||
const store = storeMap.get(item.store_id) || {};
|
||
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||
const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null;
|
||
|
||
const merged = {
|
||
...item,
|
||
store_name: store.company_name || '',
|
||
warehouse_name: warehouse.company_name || '',
|
||
item_name: stock.item_name || item.item_name || '',
|
||
item_code: stock.item_code || item.item_code || '',
|
||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||
};
|
||
|
||
if (isBySpace) {
|
||
merged.space_name = space.custom_name || space.space_code || '';
|
||
}
|
||
|
||
return merged;
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: { list, pagination: pageResult.meta },
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = StorageReportService;
|