'use strict'; const { Service } = require('egg'); const { renderSheetByType } = require('../../lib/report/render'); const { scheduleDateOf } = require('../../lib/report/day_window'); const QUERIES = require('./report/queries'); /** * 配置驱动通用报表引擎(systems 层)。 * * 链路:wms_report_definition(配置:type/file_name/fields) → 内置查询器(QUERIES 注册表) * → render.js(按类型硬编码字段规格渲染) → excel.generateAndUpload / generateBuffer(产物)。 * 本服务仅做编排与出口包装,具体口径由查询器实现并注释假设; * 定义唯一性由 id(主键)承担,plan/log 均按 report_definition_id 关联。 */ class ReportService extends Service { /** * 按 ID 读取启用的报表定义(is_enabled=1,软删自动排除)。 * @param {number|string} id 报表定义ID(正整数) * @return {Promise} 报表定义视图(fields 已解析为字符串数组) * @throws {Error} ID 非法、模型不可用或定义不存在/停用时抛出 */ async getDefinition(id) { const { ctx } = this; const model = ctx.model && ctx.model.ReportDefinition; if (!model || typeof model.findOne !== 'function') { throw new Error('报表定义模型 ReportDefinition 不可用'); } const normalizedId = Number(id) || 0; if (!Number.isInteger(normalizedId) || normalizedId <= 0) { throw new Error('报表ID report_id 必须为正整数'); } const row = await model.findOne({ where: { id: normalizedId, is_enabled: 1, }, raw: true, }); if (!row) { throw new Error(`报表定义不存在或已停用: id=${normalizedId}`); } return this.definitionToView(row); } /** * 解析 fields 字段:数组原样返回、JSON 字符串解析,其余按空数组兜底(元素统一为字符串)。 * @param {*} value 字段原始值 * @return {Array} 字段 key 数组 */ parseFieldsField(value) { let list = value; if (typeof value === 'string' && value.trim()) { try { list = JSON.parse(value); } catch (error) { this.ctx.logger.warn(`[report] 报表定义 fields JSON 解析失败: ${error.message}`); return []; } } if (!Array.isArray(list)) { return []; } return list .map(item => String(item || '').trim()) .filter(Boolean); } /** * 报表定义记录转视图对象(fields 统一解析为字符串数组,时间字段透传)。 * @param {Object} row 报表定义记录(实例或 raw) * @return {Object|null} 视图对象(记录为空时返回 null) */ definitionToView(row) { if (!row) { return null; } return { id: Number(row.id) || 0, name: String(row.name || ''), type: String(row.type || ''), file_name: String(row.file_name || ''), fields: this.parseFieldsField(row.fields), is_enabled: Number(row.is_enabled ?? 1), remark: String(row.remark || ''), created_at: row.created_at || null, updated_at: row.updated_at || null, }; } /** * 读取注册表描述条目(未知类型抛可读错误)。 * @param {string} type 报表类型(注册方法 key) * @return {{key: string, title: string, description: string, window: Object, fields: Array}} 描述条目 * @throws {Error} 类型未注册时抛出 */ resolveTypeEntry(type) { const normalizedType = String(type || '').trim(); const entries = typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; const entry = entries.find(item => item && item.key === normalizedType); if (!entry) { throw new Error(`未知的报表类型: ${normalizedType}`); } return entry; } /** * 读取查询器函数(未知类型抛错)。 * @param {string} type 报表类型(注册方法 key) * @return {Function} 查询器函数 */ resolveQuerier(type) { const normalizedType = String(type || '').trim(); const querier = QUERIES[normalizedType]; if (typeof querier !== 'function') { throw new Error(`未知的报表类型: ${normalizedType}`); } return querier; } /** * 输出注册表全量清单(供 method 层 report.definition.typeList 复用)。 * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册清单 */ listRegisteredTypes() { return typeof QUERIES.describe === 'function' ? QUERIES.describe() : []; } /** * 校验勾选字段均为该类型注册字段的子集(顶层字段 key),非法 key 列出可读错误。 * @param {string} type 报表类型(注册方法 key) * @param {Array} fields 勾选字段 key 数组 * @return {Array} 去重后的合法字段 key 数组(保持传入顺序) * @throws {Error} 含非法字段 key 时抛出 */ validateTypeFields(type, fields) { const entry = this.resolveTypeEntry(type); const registeredKeys = new Set((Array.isArray(entry.fields) ? entry.fields : []).map(field => field && field.key)); const safeFields = Array.isArray(fields) ? fields : []; const seen = new Set(); const normalized = []; const illegal = []; for (const item of safeFields) { const key = String(item || '').trim(); if (!key) { continue; } if (!registeredKeys.has(key)) { if (!illegal.includes(key)) { illegal.push(key); } continue; } if (!seen.has(key)) { seen.add(key); normalized.push(key); } } if (illegal.length > 0) { throw new Error( `fields 含非法字段: ${illegal.join(', ')}` + `(报表类型 ${type} 可用字段: ${[ ...registeredKeys ].join(', ') || '-'})` ); } return normalized; } /** * 按字段 key 顺序解析注册字段规格(用于渲染列顺序)。 * @param {Object} entry 注册表描述条目 * @param {Array} fields 勾选字段 key 数组 * @return {Array} 按勾选顺序排列的字段规格清单 */ resolveOrderedFields(entry, fields) { const entryFields = Array.isArray(entry.fields) ? entry.fields : []; const fieldMap = new Map(entryFields.map(field => [ field && field.key, field ])); const safeFields = Array.isArray(fields) ? fields : []; return safeFields .map(key => fieldMap.get(key)) .filter(Boolean); } /** * 构建导出文件名(支持 file_name 模板占位符)。 * * 占位符(2026-09-10 扩充,均为本地时区): * - `{date}`:数据日期(请求 params.bizDate,缺省服务器当天,`YYYY-MM-DD`)——语义不变; * - `{time}`:生成时刻 `HHmmss`(如 `200745`); * - `{datetime}`:`{date}_{time}`(如 `2026-09-09_200745`); * - `{timestamp}`:生成时刻毫秒时间戳(如 `1789136465123`)。 * * 用途:同一天多次投递/手动导出同一报表时,文件名带生成时刻可避免 COS 同名覆盖 *(同名文件会被后一次写覆盖,且 CDN 可能继续回源旧内容)。 * * @param {Object} definition 报表定义视图 * @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天) * @param {Date} [now=new Date()] 生成时刻(渲染 {time}/{datetime}/{timestamp} 用,可注入供测试) * @return {string} 文件名 */ buildFilename(definition, bizDate = '', now = new Date()) { const nowDate = now instanceof Date && !Number.isNaN(now.getTime()) ? now : new Date(); const dateText = String(bizDate || '').trim() || scheduleDateOf(nowDate); const timeText = `${String(nowDate.getHours()).padStart(2, '0')}` + `${String(nowDate.getMinutes()).padStart(2, '0')}` + `${String(nowDate.getSeconds()).padStart(2, '0')}`; const template = String((definition && definition.file_name) || '').trim() || `${String((definition && definition.name) || 'report')}_${dateText}.xlsx`; const filename = template .replace(/\{datetime\}/g, `${dateText}_${timeText}`) .replace(/\{date\}/g, dateText) .replace(/\{time\}/g, timeText) .replace(/\{timestamp\}/g, String(nowDate.getTime())); return filename.endsWith('.xlsx') || filename.endsWith('.xls') ? filename : `${filename}.xlsx`; } /** * 查询数据并翻译为 excel.js 的 sheets 参数(generate/generateBuffer 共用)。 * @param {Object} options 入参 * @param {number|string} options.reportId 报表定义ID * @param {number|null} [options.storeId] 货主ID * @param {number|null} [options.warehouseId] 仓库ID * @param {Object} [options.params] 查询器业务参数(如 bizDate) * @return {Promise<{sheets: Array, filename: string, queryData: Object}>} 翻译结果 */ async buildWorkbookSheets({ reportId, storeId = null, warehouseId = null, params = {} }) { const definition = await this.getDefinition(reportId); const entry = this.resolveTypeEntry(definition.type); const querier = this.resolveQuerier(definition.type); const queryData = await querier({ ctx: this.ctx, storeId, warehouseId, params: params || {}, }); const orderedFields = this.resolveOrderedFields(entry, definition.fields); const sheet = renderSheetByType({ type: definition.type, title: entry.title, fields: orderedFields, rows: Array.isArray(queryData.rows) ? queryData.rows : [], windows: Array.isArray(queryData.windows) ? queryData.windows : [], }); return { sheets: [ sheet ], filename: this.buildFilename(definition, params && params.bizDate), queryData, }; } /** * 生成报表 Excel 并上传,返回 fileKey/url(供手动导出与货主投递复用)。 * 上传目录按(报表定义 + 货主/仓库)隔离,保证不同货主的报表文件互不覆盖。 * @param {Object} options 入参 * @param {number|string} options.reportId 报表定义ID * @param {number|null} [options.storeId] 货主ID(货主维度报表必传,有效时按货主隔离上传目录) * @param {number|null} [options.warehouseId] 仓库ID(货主维度缺省时按仓库隔离上传目录) * @param {Object} [options.params] 查询器业务参数(如 bizDate) * @return {Promise<{fileKey: string, url: string, filename: string, size: number}>} 上传结果 */ async generate({ reportId, storeId = null, warehouseId = null, params = {} }) { const { sheets, filename } = await this.buildWorkbookSheets({ reportId, storeId, warehouseId, params, }); // 上传目录按(报表定义 + 货主/仓库)隔离:同一报表定义下不同货主不得共用同一文件 key, // 避免后投递货主的文件覆盖先投递货主的文件(货主限制不符缺陷)。 // storeId 缺省时退化为仓库维度,未传货主/仓库时按 common 兜底(保持手动导出兼容)。 const normalizedStoreId = Number(storeId) || 0; const normalizedWarehouseId = Number(warehouseId) || 0; const ownerSegment = normalizedStoreId > 0 ? `store-${normalizedStoreId}` : (normalizedWarehouseId > 0 ? `warehouse-${normalizedWarehouseId}` : 'common'); const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({ filename, dir: `exports/report/${String(reportId).trim()}/${ownerSegment}`, category: 'document', sheets, }); const fileKey = String(uploadResult.fileKey || uploadResult.fileName || '').trim(); const url = String( uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || fileKey || '' ).trim(); return { fileKey, url, filename: String(uploadResult.filename || filename), size: Number(uploadResult.size) || 0, }; } /** * 生成报表 Excel 缓冲(内部入口,供后续复用/直推下载)。 * @param {Object} options 入参 * @param {number|string} options.reportId 报表定义ID * @param {number|null} [options.storeId] 货主ID * @param {number|null} [options.warehouseId] 仓库ID * @param {Object} [options.params] 查询器业务参数(如 bizDate) * @return {Promise<{buffer: Buffer, filename: string, contentType: string}>} 缓冲结果 */ async generateBuffer({ reportId, storeId = null, warehouseId = null, params = {} }) { const { sheets, filename } = await this.buildWorkbookSheets({ reportId, storeId, warehouseId, params, }); const buffer = await this.ctx.service.systems.excel.generateBuffer({ bookType: 'xlsx', sheets, }); return { buffer, filename, contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }; } /** * 新增/更新报表定义(按 id upsert;未传 id 视为新增)。 * 更新语义:未传入的字段(undefined)不覆盖既有值;传入非法值会校验报错。 * 校验项:name 必填、type 必须为注册表已有类型、file_name 必填(新增时)、 * fields 必须为该类型注册字段的子集。 * @param {Object} options 入参 * @param {number} [options.id] 报表定义ID(正整数;不传视为新增) * @param {string} options.name 报表名称(必填,≤100) * @param {string} options.type 报表类型(注册方法 key,如 stockFlow;新增必填) * @param {string} options.fileName 导出文件名模板(支持 {date};新增必填,≤200) * @param {Array} options.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) * @param {number} [options.isEnabled] 是否启用(0/1) * @param {string} [options.remark] 备注(≤500) * @return {Promise} 保存后的报表定义视图 * @throws {Error} 参数非法、类型未知或字段非法时抛出业务可读错误 */ async saveDefinition({ id, name = '', type, fileName, fields, isEnabled, remark, } = {}) { const { ctx } = this; const model = ctx.model && ctx.model.ReportDefinition; if (!model || typeof model.findOne !== 'function') { throw new Error('报表定义模型 ReportDefinition 不可用'); } const normalizedId = id === undefined || id === null || id === '' ? null : Number(id) || 0; if (normalizedId !== null && (!Number.isInteger(normalizedId) || normalizedId <= 0)) { throw new Error('报表ID id 必须为正整数'); } const normalizedName = String(name || '').trim(); if (!normalizedName) { throw new Error('报表名称 name 不能为空'); } if (normalizedName.length > 100) { throw new Error('报表名称 name 不能超过 100 字符'); } // 软删记录也纳入查找(按 id 主键查重,paranoid: false 支持恢复), // 并复用既有记录 type 完成 fields 校验(避免重复查库) const existing = normalizedId !== null ? await this.findDefinitionById(model, normalizedId) : null; if (normalizedId !== null && !existing) { throw new Error(`报表定义不存在: id=${normalizedId}`); } // 未传 type(undefined)不校验也不覆盖既有值;显式传空/未知类型仍报错 let normalizedType; if (type !== undefined) { normalizedType = String(type || '').trim(); this.resolveTypeEntry(normalizedType); } // 未传 fields(undefined)不校验;显式传值须为该类型注册字段子集 let normalizedFields; if (fields !== undefined) { if (!Array.isArray(fields)) { throw new Error('报表字段 fields 必须为数组'); } // 校验查询器取本次 type,其次取既有记录 type const fieldsValidationType = normalizedType !== undefined ? normalizedType : (existing && existing.type); if (!fieldsValidationType) { throw new Error('报表类型 type 不能为空'); } normalizedFields = this.validateTypeFields(fieldsValidationType, fields); } // 未传 fileName(undefined)不覆盖既有值;新增时必填 let normalizedFileName; if (fileName !== undefined) { normalizedFileName = String(fileName || '').trim(); if (!normalizedFileName) { throw new Error('导出文件名 file_name 不能为空'); } if (normalizedFileName.length > 200) { throw new Error('导出文件名 file_name 不能超过 200 字符'); } } if (isEnabled !== undefined) { const enabledNum = Number(isEnabled); if (enabledNum !== 0 && enabledNum !== 1) { throw new Error('is_enabled 仅支持 0/1'); } } // 新增时必须提供 type/file_name/fields(existing 已在上方按 id 查询一次) if (!existing) { if (normalizedType === undefined) { throw new Error('报表类型 type 不能为空'); } if (normalizedFileName === undefined) { throw new Error('导出文件名 file_name 不能为空'); } if (normalizedFields === undefined) { throw new Error('报表字段 fields 不能为空'); } } const payload = { name: normalizedName, }; if (normalizedType !== undefined) { payload.type = normalizedType; } if (normalizedFileName !== undefined) { payload.file_name = normalizedFileName; } if (normalizedFields !== undefined) { payload.fields = normalizedFields; } if (isEnabled !== undefined) { payload.is_enabled = Number(isEnabled) ? 1 : 0; } if (remark !== undefined) { payload.remark = String(remark || '').slice(0, 500); } let saved; if (existing) { if (existing.deleted_at) { // 命中软删记录:恢复后按入参更新 await existing.restore(); } await existing.update(payload); saved = existing; } else { const created = await model.create(payload); saved = created && created.toJSON ? created.toJSON() : created; } return this.definitionToView(saved); } /** * 按 ID 查找报表定义(paranoid: false,软删记录也返回,供恢复与校验复用)。 * @param {Object} model ReportDefinition 模型 * @param {number|null} id 报表定义ID(null 时直接返回 null) * @return {Promise} 记录实例(含软删记录),不存在返回 null */ async findDefinitionById(model, id) { if (id === null || Number(id) <= 0) { return null; } return model.findOne({ where: { id: Number(id) }, paranoid: false, }); } /** * 分页查询报表定义列表(name 模糊、type/is_enabled 精确,sortField 白名单)。 * @param {Object} [options={}] 入参 * @param {string} [options.nameKeyword=''] name 模糊关键字 * @param {string} [options.type=''] 报表类型精确筛选(注册方法 key) * @param {number|string} [options.isEnabled=null] 启用状态精确筛选(0/1) * @param {Object} [options.pagination={}] 分页 { page, pageSize } * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 */ async listDefinitions({ nameKeyword = '', type = '', isEnabled = null, pagination = {}, sort = {}, } = {}) { const { ctx } = this; const model = ctx.model && ctx.model.ReportDefinition; if (!model) { throw new Error('报表定义模型 ReportDefinition 不可用'); } const { Op } = ctx.app.Sequelize; const escapeLike = value => String(value || '').replace(/[\\%_]/g, match => `\\${match}`); const where = {}; const normalizedNameKeyword = String(nameKeyword || '').trim(); if (normalizedNameKeyword) { where.name = { [Op.like]: `%${escapeLike(normalizedNameKeyword)}%` }; } const normalizedType = String(type || '').trim(); if (normalizedType) { this.resolveTypeEntry(normalizedType); where.type = normalizedType; } if (isEnabled !== null && isEnabled !== undefined && isEnabled !== '') { where.is_enabled = Number(isEnabled) ? 1 : 0; } const page = Math.max(1, Math.floor(Number(pagination.page) || 1)); const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20))); const allowedSortFields = [ 'id', 'name', 'type', 'is_enabled', 'created_at', 'updated_at' ]; const sortField = String(sort.sortField || sort.sort_field || 'id').trim(); const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC'; const order = allowedSortFields.includes(sortField) ? [[ sortField, sortOrder ]] : [[ 'id', 'DESC' ]]; const [ rows, total ] = await Promise.all([ model.findAll({ where, order, offset: (page - 1) * pageSize, limit: pageSize, raw: true, }), model.count({ where }), ]); return { list: (Array.isArray(rows) ? rows : []).map(row => this.definitionToView(row)), total: Number(total) || 0, page, pageSize, }; } /** * 软删除报表定义。 * 删除前检查投递计划引用:仅拦截「启用中」的计划,停用计划不阻断—— * 停用计划不再生产投递任务,历史投递日志按 report_definition_id 关联不受定义删除影响。 * 重复删除同一 ID 按幂等成功处理,避免前端重复点击报错。 * @param {Object} options 入参 * @param {number|string} options.id 报表定义ID(必填,正整数) * @return {Promise<{id: number, deleted: number}>} 删除结果(deleted 恒为 1) * @throws {Error} ID 非法、定义不存在或存在启用中的投递计划引用时抛出业务可读错误 */ async deleteDefinition({ id } = {}) { const { ctx } = this; const model = ctx.model && ctx.model.ReportDefinition; if (!model) { throw new Error('报表定义模型 ReportDefinition 不可用'); } const normalizedId = Number(id) || 0; if (!Number.isInteger(normalizedId) || normalizedId <= 0) { throw new Error('报表ID id 必须为正整数'); } // 引用拦截:仅统计启用中的投递计划(enabled=1) const planModel = ctx.model && ctx.model.ReportDeliveryPlan; if (planModel && typeof planModel.count === 'function') { const activePlanCount = await planModel.count({ where: { report_definition_id: normalizedId, enabled: 1, }, }); if (activePlanCount > 0) { throw new Error(`存在 ${activePlanCount} 个启用的投递计划引用该报表,请先停用计划`); } } const existing = await this.findDefinitionById(model, normalizedId); if (!existing) { throw new Error(`报表定义不存在: id=${normalizedId}`); } if (existing.deleted_at) { return { id: normalizedId, deleted: 1 }; } await existing.destroy(); return { id: normalizedId, deleted: 1 }; } } module.exports = ReportService;