'use strict'; const MainService = require('../main'); const ReportDeliveryPlanMethodService = require('./report/deliveryPlan'); const ReportDeliveryLogMethodService = require('./report/deliveryLog'); const ReportDefinitionMethodService = require('./report/definition'); const REPORT_GENERATE_TASK_CACHE_KEY_PREFIX = 'report_generate_task_'; const REPORT_GENERATE_TASK_CACHE_TTL_SECONDS = 1800; /** * 系统方法层:report(配置驱动通用报表接口包装层)。 * 仅做出口包装与导出任务编排,业务逻辑下沉 systems/report。 */ class ReportMethodService extends MainService { /** * 初始化 report 方法层:配置免鉴权清单,并挂载子目录服务实例。 * report.js 与 report/ 子目录同名并存时,egg 会把子目录服务作为静态属性挂在类构造器上, * ctx 层实例化后静态属性不可见,需按 storeWarehouse 同款模式在实例上显式挂载, * 保证 /system 网关可按 report.deliveryPlan.* / report.deliveryLog.* 路径解析。 * @param {Egg.Context} ctx Egg 上下文对象。 */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; const _noNeedRight = 'generate,generateTaskProgress'; const _noNeedLog = 'generate,generateTaskProgress'; const _noNeedAuth = 'generate,generateTaskProgress'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); // 显式挂载子目录服务实例(与 storeWarehouse.js 挂载 store/warehouse 的模式一致) this.deliveryPlan = new ReportDeliveryPlanMethodService(ctx); this.deliveryLog = new ReportDeliveryLogMethodService(ctx); this.definition = new ReportDefinitionMethodService(ctx); } /** * 提交报表导出异步任务(手动导出)。 * warehouse_id 由服务端从登录上下文自动注入,前端无需传递。 * @param {Object} data 请求体 * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) * @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id) * @param {number} [data.store_id] 货主ID(可选,货主维度报表时传入) * @param {Object} [data.params] 查询器业务参数(如 bizDate) * @return {Promise} 统一 success 包装,data 为导出任务信息 */ async generate(data = {}) { const { service } = this; const { report_id: reportIdSnake, reportId: reportIdCamel, store_id: storeIdSnake, storeId: storeIdCamel, params = {}, } = data; const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0; if (!Number.isInteger(reportId) || reportId <= 0) { return this.fail('报表ID report_id 必须为正整数'); } // 服务端注入仓库维度(禁止前端传 warehouse_id) const warehouseId = Number(this.ctx.user && this.ctx.user.store_id) || 0; const storeId = Number(storeIdCamel ?? storeIdSnake ?? 0) || 0; 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.report.generate({ reportId, storeId: storeId > 0 ? storeId : null, warehouseId, params, }); 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} 统一 success 包装 */ async generateTaskProgress(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 `report_generate_${warehouseId}_${timestamp}_${randomToken}`; } /** * 归一化导出任务ID。 * @param {Object} data 请求体 * @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 `${REPORT_GENERATE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; } /** * 写入导出任务进度缓存。 * @param {string} taskId 任务ID * @param {Object} payload 任务状态载荷 * @return {Promise} 无返回值 */ 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, REPORT_GENERATE_TASK_CACHE_TTL_SECONDS); } catch (error) { const errorMessage = error && error.message ? error.message : `${error}`; this.ctx.logger.warn(`[report.generate] 写入导出任务缓存失败: ${errorMessage}`); } } /** * 读取导出任务进度缓存。 * @param {string} taskId 任务ID * @return {Promise} 任务缓存 */ 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) { const errorMessage = error && error.message ? error.message : `${error}`; this.ctx.logger.warn(`[report.generateTaskProgress] 读取导出任务缓存失败: ${errorMessage}`); return null; } } } module.exports = ReportMethodService;