feat: 新增 stock.transaction 商品流水导出 + keyword 商品搜索
- systems/stock_transaction.js: 新增 exportList() 异步导出 Excel(上限50000条) - 新增 _resolveKeywordToStockIds() 关键词→stock_id 解析 - queryList/exportList 支持 keyword 模糊搜索(按 item_code/item_name/goods_code/barcode/SKU ID) - systemMethods/stock/transaction.js: - 新增 export/exportStore/exportTaskProgress 异步导出方法 - list/storeList/export/exportStore 全部透传 keyword - storeList 新增 warehouse_id/stock_id 单数兼容 - methods/system.json + changes/system.json: 新增3个method文档
This commit is contained in:
parent
3e813c4975
commit
df8173cecd
@ -2,6 +2,9 @@
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_transaction_export_task_';
|
||||
const STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
/**
|
||||
* 系统方法层:stock.transaction(商品出入库流水查询包装层)。
|
||||
*/
|
||||
@ -9,9 +12,9 @@ class StockTransactionMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,storeList';
|
||||
const _noNeedLog = 'list,storeList';
|
||||
const _noNeedAuth = 'list,storeList';
|
||||
const _noNeedRight = 'list,storeList,export,exportStore,exportTaskProgress';
|
||||
const _noNeedLog = 'list,storeList,export,exportStore,exportTaskProgress';
|
||||
const _noNeedAuth = 'list,storeList,export,exportStore,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -34,6 +37,7 @@ class StockTransactionMethodService extends MainService {
|
||||
end_time: endTime,
|
||||
store_ids: storeIds,
|
||||
stock_ids: stockIds,
|
||||
keyword,
|
||||
transaction_type: transactionType,
|
||||
order_type: orderType,
|
||||
order_no: orderNo,
|
||||
@ -62,6 +66,7 @@ class StockTransactionMethodService extends MainService {
|
||||
endTime,
|
||||
storeIds,
|
||||
stockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
@ -71,6 +76,7 @@ class StockTransactionMethodService extends MainService {
|
||||
orderId,
|
||||
sort: sortOption,
|
||||
pagination,
|
||||
mode: 'warehouse',
|
||||
});
|
||||
|
||||
return this.success('ok', result);
|
||||
@ -98,8 +104,11 @@ class StockTransactionMethodService extends MainService {
|
||||
const {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
warehouse_ids: warehouseIds,
|
||||
stock_ids: stockIds,
|
||||
warehouse_ids: warehouseIdsRaw,
|
||||
warehouse_id: warehouseIdRaw,
|
||||
stock_ids: stockIdsRaw,
|
||||
stock_id: stockIdRaw,
|
||||
keyword,
|
||||
transaction_type: transactionType,
|
||||
order_type: orderType,
|
||||
order_no: orderNo,
|
||||
@ -109,6 +118,16 @@ class StockTransactionMethodService extends MainService {
|
||||
order_id: orderId,
|
||||
} = whereValue;
|
||||
|
||||
// 兼容 warehouse_id(单数)和 warehouse_ids(数组)
|
||||
const warehouseIds = warehouseIdsRaw !== undefined
|
||||
? warehouseIdsRaw
|
||||
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
sort_field: sortFieldSnake,
|
||||
@ -128,6 +147,7 @@ class StockTransactionMethodService extends MainService {
|
||||
endTime,
|
||||
warehouseIds,
|
||||
stockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
@ -141,6 +161,361 @@ class StockTransactionMethodService extends MainService {
|
||||
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 仓库侧提交商品流水导出任务。
|
||||
* 与 list 使用相同查询条件,异步执行,立即返回任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { service } = this;
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
store_ids: storeIds,
|
||||
stock_ids: stockIds,
|
||||
keyword,
|
||||
transaction_type: transactionType,
|
||||
order_type: orderType,
|
||||
order_no: orderNo,
|
||||
batch_no: batchNo,
|
||||
entry_order_id: entryOrderId,
|
||||
receiving_id: receivingId,
|
||||
order_id: orderId,
|
||||
} = whereValue;
|
||||
|
||||
const { sort = {} } = data;
|
||||
const sortOption = {
|
||||
sortField: sort.sortField || sort.sort_field,
|
||||
sortOrder: sort.sortOrder || sort.sort_order,
|
||||
};
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.stockTransaction.exportList({
|
||||
warehouseId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds,
|
||||
stockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
entryOrderId,
|
||||
receivingId,
|
||||
orderId,
|
||||
sort: sortOption,
|
||||
mode: 'warehouse',
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧提交商品流水导出任务。
|
||||
* 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.store_id 货主ID(必传)
|
||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||
*/
|
||||
async exportStore(data = {}) {
|
||||
const { service } = this;
|
||||
const storeId = Number(data.store_id);
|
||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||
return this.failure('store_id 不能为空');
|
||||
}
|
||||
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
const {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
warehouse_ids: warehouseIdsRaw,
|
||||
warehouse_id: warehouseIdRaw,
|
||||
stock_ids: stockIdsRaw,
|
||||
stock_id: stockIdRaw,
|
||||
keyword,
|
||||
transaction_type: transactionType,
|
||||
order_type: orderType,
|
||||
order_no: orderNo,
|
||||
batch_no: batchNo,
|
||||
entry_order_id: entryOrderId,
|
||||
receiving_id: receivingId,
|
||||
order_id: orderId,
|
||||
} = whereValue;
|
||||
|
||||
const warehouseIds = warehouseIdsRaw !== undefined
|
||||
? warehouseIdsRaw
|
||||
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
|
||||
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const sortOption = {
|
||||
sortField: sort.sortField || sort.sort_field,
|
||||
sortOrder: sort.sortOrder || sort.sort_order,
|
||||
};
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.stockTransaction.exportList({
|
||||
storeId,
|
||||
startTime,
|
||||
endTime,
|
||||
warehouseIds,
|
||||
stockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
entryOrderId,
|
||||
receivingId,
|
||||
orderId,
|
||||
sort: sortOption,
|
||||
mode: 'store',
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询商品流水导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cndUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成导出任务ID。
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `stock_transaction_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${STOCK_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, STOCK_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[stock.transaction.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[stock.transaction.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StockTransactionMethodService;
|
||||
|
||||
@ -308,6 +308,63 @@ class StockTransactionService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据关键字解析匹配的 stock_id 列表。
|
||||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。
|
||||
* @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}%`;
|
||||
const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null;
|
||||
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,
|
||||
});
|
||||
|
||||
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 ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询商品出入库流水列表(原始记录,不做聚合)。
|
||||
* 仓库侧:按 warehouseId 限定;货主侧:按 storeId 限定。
|
||||
@ -319,6 +376,7 @@ class StockTransactionService extends Service {
|
||||
* @param {Array<number|string>} [options.storeIds] 货主ID数组(仓库侧筛选)
|
||||
* @param {Array<number|string>} [options.warehouseIds] 仓库ID数组(货主侧筛选)
|
||||
* @param {Array<number|string>} [options.stockIds] 商品库存ID数组
|
||||
* @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配)
|
||||
* @param {string} [options.transactionType] 流水类型
|
||||
* @param {string} [options.orderType] 单据类型
|
||||
* @param {string} [options.orderNo] 单据号
|
||||
@ -328,6 +386,7 @@ class StockTransactionService extends Service {
|
||||
* @param {number} [options.orderId] 发货单ID
|
||||
* @param {Object} [options.sort] 排序参数
|
||||
* @param {Object} [options.pagination] 分页参数
|
||||
* @param {string} [options.mode] 模式 'warehouse'/'store',用于 keyword 解析时决定主维度
|
||||
* @return {Promise<Object>} { list, pagination }
|
||||
*/
|
||||
async queryList(options = {}) {
|
||||
@ -339,7 +398,8 @@ class StockTransactionService extends Service {
|
||||
endTime,
|
||||
storeIds,
|
||||
warehouseIds,
|
||||
stockIds,
|
||||
stockIds: rawStockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
@ -349,8 +409,23 @@ class StockTransactionService extends Service {
|
||||
orderId,
|
||||
sort = {},
|
||||
pagination = {},
|
||||
mode = 'warehouse',
|
||||
} = options;
|
||||
|
||||
// keyword 解析为 stock_ids
|
||||
let resolvedStockIds = Array.isArray(rawStockIds)
|
||||
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
if (normalizedKeyword && resolvedStockIds.length === 0) {
|
||||
const isStoreMode = mode === 'store';
|
||||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
|
||||
if (primaryDimVal > 0) {
|
||||
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
|
||||
}
|
||||
}
|
||||
|
||||
const whereClauses = [];
|
||||
const replacements = {};
|
||||
|
||||
@ -401,11 +476,7 @@ class StockTransactionService extends Service {
|
||||
}
|
||||
|
||||
// 商品筛选
|
||||
const normalizedStockIds = Array.isArray(stockIds)
|
||||
? stockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
if (normalizedStockIds.length > 0) {
|
||||
whereClauses.push('t.stock_id IN (:stockIds)');
|
||||
const normalizedStockIds = resolvedStockIds;
|
||||
replacements.stockIds = normalizedStockIds;
|
||||
}
|
||||
|
||||
@ -552,6 +623,249 @@ class StockTransactionService extends Service {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出商品出入库流水列表为 Excel。
|
||||
* 与 queryList 使用相同的查询条件,但不分页(导出上限 50000 条)。
|
||||
* @param {Object} options 查询参数(与 queryList 一致,忽略 pagination)
|
||||
* @param {string} [options.mode] 导出模式:'warehouse' 仓库侧 / 'store' 货主侧
|
||||
* @return {Promise<Object>} Excel 导出结果 { url, filename }
|
||||
*/
|
||||
async exportList(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const {
|
||||
warehouseId,
|
||||
storeId,
|
||||
startTime,
|
||||
endTime,
|
||||
storeIds,
|
||||
warehouseIds,
|
||||
stockIds: rawStockIds,
|
||||
keyword,
|
||||
transactionType,
|
||||
orderType,
|
||||
orderNo,
|
||||
batchNo,
|
||||
entryOrderId,
|
||||
receivingId,
|
||||
orderId,
|
||||
sort = {},
|
||||
mode = 'warehouse',
|
||||
} = options;
|
||||
|
||||
// keyword 解析为 stock_ids
|
||||
let resolvedStockIds = Array.isArray(rawStockIds)
|
||||
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
if (normalizedKeyword && resolvedStockIds.length === 0) {
|
||||
const isStoreMode = mode === 'store';
|
||||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
|
||||
if (primaryDimVal > 0) {
|
||||
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
|
||||
}
|
||||
}
|
||||
|
||||
const isStoreMode = mode === 'store';
|
||||
const whereClauses = [];
|
||||
const replacements = {};
|
||||
|
||||
// 数据范围限定
|
||||
if (warehouseId !== undefined && warehouseId !== null) {
|
||||
whereClauses.push('t.warehouse_id = :warehouseId');
|
||||
replacements.warehouseId = Number(warehouseId);
|
||||
}
|
||||
|
||||
if (storeId !== undefined && storeId !== null) {
|
||||
whereClauses.push('t.store_id = :storeId');
|
||||
replacements.storeId = Number(storeId);
|
||||
}
|
||||
|
||||
if (startTime !== undefined && startTime !== null && startTime !== '') {
|
||||
const startMs = new Date(startTime).getTime();
|
||||
if (!Number.isNaN(startMs)) {
|
||||
whereClauses.push('t.created_at >= :startTime');
|
||||
replacements.startTime = startTime;
|
||||
}
|
||||
}
|
||||
|
||||
if (endTime !== undefined && endTime !== null && endTime !== '') {
|
||||
const endMs = new Date(endTime).getTime();
|
||||
if (!Number.isNaN(endMs)) {
|
||||
whereClauses.push('t.created_at <= :endTime');
|
||||
replacements.endTime = endTime;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedStoreIds = Array.isArray(storeIds)
|
||||
? storeIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
whereClauses.push('t.store_id IN (:storeIds)');
|
||||
replacements.storeIds = normalizedStoreIds;
|
||||
}
|
||||
|
||||
const normalizedWarehouseIds = Array.isArray(warehouseIds)
|
||||
? warehouseIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
: [];
|
||||
if (normalizedWarehouseIds.length > 0) {
|
||||
whereClauses.push('t.warehouse_id IN (:warehouseIds)');
|
||||
replacements.warehouseIds = normalizedWarehouseIds;
|
||||
}
|
||||
|
||||
const normalizedStockIds = resolvedStockIds;
|
||||
if (normalizedStockIds.length > 0) {
|
||||
whereClauses.push('t.stock_id IN (:stockIds)');
|
||||
replacements.stockIds = normalizedStockIds;
|
||||
}
|
||||
|
||||
if (transactionType) {
|
||||
whereClauses.push('t.transaction_type = :transactionType');
|
||||
replacements.transactionType = String(transactionType).trim();
|
||||
}
|
||||
|
||||
if (orderType) {
|
||||
whereClauses.push('t.order_type = :orderType');
|
||||
replacements.orderType = String(orderType).trim();
|
||||
}
|
||||
|
||||
if (orderNo) {
|
||||
whereClauses.push('t.order_no LIKE :orderNo');
|
||||
replacements.orderNo = `%${String(orderNo).trim()}%`;
|
||||
}
|
||||
|
||||
if (batchNo) {
|
||||
whereClauses.push('t.batch_no = :batchNo');
|
||||
replacements.batchNo = String(batchNo).trim();
|
||||
}
|
||||
|
||||
if (entryOrderId !== undefined && entryOrderId !== null) {
|
||||
const eid = Number(entryOrderId);
|
||||
if (Number.isInteger(eid) && eid > 0) {
|
||||
whereClauses.push('t.entry_order_id = :entryOrderId');
|
||||
replacements.entryOrderId = eid;
|
||||
}
|
||||
}
|
||||
|
||||
if (receivingId !== undefined && receivingId !== null) {
|
||||
const rid = Number(receivingId);
|
||||
if (Number.isInteger(rid) && rid > 0) {
|
||||
whereClauses.push('t.receiving_id = :receivingId');
|
||||
replacements.receivingId = rid;
|
||||
}
|
||||
}
|
||||
|
||||
if (orderId !== undefined && orderId !== null) {
|
||||
const oid = Number(orderId);
|
||||
if (Number.isInteger(oid) && oid > 0) {
|
||||
whereClauses.push('t.order_id = :orderId');
|
||||
replacements.orderId = oid;
|
||||
}
|
||||
}
|
||||
|
||||
const whereSQL = whereClauses.length > 0
|
||||
? `WHERE ${whereClauses.join(' AND ')}`
|
||||
: '';
|
||||
|
||||
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id' ]);
|
||||
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
|
||||
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
|
||||
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
|
||||
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
const EXPORT_MAX = 50000;
|
||||
const rows = await ctx.model.query(
|
||||
`SELECT
|
||||
t.id,
|
||||
t.created_at,
|
||||
t.transaction_type,
|
||||
t.warehouse_id,
|
||||
t.store_id,
|
||||
t.stock_id,
|
||||
t.quantity,
|
||||
t.before_quantity,
|
||||
t.after_quantity,
|
||||
t.before_locked_quantity,
|
||||
t.after_locked_quantity,
|
||||
t.batch_no,
|
||||
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
|
||||
${whereSQL}
|
||||
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
|
||||
LIMIT ${EXPORT_MAX}
|
||||
`,
|
||||
{
|
||||
replacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
const safeRows = Array.isArray(rows) ? rows : [];
|
||||
const excelRows = safeRows.map((item, index) => ({
|
||||
序号: index + 1,
|
||||
创建时间: item.created_at ? app.formatDate(item.created_at) : '',
|
||||
流水类型: item.transaction_type || '',
|
||||
仓库ID: Number(item.warehouse_id) || 0,
|
||||
货主ID: Number(item.store_id) || 0,
|
||||
商品ID: Number(item.stock_id) || 0,
|
||||
变动数量: Number(item.quantity) || 0,
|
||||
变更前库存: Number(item.before_quantity) || 0,
|
||||
变更后库存: Number(item.after_quantity) || 0,
|
||||
变更前锁定: Number(item.before_locked_quantity) || 0,
|
||||
变更后锁定: Number(item.after_locked_quantity) || 0,
|
||||
批次号: item.batch_no || '',
|
||||
单据类型: item.order_type || '',
|
||||
单据号: item.order_no || '',
|
||||
收货单ID: Number(item.receiving_id) || 0,
|
||||
入库单ID: Number(item.entry_order_id) || 0,
|
||||
发货单ID: Number(item.order_id) || 0,
|
||||
操作人: item.operator_name || '',
|
||||
备注: item.remark || '',
|
||||
}));
|
||||
|
||||
const titleSuffix = isStoreMode ? '货主侧' : '仓库侧';
|
||||
const warehouseIdForPath = warehouseId || storeId || 'unknown';
|
||||
|
||||
return await ctx.service.systems.excel.generateAndUpload({
|
||||
filename: `商品流水_${titleSuffix}_${warehouseIdForPath}_${Date.now()}.xlsx`,
|
||||
dir: `exports/stock/transaction/${warehouseIdForPath}`,
|
||||
category: 'document',
|
||||
sheets: [
|
||||
{
|
||||
name: '商品流水',
|
||||
columns: [
|
||||
{ header: '序号', key: '序号' },
|
||||
{ header: '创建时间', key: '创建时间' },
|
||||
{ header: '流水类型', key: '流水类型' },
|
||||
{ header: '仓库ID', key: '仓库ID' },
|
||||
{ header: '货主ID', key: '货主ID' },
|
||||
{ header: '商品ID', key: '商品ID' },
|
||||
{ header: '变动数量', key: '变动数量' },
|
||||
{ header: '变更前库存', key: '变更前库存' },
|
||||
{ header: '变更后库存', key: '变更后库存' },
|
||||
{ header: '变更前锁定', key: '变更前锁定' },
|
||||
{ header: '变更后锁定', key: '变更后锁定' },
|
||||
{ header: '批次号', key: '批次号' },
|
||||
{ header: '单据类型', key: '单据类型' },
|
||||
{ header: '单据号', key: '单据号' },
|
||||
{ header: '收货单ID', key: '收货单ID' },
|
||||
{ header: '入库单ID', key: '入库单ID' },
|
||||
{ header: '发货单ID', key: '发货单ID' },
|
||||
{ header: '操作人', key: '操作人' },
|
||||
{ header: '备注', key: '备注' },
|
||||
],
|
||||
rows: excelRows,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StockTransactionService;
|
||||
|
||||
@ -4912,5 +4912,22 @@
|
||||
"更新 systems/storage/entry.js L273 注释引用",
|
||||
"文档:methods/system.json module storage.report→stock.report,5个 method 名同步更新"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.07.17-stock-transaction-export-01",
|
||||
"date": "2026-07-17",
|
||||
"type": "added",
|
||||
"summary": "新增 stock.transaction 商品流水导出(仓库侧+货主侧),异步任务模式,支持与列表查询一致的条件筛选",
|
||||
"methods": [
|
||||
"stock.transaction.export",
|
||||
"stock.transaction.exportStore",
|
||||
"stock.transaction.exportTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"systems/stock_transaction.js 新增 exportList(),复用 queryList 的查询逻辑,不分页导出 Excel(上限 50000 条)",
|
||||
"systemMethods/stock/transaction.js 新增 export/exportStore/exportTaskProgress,采用异步任务模式(setImmediate + 缓存)",
|
||||
"仓库侧导出自动限定 warehouse_id=ctx.user.store_id,货主侧需传 store_id",
|
||||
"导出 Excel 列:序号/创建时间/流水类型/仓库ID/货主ID/商品ID/变动数量/变更前库存/变更后库存/变更前锁定/变更后锁定/批次号/单据类型/单据号/收货单ID/入库单ID/发货单ID/操作人/备注"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@ -28326,6 +28326,332 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"groupName": "商品流水模块",
|
||||
"module": "stock.transaction",
|
||||
"list": [
|
||||
{
|
||||
"method": "stock.transaction.export",
|
||||
"description": "提交商品出入库流水导出异步任务(仓库侧)。与 stock.transaction.list 使用相同查询条件,立即返回任务受理信息,不直接返回文件。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "where",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "查询条件对象。支持字段:start_time(开始时间)、end_time(结束时间)、store_ids(货主ID数组)、stock_ids(商品库存ID数组)、transaction_type(流水类型 INBOUND/OUTBOUND/LOCK/UNLOCK)、order_type(单据类型)、order_no(单据号,模糊匹配)、batch_no(批次号)、entry_order_id(入库单ID)、receiving_id(收货单ID)、order_id(发货单ID)。仓库范围自动取自 ctx.user.store_id。"
|
||||
},
|
||||
{
|
||||
"name": "where.start_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "开始时间"
|
||||
},
|
||||
{
|
||||
"name": "where.end_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "结束时间"
|
||||
},
|
||||
{
|
||||
"name": "where.store_ids",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "货主ID数组"
|
||||
},
|
||||
{
|
||||
"name": "where.stock_ids",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "商品库存ID数组"
|
||||
},
|
||||
{
|
||||
"name": "where.transaction_type",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "流水类型:INBOUND/OUTBOUND/LOCK/UNLOCK"
|
||||
},
|
||||
{
|
||||
"name": "where.order_type",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "单据类型"
|
||||
},
|
||||
{
|
||||
"name": "where.order_no",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "单据号(模糊匹配)"
|
||||
},
|
||||
{
|
||||
"name": "where.batch_no",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "批次号"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id;sortOrder 支持 ASC/DESC"
|
||||
},
|
||||
{
|
||||
"name": "sort.sortField",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序字段"
|
||||
},
|
||||
{
|
||||
"name": "sort.sort_field",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序字段下划线别名"
|
||||
},
|
||||
{
|
||||
"name": "sort.sortOrder",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序方向"
|
||||
},
|
||||
{
|
||||
"name": "sort.sort_order",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序方向下划线别名"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "进度:0"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "受理消息"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "更新时间戳"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"method": "stock.transaction.exportStore",
|
||||
"description": "提交商品出入库流水导出异步任务(货主侧)。与 stock.transaction.storeList 使用相同查询条件,需传 store_id,立即返回任务受理信息。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "货主ID"
|
||||
},
|
||||
{
|
||||
"name": "where",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "查询条件对象。支持字段:start_time、end_time、warehouse_ids(仓库ID数组)、stock_ids(商品库存ID数组)、transaction_type、order_type、order_no、batch_no、entry_order_id、receiving_id、order_id。兼容 warehouse_id 单数。"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "排序参数。sortField 白名单:created_at/quantity/stock_id/store_id/warehouse_id"
|
||||
},
|
||||
{
|
||||
"name": "sort.sortField",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序字段"
|
||||
},
|
||||
{
|
||||
"name": "sort.sort_field",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序字段下划线别名"
|
||||
},
|
||||
{
|
||||
"name": "sort.sortOrder",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序方向"
|
||||
},
|
||||
{
|
||||
"name": "sort.sort_order",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.sort",
|
||||
"description": "排序方向下划线别名"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "进度:0"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "受理消息"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "更新时间戳"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"method": "stock.transaction.exportTaskProgress",
|
||||
"description": "根据 task_id 查询商品流水导出任务进度与结果。status 可能值:submitted/running/success/failed/not_found。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(下划线写法)"
|
||||
},
|
||||
{
|
||||
"name": "taskId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(驼峰写法)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted/running/success/failed/not_found"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "进度百分比(0-100)"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "状态说明"
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "失败时错误信息"
|
||||
},
|
||||
{
|
||||
"name": "download_url",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "成功后下载链接"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "更新时间戳"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user