'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|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 '移库入'; } return rawType; } const SORT_FIELD_WHITE_LIST = new Set([ 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]); /** * 归一化排序参数。 * @param {Object|null|undefined} sort 排序入参 * @param {string} [sort.sortField] 排序字段 * @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; return list.sort((a, b) => { const aValue = toNumber(a[sortField]); const bValue = toNumber(b[sortField]); if (aValue !== bValue) { return (aValue - bValue) * direction; } return compareByDefaultOrder(a, b, isBySpace); }); } /** * 根据区间流水构建“首条before、末条after”的快照映射。 * @param {Object[]} rows 区间流水列表 * @param {(row: Object) => string|null} resolveKey 键解析函数 * @return {Map} 快照映射 */ 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} 期初快照映射 */ 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; } 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] 是否加载条码映射 * @return {Promise} 映射对象 */ async loadReportReferenceMaps({ stockIds = [], storeIds = [], spaceIds = [], includeBarcode = false, } = {}) { const { ctx } = 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 [ stockRows, storeRows, spaceRows, barcodeRows ] = await Promise.all([ normalizedStockIds.length > 0 ? ctx.model.StockWarehouse.findAll({ where: { id: normalizedStockIds, }, attributes: [ 'id', 'item_name', 'item_code' ], raw: true, }) : [], 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, }) : [], includeBarcode && normalizedStockIds.length > 0 ? ctx.model.StockBarcode.findAll({ where: { stock_id: normalizedStockIds, }, attributes: [ 'stock_id', 'barcode' ], raw: true, }) : [], ]); const stockMap = new Map((stockRows || []).map(item => [ Number(item.id), item ])); const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ])); const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ])); const barcodeMap = new Map(); for (const row of barcodeRows || []) { const stockId = Number(row.stock_id); const barcode = row.barcode ? String(row.barcode).trim() : ''; if (!stockId || !barcode) { continue; } if (!barcodeMap.has(stockId)) { barcodeMap.set(stockId, new Set()); } barcodeMap.get(stockId).add(barcode); } return { stockMap, storeMap, spaceMap, barcodeMap, }; } /** * 构建库存报表导出文件名。 * @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|null} [storeIds=[]] 货主ID列表 * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段 * @param {string} [sort.sortOrder] 排序顺序 * @return {Promise} excel 上传结果 */ async export(startTime, endTime, bySpace = false, storeIds = [], sort = null) { const { ctx, app } = this; const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort); if (!searchResult || searchResult.code !== 200) { return searchResult; } const summaryList = Array.isArray(searchResult.data && searchResult.data.list) ? searchResult.data.list : []; const warehouseId = Number(ctx.user && ctx.user.store_id); const startTimeMs = toTimeMs(startTime); const endTimeMs = toTimeMs(endTime); const normalizedStoreIds = normalizeStoreIds(storeIds); const isBySpace = normalizeBoolean(bySpace); const whereClauses = [ 't.warehouse_id = :warehouseId' ]; const replacements = { warehouseId, }; 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 (normalizedStoreIds.length > 0) { whereClauses.push('t.store_id IN (:storeIds)'); replacements.storeIds = normalizedStoreIds; } const detailRows = await ctx.model.query(` SELECT t.id, t.created_at, t.transaction_type, t.store_id, t.stock_id, 0 AS space_id, t.quantity, t.before_quantity, t.after_quantity, t.before_locked_quantity, t.after_locked_quantity, t.batch_no, '' AS inventory_type, t.order_type, t.order_no, t.order_id, t.receiving_id, t.entry_order_id, t.operator_name, t.remark FROM wms_stock_transaction 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 summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_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)) ] : []; const maps = await this.loadReportReferenceMaps({ stockIds: [ ...new Set([ ...summaryStockIds, ...detailStockIds ]) ], storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ], spaceIds: [ ...new Set([ ...summarySpaceIds, ...detailSpaceIds ]) ], includeBarcode: true, }); const summaryColumns = [ { header: '开始时间', key: 'start_time' }, { header: '结束时间', key: 'end_time' }, { header: '货主ID', key: 'store_id' }, { header: '货主名称', key: 'store_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 || '', 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 spaceId = toNumber(item.space_id); const stock = maps.stockMap.get(stockId) || {}; const store = maps.storeMap.get(storeId) || {}; const space = maps.spaceMap.get(spaceId) || {}; const barcodeSet = maps.barcodeMap.get(stockId); return { created_at: formatDateTime(item.created_at), transaction_type: formatTransactionType(item.transaction_type), store_id: storeId, store_name: store.company_name || '', stock_id: stockId, item_code: stock.item_code || '', item_name: stock.item_name || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', space_id: spaceId, space_name: space.custom_name || space.space_code || '', 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: toNumber(item.order_id), receiving_id: toNumber(item.receiving_id), entry_order_id: toNumber(item.entry_order_id), operator_name: item.operator_name || '', remark: item.remark || '', }; }); const detailColumns = [ { header: '时间', key: 'created_at' }, { header: '类型', key: 'transaction_type' }, { header: '货主名称', key: 'store_name' }, { header: '商品库存ID', key: 'stock_id' }, { header: '商品编码', key: 'item_code' }, { header: '商品名称', key: 'item_name' }, { header: '条码', key: 'barcode' }, { header: '库位ID', key: 'space_id' }, { header: '库位名称', key: 'space_name' }, { 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: '收货单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 || 'common'}`, category: 'document', sheets: [ { name: '汇总', columns: summaryColumns, rows: summarySheetRows, }, { name: '变更记录', columns: detailColumns, rows: detailSheetRows, }, ], }); } /** * 查询库存流水统计报表。 * 规则: * 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。 * 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。 * 3) 期末取区间内末条流水的 after_quantity。 * 4) 若维度键在区间内仍无流水,期初/期末统一回退为 0。 * 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|null} [storeIds=[]] 货主ID列表 * @param {Object} [sort] 排序参数 * @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total) * @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感) * @return {Promise} code/data/message 结构 */ async search(startTime, endTime, bySpace = false, storeIds = [], sort = null) { const { ctx, app } = this; const warehouseId = Number(ctx.user && ctx.user.store_id); if (!warehouseId) { return { code: 400, message: '用户未绑定仓库', data: { list: [] }, }; } 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); const normalizedStoreIds = normalizeStoreIds(storeIds); let baseStockRows = []; let baseStorageRows = []; if (!isBySpace) { const baseWhereClauses = [ 'sw.warehouse_id = :warehouseId' ]; const baseReplacements = { warehouseId, }; if (normalizedStoreIds.length > 0) { baseWhereClauses.push('sw.store_id IN (:storeIds)'); baseReplacements.storeIds = normalizedStoreIds; } baseStockRows = await ctx.model.query(` SELECT sw.id AS stock_id, sw.store_id, sw.quantity FROM wms_stock_warehouse sw WHERE ${baseWhereClauses.join(' AND ')} `, { replacements: baseReplacements, type: app.Sequelize.QueryTypes.SELECT, }); if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) { return { code: 200, message: '查询成功', data: { list: [] }, }; } } else { const baseWhereClauses = [ 's.warehouse_id = :warehouseId', 's.delete_at IS NULL' ]; const baseReplacements = { warehouseId, }; if (normalizedStoreIds.length > 0) { baseWhereClauses.push('s.store_id IN (:storeIds)'); baseReplacements.storeIds = normalizedStoreIds; } baseStorageRows = await ctx.model.query(` SELECT s.stock_id, COALESCE(s.space_id, 0) AS space_id, s.store_id, SUM(s.quantity) AS quantity FROM wms_storage s WHERE ${baseWhereClauses.join(' AND ')} GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id `, { replacements: baseReplacements, type: app.Sequelize.QueryTypes.SELECT, }); baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : []; } const rangeWhereClauses = [ 't.warehouse_id = :warehouseId' ]; const rangeReplacements = { warehouseId, }; 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 (normalizedStoreIds.length > 0) { rangeWhereClauses.push('t.store_id IN (:storeIds)'); rangeReplacements.storeIds = normalizedStoreIds; } 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: [] }, }; } rangeWhereClauses.push('t.stock_id IN (:baseStockIds)'); rangeReplacements.baseStockIds = baseStockIds; } const rangeRowsSql = ` SELECT t.stock_id, 0 AS space_id, 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 wms_stock_transaction t WHERE ${rangeWhereClauses.join(' AND ')} GROUP BY t.stock_id, t.store_id `; const rangeRows = await ctx.model.query(rangeRowsSql, { replacements: rangeReplacements, type: app.Sequelize.QueryTypes.SELECT, }); const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : []; const intervalEdgeRows = await ctx.model.query(` SELECT t.id, t.stock_id, 0 AS space_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at FROM wms_stock_transaction t WHERE ${rangeWhereClauses.join(' AND ')} ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC `, { replacements: rangeReplacements, type: app.Sequelize.QueryTypes.SELECT, }); let preStartSnapshotRows = []; if (startTimeMs !== null) { const preStartWhereClauses = [ 't.warehouse_id = :warehouseId', 't.created_at < :startTime', ]; const preStartReplacements = { warehouseId, startTime, }; if (normalizedStoreIds.length > 0) { preStartWhereClauses.push('t.store_id IN (:storeIds)'); preStartReplacements.storeIds = normalizedStoreIds; } if (!isBySpace) { preStartWhereClauses.push('t.stock_id IN (:baseStockIds)'); preStartReplacements.baseStockIds = rangeReplacements.baseStockIds; } preStartSnapshotRows = await ctx.model.query(` SELECT t.id, t.stock_id, 0 AS space_id, t.store_id, t.after_quantity, t.created_at FROM wms_stock_transaction t WHERE ${preStartWhereClauses.join(' AND ')} ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id 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 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) : 0; return { start_time: startTime || null, end_time: endTime || null, stock_id: stockId, store_id: storeId, begin_total: beginTotal, end_total: endTotal, inbound_total: toNumber(rangeSum && rangeSum.inbound_total), outbound_total: toNumber(rangeSum && rangeSum.outbound_total), store_name: '', item_name: '', barcode: '', item_code: '', }; }) .filter(item => item.stock_id > 0 && item.store_id > 0); const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; const [ stockRows, barcodeRows, storeRows ] = await Promise.all([ stockIds.length > 0 ? ctx.model.StockWarehouse.findAll({ where: { id: stockIds, }, attributes: [ 'id', 'item_name', 'item_code' ], raw: true, }) : [], stockIds.length > 0 ? ctx.model.StockBarcode.findAll({ where: { stock_id: stockIds, }, attributes: [ 'stock_id', 'barcode' ], raw: true, }) : [], storeIdList.length > 0 ? ctx.model.Store.findAll({ where: { id: storeIdList, }, attributes: [ 'id', 'company_name' ], raw: true, }) : [], ]); const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); const barcodesByStock = new Map(); for (const row of barcodeRows) { const stockId = Number(row.stock_id); const barcode = row.barcode ? String(row.barcode).trim() : ''; if (!stockId || !barcode) { continue; } if (!barcodesByStock.has(stockId)) { barcodesByStock.set(stockId, new Set()); } barcodesByStock.get(stockId).add(barcode); } const list = groupedList .map(item => { const stock = stockMap.get(item.stock_id) || {}; const store = storeMap.get(item.store_id) || {}; const barcodeSet = barcodesByStock.get(item.stock_id); return { ...item, store_name: store.company_name || '', item_name: stock.item_name || '', item_code: stock.item_code || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', }; }); sortReportList(list, false, sort); return { code: 200, message: '查询成功', data: { list, }, }; } 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); if (!stockId || !storeId) { continue; } const baseKey = `${stockId}_${spaceId}_${storeId}`; baseEntryByKey.set(baseKey, { stock_id: stockId, space_id: spaceId, store_id: storeId, quantity: toNumber(row.quantity), }); } 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}`; if (!baseEntryByKey.has(baseKey)) { baseEntryByKey.set(baseKey, { stock_id: stockId, space_id: spaceId, store_id: storeId, quantity: 0, }); } } const baseEntries = [ ...baseEntryByKey.values() ]; if (baseEntries.length === 0) { return { code: 200, message: '查询成功', data: { list: [] }, }; } 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 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, ...(isBySpace ? { space_id: spaceId } : {}), begin_total: 0, end_total: 0, inbound_total: 0, outbound_total: 0, store_name: '', item_name: '', barcode: '', 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) : 0; 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() ]; const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; const spaceIds = isBySpace ? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ] : []; const [ stockRows, barcodeRows, storeRows, spaceRows ] = await Promise.all([ stockIds.length > 0 ? ctx.model.StockWarehouse.findAll({ where: { id: stockIds, }, attributes: [ 'id', 'item_name', 'item_code' ], raw: true, }) : [], stockIds.length > 0 ? ctx.model.StockBarcode.findAll({ where: { stock_id: stockIds, }, attributes: [ 'stock_id', 'barcode' ], raw: true, }) : [], 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, }) : [], ]); const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ])); const barcodesByStock = new Map(); for (const row of barcodeRows) { const stockId = Number(row.stock_id); const barcode = row.barcode ? String(row.barcode).trim() : ''; if (!stockId || !barcode) { continue; } if (!barcodesByStock.has(stockId)) { barcodesByStock.set(stockId, new Set()); } barcodesByStock.get(stockId).add(barcode); } const list = groupedList .map(item => { const stock = stockMap.get(item.stock_id) || {}; const store = storeMap.get(item.store_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 || '', item_name: stock.item_name || '', item_code: stock.item_code || '', barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', }; if (isBySpace) { merged.space_name = space.custom_name || space.space_code || ''; } return merged; }); sortReportList(list, isBySpace, sort); return { code: 200, message: '查询成功', data: { list, }, }; } } module.exports = StorageReportService;