diff --git a/README.md b/README.md index d237237..2ecfed1 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ - Method 路由映射说明:`AI_METHOD_ROUTING.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` +- 配置驱动报表配置说明:`docs/report-config-guide.md` - 日报:`day.log` ## 项目目录结构 @@ -39,6 +40,7 @@ - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 +- `docs/report-config-guide.md`:配置驱动通用报表(wms_report_definition 三段 JSON 配置、内置查询器口径)与货主定时投递说明。 - `day.log`:每日工作留痕。 ## 快速开始 diff --git a/app/lib/report/day_window.js b/app/lib/report/day_window.js new file mode 100644 index 0000000..9b30a27 --- /dev/null +++ b/app/lib/report/day_window.js @@ -0,0 +1,171 @@ +'use strict'; + +/** + * 报表「日窗口」纯函数工具模块(无 ctx 依赖,可单测)。 + * + * 日窗口定义:[D 07:00, D+1 07:00) 半开区间(毫秒时间戳), + * 与旧 PHP《7日出入库数据》(Wms.php putout_putin_storage7) 的 + * 07:00 切日口径保持一致,统一使用服务器本地时区(不依赖 UTC)。 + */ + +const DEFAULT_DAY_COUNT = 7; +const DEFAULT_CUTOVER_HOUR = 7; + +/** + * 数字补零为两位字符串。 + * @param {number} value 数值 + * @return {string} 补零后的两位字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 按本地时区构建连续的日窗口列表(最旧在前)。 + * + * 规则: + * 1. 每个窗口为 [D 07:00, D+1 07:00)(cutoverHour 可配置),start 含、end 不含; + * 2. 最新窗口是「包含 now 的窗口」:now 当日已过切点时从今日切点起算, + * 未过切点时从昨日切点起算; + * 3. 窗口共 dayCount 个,按时间从旧到新排列; + * 4. 通过 `new Date(y, m, d + offset, hour)` 构造,规避夏令时导致的 24h 步进偏差。 + * + * @param {Object} [options={}] 构建选项 + * @param {number} [options.dayCount=7] 窗口数量 + * @param {number} [options.cutoverHour=7] 切点小时(0-23) + * @param {number|Date} [options.now=Date.now()] 参考时刻 + * @return {Array<{start: number, end: number}>} 日窗口列表(毫秒,最旧在前) + */ +function buildDayWindows({ dayCount = DEFAULT_DAY_COUNT, cutoverHour = DEFAULT_CUTOVER_HOUR, now = Date.now() } = {}) { + const normalizedCount = Math.max(1, Math.floor(Number(dayCount) || DEFAULT_DAY_COUNT)); + const normalizedHour = Math.min(23, Math.max(0, Math.floor(Number(cutoverHour) || 0))); + const current = new Date(Number(now) || Date.now()); + + // 今天切点:本地时区当日 07:00 + let anchor = new Date( + current.getFullYear(), + current.getMonth(), + current.getDate(), + normalizedHour, + 0, + 0, + 0 + ); + + // 未到今日切点:最新窗口尚未开始,从昨日切点起算 + if (current.getTime() < anchor.getTime()) { + anchor = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() - 1, + normalizedHour, + 0, + 0, + 0 + ); + } + + const windows = []; + for (let index = 0; index < normalizedCount; index += 1) { + // 最旧在前:dayOffset 从 -(count-1) 递增到 0 + const dayOffset = index - (normalizedCount - 1); + const start = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset, + normalizedHour, + 0, + 0, + 0 + ); + const end = new Date( + anchor.getFullYear(), + anchor.getMonth(), + anchor.getDate() + dayOffset + 1, + normalizedHour, + 0, + 0, + 0 + ); + windows.push({ + start: start.getTime(), + end: end.getTime(), + }); + } + + return windows; +} + +/** + * 按 PHP date() 风格的 token 格式化窗口开始日期(本地时区,无前导零)。 + * + * 支持的 token: + * Y=四位年;y=两位年;m=补零月;n=无前导零月;d=补零日;j=无前导零日; + * H=补零小时;i=补零分钟;s=补零秒。其余字符原样保留。 + * + * @param {Array<{start: number, end: number}>} windows 日窗口列表 + * @param {number} index 窗口下标 + * @param {string} [pattern='Y/n/j'] 日期格式模板(如 '2026/8/23') + * @return {string} 格式化后的日期字符串 + */ +function formatWindowStart(windows, index, pattern = 'Y/n/j') { + const windowItem = Array.isArray(windows) ? windows[index] : null; + if (!windowItem || !Number.isFinite(Number(windowItem.start))) { + return ''; + } + + const date = new Date(Number(windowItem.start)); + const tokens = { + Y: String(date.getFullYear()), + y: String(date.getFullYear()).slice(2), + m: pad2(date.getMonth() + 1), + n: String(date.getMonth() + 1), + d: pad2(date.getDate()), + j: String(date.getDate()), + H: pad2(date.getHours()), + i: pad2(date.getMinutes()), + s: pad2(date.getSeconds()), + }; + + return String(pattern || 'Y/n/j').replace(/[YymndjHis]/g, character => tokens[character]); +} + +/** + * 取时刻的本地 'HH:mm'(补零)。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'HH:mm' 格式字符串 + */ +function hhmmOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${pad2(normalizedDate.getHours())}:${pad2(normalizedDate.getMinutes())}`; +} + +/** + * 取时刻的本地自然日('YYYY-MM-DD')。 + * @param {Date|number} date 日期对象或毫秒时间戳 + * @return {string} 'YYYY-MM-DD' 格式字符串 + */ +function scheduleDateOf(date) { + const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now()); + return `${normalizedDate.getFullYear()}-${pad2(normalizedDate.getMonth() + 1)}-${pad2(normalizedDate.getDate())}`; +} + +/** + * 从窗口参数对象解析 dayCount/cutoverHour,供查询器与元数据接口共用。 + * 口径与查询器保持一致:dayCount 缺省 7(<=0 视为 7),cutoverHour 缺省 7 且钳制到 0-23。 + * @param {Object} [params={}] 窗口参数(支持 dayCount/day_count、cutoverHour/cutover_hour) + * @return {{dayCount: number, cutoverHour: number}} 归一化窗口参数 + */ +function resolveWindowConfig(params = {}) { + const dayCount = Math.max(1, Math.floor(Number(params.dayCount || params.day_count || 7))); + const cutoverHour = Math.min(23, Math.max(0, Math.floor(Number(params.cutoverHour ?? params.cutover_hour ?? 7)))); + return { dayCount, cutoverHour }; +} + +module.exports = { + buildDayWindows, + formatWindowStart, + hhmmOf, + scheduleDateOf, + resolveWindowConfig, +}; diff --git a/app/lib/report/formatters.js b/app/lib/report/formatters.js new file mode 100644 index 0000000..4d1b61d --- /dev/null +++ b/app/lib/report/formatters.js @@ -0,0 +1,167 @@ +'use strict'; + +/** + * 报表单元格格式化器注册表(纯函数模块,无 ctx 依赖,可单测)。 + * + * 设计约定: + * 1. 所有格式化器首参为单元格原始值(value),其余参数为格式化参数; + * 2. 数值计算统一走「截断取整」(等价旧 PHP 的 intval 语义,向零取整); + * 3. 低库存补偿口径与旧 PHP《7日出入库数据》保持一致: + * 可用库存 < 20 且 7 日入库 < 20 时视为低库存,触发补偿与预警。 + */ + +/** + * 安全转数值:非有限数值一律按 0 处理。 + * @param {*} value 原始值 + * @return {number} 数值 + */ +function toFiniteNumber(value) { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +} + +/** + * 截断取整(PHP intval 语义,向零取整)。 + * @param {*} value 原始值 + * @return {number} 整数 + */ +function integer(value) { + return Math.trunc(toFiniteNumber(value)); +} + +/** + * 零值占位:0 / '0' / null / undefined / '' 统一显示为 '-'。 + * 说明:'0' 一并转 '-',与 PHP empty('0') 为真的旧口径保持一致。 + * @param {*} value 原始值 + * @return {*} 非零原值或 '-' + */ +function zeroToDash(value) { + if (value === 0 || value === '0' || value === null || value === undefined || value === '') { + return '-'; + } + return value; +} + +/** + * 布尔转中文:真值 → '是',假值 → '否'。 + * 说明:''、0、'0'、null、undefined、false 均视为假,与 PHP 布尔语义对齐。 + * @param {*} flag 原始值 + * @return {string} '是' 或 '否' + */ +function yesNo(flag) { + const falsy = flag === false + || flag === null + || flag === undefined + || flag === '' + || flag === 0 + || flag === '0' + || String(flag).toLowerCase() === 'false'; + return falsy ? '否' : '是'; +} + +/** + * 7 日日均 ×10 取整(保留一位小数但避免浮点误差)。 + * 公式:int(total / days * 10),与旧 PHP intval($ck / 7 * 10) 一致。 + * @param {*} value 周期合计值 + * @param {*} days 天数 + * @return {number} 日均×10 的整数 + */ +function avgDaysPerWeek(value, days) { + const total = toFiniteNumber(value); + const dayCount = toFiniteNumber(days); + if (dayCount <= 0) { + return 0; + } + return Math.trunc((total / dayCount) * 10); +} + +/** + * 建议补货量(含低库存补偿): + * 基础值 int(ck_total / 7 * 10);仅当低库存(available < 20 且 rk_total < 20)时 + * 补偿到不低于 30(保证低库存货主获得最小补货建议)。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {number} 建议补货量 + */ +function suggestWithCompensate(ckTotal, available, rkTotal) { + const base = Math.trunc((toFiniteNumber(ckTotal) / 7) * 10); + const availableNumber = toFiniteNumber(available); + const rkNumber = toFiniteNumber(rkTotal); + if (availableNumber < 20 && rkNumber < 20) { + return Math.max(base, 30); + } + return base; +} + +/** + * 库存预警判定(布尔): + * 1. 按 7 日均出库 ×4 折算的周转阈值高于可用库存(int(ck/7*4) - available > 0); + * 2. 或处于低库存状态(available < 20 且 rk_total < 20)。 + * 展示时建议叠加 yesNo 格式化器转中文。 + * @param {*} ckTotal 7 日总出库 + * @param {*} available 可用库存 + * @param {*} rkTotal 7 日总入库 + * @return {boolean} 是否预警 + */ +function warnOf(ckTotal, available, rkTotal) { + const threshold = Math.trunc((toFiniteNumber(ckTotal) / 7) * 4); + return threshold - toFiniteNumber(available) > 0 + || (toFiniteNumber(available) < 20 && toFiniteNumber(rkTotal) < 20); +} + +/** + * 文本前缀工厂:返回一个给文本加前缀的格式化函数。 + * 典型用法:`'` 前缀防科学计数法(Excel 将长数字串强制按文本展示)。 + * @param {string} [prefix=''] 前缀 + * @return {Function} 格式化函数 (value) => `${prefix}${value}` + */ +function textPrefix(prefix = '') { + return value => `${String(prefix || '')}${value === null || value === undefined ? '' : String(value)}`; +} + +/** + * 格式化器注册表(配置驱动报表按名称引用)。 + * @type {Object} + */ +const FORMATTERS = Object.freeze({ + textPrefix: (value, prefix) => textPrefix(prefix)(value), + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}); + +/** + * 按名称应用格式化器。 + * @param {string} name 格式化器名称 + * @param {*} value 单元格原始值 + * @param {...*} args 格式化器额外参数 + * @return {*} 格式化结果 + * @throws {Error} 未知格式化器名称时抛出 + */ +function applyFormat(name, value, ...args) { + const formatterName = String(name || '').trim(); + if (!formatterName) { + return value; + } + const formatter = FORMATTERS[formatterName]; + if (typeof formatter !== 'function') { + throw new Error(`未知的报表格式化器: ${formatterName}`); + } + return formatter(value, ...args); +} + +module.exports = { + FORMATTERS, + applyFormat, + textPrefix, + zeroToDash, + yesNo, + integer, + avgDaysPerWeek, + suggestWithCompensate, + warnOf, +}; diff --git a/app/lib/report/notifyTemplate.js b/app/lib/report/notifyTemplate.js new file mode 100644 index 0000000..e3b0149 --- /dev/null +++ b/app/lib/report/notifyTemplate.js @@ -0,0 +1,101 @@ +'use strict'; + +/** + * 货主报表文本通知模板渲染器(纯函数模块,无 ctx 依赖,可单测)。 + * + * 标签白名单(其余 {xxx} 一律不替换,保存入口由 reportDelivery.savePlan 校验拦截): + * - {time} 发送时间,格式 YYYY-MM-DD HH:mm + * - {url} 报表文件下载链接(url 为空时替换为兜底文案) + * - {report_name} 报表名称 + * - {biz_date} 数据日期 YYYY-MM-DD + */ + +/** 模板标签白名单 */ +const ALLOWED_TAGS = Object.freeze([ 'time', 'url', 'report_name', 'biz_date' ]); + +/** + * url 为空时的兜底文案。 + * 理由:生成结果 url 可能因异步上传尚未就绪,以占位文案保证通知可达, + * 避免因链接缺失引发整链路失败重试风暴;实际链接可在投递记录中查看。 + */ +const EMPTY_URL_FALLBACK = '文件生成中,稍后可在投递记录中查看'; + +/** 模板标签匹配正则:{xxx} 占位 */ +const TAG_PATTERN = /\{([^{}]+)\}/g; + +/** + * 提取模板中出现过的全部标签名(按出现顺序,含重复项)。 + * @param {string} template 模板字符串 + * @return {Array} 标签名数组 + */ +function extractTagNames(template) { + const names = []; + const source = String(template || ''); + let match = TAG_PATTERN.exec(source); + while (match) { + names.push(String(match[1]).trim()); + match = TAG_PATTERN.exec(source); + } + return names; +} + +/** + * 校验模板标签是否全部位于白名单内(未知标签不替换、保存时拒绝)。 + * @param {string} template 模板字符串 + * @return {{valid: boolean, invalidTags: Array}} 校验结果(invalidTags 已去重) + */ +function validateNotifyTemplate(template) { + const names = extractTagNames(template); + const invalidSet = new Set(); + for (const name of names) { + if (!ALLOWED_TAGS.includes(name)) { + invalidSet.add(name); + } + } + return { valid: invalidSet.size === 0, invalidTags: [ ...invalidSet ] }; +} + +/** + * 渲染通知模板:仅替换白名单标签,未知标签原样保留(保存入口已校验拦截)。 + * @param {string} template 模板字符串 + * @param {Object} [context={}] 渲染上下文 + * @param {string} [context.time=''] 发送时间(YYYY-MM-DD HH:mm) + * @param {string} [context.url=''] 报表文件下载链接(空则替换为兜底文案) + * @param {string} [context.reportName=''] 报表名称 + * @param {string} [context.bizDate=''] 数据日期(YYYY-MM-DD) + * @return {string} 渲染后的通知文本 + */ +function renderNotifyTemplate(template, context = {}) { + const url = String((context && context.url) || '').trim() || EMPTY_URL_FALLBACK; + const replacements = { + time: String((context && context.time) || ''), + url, + report_name: String((context && context.reportName) || ''), + biz_date: String((context && context.bizDate) || ''), + }; + return String(template || '').replace(TAG_PATTERN, (raw, name) => { + const key = String(name).trim(); + return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : raw; + }); +} + +/** + * 格式化发送时间为 YYYY-MM-DD HH:mm(服务器本地时区)。 + * @param {Date} [date=new Date()] 时刻 + * @return {string} 格式化后的时间字符串 + */ +function formatNotifyTime(date) { + const target = date instanceof Date ? date : new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())} ` + + `${pad(target.getHours())}:${pad(target.getMinutes())}`; +} + +module.exports = { + ALLOWED_TAGS, + EMPTY_URL_FALLBACK, + extractTagNames, + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +}; diff --git a/app/lib/report/render.js b/app/lib/report/render.js new file mode 100644 index 0000000..1b82da8 --- /dev/null +++ b/app/lib/report/render.js @@ -0,0 +1,233 @@ +'use strict'; + +const { applyFormat } = require('./formatters'); +const { formatWindowStart } = require('./day_window'); + +/** + * 报表渲染翻译层(纯函数模块,无 ctx 依赖,可单测)。 + * + * 输入:报表类型 type 的硬编码字段注册清单(fields,按勾选顺序)+ 查询器产出的数据 rows; + * 输出:适配 `app/service/systems/excel.js` 的 sheets 参数结构 + * ({ name, columns, rows, merges, styledRows, textColumns? })。 + * + * 约定(与 excel.js 的 buildExcelJsWorkbook 对齐): + * 1. 数据以 AOA(二维数组)形式输出,表头行内联在 rows 首位,columns 恒传空数组; + * 2. merges 统一输出 {s:{r,c}, e:{r,c}} 结构(excel.js 两套构建器均支持); + * 3. textColumns 输出 0 基列索引,由 excel.js 落地为文本单元格。 + * + * 列规则(全部由字段注册清单硬编码决定,无 sheet_config 自定义): + * 1. string 字段 → 静态列(header=label),asText=true 时加入 textColumns; + * 2. number 字段 → 静态列,统一 zeroToDash(0/''/null 显示 '-'); + * 3. boolean 字段 → 静态列,统一 yesNo(真→是,假→否); + * 4. array 字段 → 窗口展开列:per=窗口数,pair=children keys,表头第 1 行按窗口 + * 输出 '{date}' 日期(Y/n/j 无前导零)并在每窗口 pair.length>1 时横向合并, + * 表头第 2 行按 children label 填充;子字段为 number 时单元格统一 zeroToDash; + * 5. 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2)。 + */ + +/** + * 判断字段是否为普通对象。 + * @param {*} field 待判断字段 + * @return {boolean} 是否普通对象 + */ +function isPlainObject(field) { + return Boolean(field) && typeof field === 'object' && !Array.isArray(field); +} + +/** + * 规范化字段注册清单:仅保留含 key 的对象,key 统一为字符串。 + * @param {Array} fields 字段清单(注册表 fields,按勾选顺序) + * @return {Array} 规范化字段清单 + */ +function normalizeFields(fields) { + if (!Array.isArray(fields)) { + return []; + } + return fields + .filter(field => isPlainObject(field) && String(field.key || '').trim()) + .map(field => ({ ...field, key: String(field.key).trim() })); +} + +/** + * 按类型字段清单构建列计划(含窗口展开与表头合并)。 + * @param {Object} [options={}] 构建选项 + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.windows=[]] 日窗口列表(展开列 per 取窗口数) + * @return {{columns: Array, headerRowCount: number, generatedMerges: Array}} 列计划 + */ +function buildColumnPlan({ fields = [], windows = [] } = {}) { + const safeFields = normalizeFields(fields); + const safeWindows = Array.isArray(windows) ? windows : []; + const expandPer = Math.max(1, safeWindows.length || 7); + + const columns = []; + const generatedMerges = []; + let expandStartColumn = -1; + + for (const field of safeFields) { + if (field.type === 'array') { + const children = Array.isArray(field.children) ? field.children : []; + const pair = children.length > 0 ? children : [{ key: 'value', label: '值', type: 'string' }]; + expandStartColumn = columns.length; + for (let windowIndex = 0; windowIndex < expandPer; windowIndex += 1) { + for (let pairIndex = 0; pairIndex < pair.length; pairIndex += 1) { + columns.push({ + type: 'expand', + windowIndex, + pairIndex, + pair: pair[pairIndex] && isPlainObject(pair[pairIndex]) ? pair[pairIndex] : {}, + headerRow1Template: '{date}', + headerRow2List: pair.map(child => String((child && child.label) || '')), + }); + } + if (pair.length > 1) { + // 每窗口多列表头横向合并(如 D1:E1 … P1:Q1) + const groupStart = expandStartColumn + windowIndex * pair.length; + generatedMerges.push({ + s: { r: 0, c: groupStart }, + e: { r: 0, c: groupStart + pair.length - 1 }, + }); + } + } + continue; + } + columns.push({ + type: field.type === 'array' ? 'static' : (field.type || 'string'), + header: String(field.label || field.key || ''), + field: field.key, + asText: field.asText === true, + }); + } + + const hasExpandColumn = columns.some(column => column.type === 'expand'); + const headerRowCount = hasExpandColumn ? 2 : 1; + + // 两行表头下,非展开列按列纵向合并(A1:A2 等) + if (headerRowCount === 2) { + columns.forEach((column, columnIndex) => { + if (column.type !== 'expand') { + generatedMerges.push({ + s: { r: 0, c: columnIndex }, + e: { r: 1, c: columnIndex }, + }); + } + }); + } + + return { + columns, + headerRowCount, + generatedMerges, + }; +} + +/** + * 构建表头第 1 行(展开列按窗口开始日期输出 'Y/n/j' 无前导零)。 + * @param {Array} columns 列计划 + * @param {Array} windows 日窗口列表 + * @return {Array} 表头第 1 行 + */ +function buildHeaderRow1(columns, windows = []) { + return columns.map(column => { + if (column.type === 'expand') { + return formatWindowStart(windows, column.windowIndex, 'Y/n/j'); + } + return column.header; + }); +} + +/** + * 构建表头第 2 行(单行表头模式下返回 null;展开列按 pair label 填充)。 + * @param {Array} columns 列计划 + * @param {number} headerRowCount 表头行数 + * @return {Array|null} 表头第 2 行 + */ +function buildHeaderRow2(columns, headerRowCount) { + if (headerRowCount !== 2) { + return null; + } + return columns.map(column => { + if (column.type === 'expand') { + const list = column.headerRow2List; + return list.length > 0 ? list[column.pairIndex % list.length] || '' : ''; + } + return ''; + }); +} + +/** + * 渲染单个单元格(按列类型与字段类型硬编码格式化口径)。 + * @param {Object} column 列计划 + * @param {Object} row 数据行 + * @return {*} 单元格值 + */ +function renderCell(column, row = {}) { + if (column.type === 'expand') { + const daily = Array.isArray(row.daily) ? row.daily : []; + const day = daily[column.windowIndex]; + const value = day && typeof day === 'object' ? day[column.pair.key] : 0; + return applyFormat(column.pair.type === 'number' ? 'zeroToDash' : '', value); + } + + const value = row[column.field]; + if (column.type === 'boolean') { + return applyFormat('yesNo', value); + } + if (column.type === 'number') { + return applyFormat('zeroToDash', value); + } + return value; +} + +/** + * 按类型字段注册清单渲染 sheet(配置极简:无 sheet_config 自定义列/合并/样式)。 + * + * @param {Object} [options={}] 渲染选项 + * @param {string} [options.type=''] 报表类型(查询器注册 key,仅透传不参与渲染口径) + * @param {string} [options.title='报表'] sheet 名称(报表标题) + * @param {Array} [options.fields=[]] 字段注册清单(按勾选顺序) + * @param {Array} [options.rows=[]] 查询器产出的数据行 + * @param {Array} [options.windows=[]] 日窗口列表 + * @return {Object} excel.js sheet 参数 + * ({name, columns, rows, merges, styledRows},存在 asText 列时附带 textColumns) + */ +function renderSheetByType({ type = '', title = '报表', fields = [], rows = [], windows = [] } = {}) { + void type; + const plan = buildColumnPlan({ fields, windows }); + const safeRows = Array.isArray(rows) ? rows : []; + + const headerRow1 = buildHeaderRow1(plan.columns, windows); + const headerRow2 = buildHeaderRow2(plan.columns, plan.headerRowCount); + + const aoaRows = [ headerRow1 ]; + if (headerRow2) { + aoaRows.push(headerRow2); + } + for (const row of safeRows) { + aoaRows.push(plan.columns.map(column => renderCell(column, row))); + } + + // asText 列收集为 0 基列索引,交由 excel.js 落地文本单元格(无 asText 时不输出) + const textColumns = plan.columns + .map((column, columnIndex) => (column.asText ? columnIndex : -1)) + .filter(columnIndex => columnIndex >= 0); + + const result = { + name: String(title || '报表'), + columns: [], + rows: aoaRows, + merges: plan.generatedMerges, + styledRows: [], + }; + + if (textColumns.length > 0) { + result.textColumns = textColumns; + } + + return result; +} + +module.exports = { + renderSheetByType, + buildColumnPlan, +}; diff --git a/app/model/report_definition.js b/app/model/report_definition.js new file mode 100644 index 0000000..32a9693 --- /dev/null +++ b/app/model/report_definition.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 报表模板定义 Model。 + * 报表采用「配置驱动」:name/type(注册方法 key)/file_name(导出文件名模板)/fields(勾选字段), + * 唯一性由主键 id 承担,新报表只需加配置行,免发版。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDefinition = app.model.define('report_definition', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + type: { + type: STRING(50), + allowNull: false, + comment: '报表类型(内置查询器注册 key,如 stockFlow)', + }, + file_name: { + type: STRING(200), + allowNull: false, + comment: '导出文件名模板(支持 {date} 占位,如 7日出入库_{date}.xlsx)', + }, + fields: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '勾选的字段 key 数组(列头/合并/样式/格式化由类型硬编码字段规格决定)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_definition', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表模板定义表', + indexes: [ + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDefinition; +}; diff --git a/app/model/report_delivery_log.js b/app/model/report_delivery_log.js new file mode 100644 index 0000000..29a68a4 --- /dev/null +++ b/app/model/report_delivery_log.js @@ -0,0 +1,134 @@ +'use strict'; + +/** + * 报表投递记录 Model。 + * 状态机 pending → exporting → delivered/failed/cancelled; + * 失败按退避重试(retry_count/next_retry_at),幂等键 + * uk_store_report_biz_time 保证同一货主同一报表定义同一数据日期同一时间点不重复投递; + * report_definition_id 关联报表定义,report_name 为投递时报表名称快照(审计回放)。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, DATEONLY } = app.Sequelize; + + const ReportDeliveryLog = app.model.define('report_delivery_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + report_name: { + type: STRING(100), + allowNull: true, + comment: '报表名称快照(投递时的定义 name,审计回放)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + comment: '投递成功时间', + }, + notify_targets: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '报表投递记录表', + indexes: [ + { name: 'uk_store_report_biz_time', unique: true, fields: [ 'store_id', 'report_definition_id', 'biz_date', 'time_point', 'deleted_at' ] }, + { name: 'idx_status_id', fields: [ 'status', 'id' ] }, + { name: 'idx_status_updated_at', fields: [ 'status', 'updated_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryLog; +}; diff --git a/app/model/report_delivery_plan.js b/app/model/report_delivery_plan.js new file mode 100644 index 0000000..83b3cf0 --- /dev/null +++ b/app/model/report_delivery_plan.js @@ -0,0 +1,115 @@ +'use strict'; + +/** + * 货主报表投递计划 Model。 + * 每个货主(store_id)对每个报表定义(report_definition_id)可配置每日多个投递时间点 + * (schedule_times JSON 数组),由分钟级扫描调度按 HH:mm 命中后生成并投递报表。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, TINYINT, DATE } = app.Sequelize; + + const ReportDeliveryPlan = app.model.define('report_delivery_plan', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_definition_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '报表定义ID(wms_report_definition.id)', + }, + name: { + type: STRING(100), + allowNull: true, + comment: '计划名称(前端展示用,缺省时可用报表名称兜底)', + }, + schedule_times: { + type: app.Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + notify_template: { + type: STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }, + notify_group_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }, + notify_member_ids: { + type: app.Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_report_delivery_plan', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + deletedAt: 'deleted_at', + paranoid: true, + comment: '货主报表投递计划表', + indexes: [ + { name: 'uk_store_report_definition', unique: true, fields: [ 'store_id', 'report_definition_id', 'deleted_at' ] }, + { name: 'idx_enabled_deleted', fields: [ 'enabled', 'deleted_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return ReportDeliveryPlan; +}; diff --git a/app/schedule/report_delivery_dispatch.js b/app/schedule/report_delivery_dispatch.js new file mode 100644 index 0000000..8f8ab29 --- /dev/null +++ b/app/schedule/report_delivery_dispatch.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * 货主报表定时投递调度。 + * 每分钟在单 worker 中扫描一次 wms_report_delivery_plan, + * 命中投递时间点(含宽限)后幂等生成并投递报表(进程内布尔防重入)。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行报表投递调度。 + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._reportDeliveryDispatchRunning) { + return; + } + + ctx.app._reportDeliveryDispatchRunning = true; + + try { + const summary = await ctx.service.systems.reportDelivery.dispatch(); + + ctx.logger.info( + `[report-delivery-dispatch] 本轮投递完成:扫描 ${summary && summary.scanned || 0} 个计划,` + + `投递 ${summary && summary.delivered || 0},失败 ${summary && summary.failed || 0},` + + `跳过 ${summary && summary.skipped || 0}` + ); + } catch (error) { + ctx.logger.error(`[report-delivery-dispatch] 投递调度执行失败: ${error.message}`); + } finally { + ctx.app._reportDeliveryDispatchRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/report.js b/app/service/systemMethods/report.js new file mode 100644 index 0000000..8c219af --- /dev/null +++ b/app/service/systemMethods/report.js @@ -0,0 +1,294 @@ +'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,meta'; + const _noNeedLog = 'generate,generateTaskProgress'; + const _noNeedAuth = 'generate,generateTaskProgress,meta'; + 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 {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id) + * @return {Promise} 统一 success 包装,data 为报表元数据 + */ + async meta(data = {}) { + const { service } = this; + const { + report_id: reportIdSnake, + reportId: reportIdCamel, + } = data; + + const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0; + if (!Number.isInteger(reportId) || reportId <= 0) { + return this.fail('报表ID report_id 必须为正整数'); + } + + const reportMeta = await service.systems.report.getMeta({ reportId }); + const { id, ...rest } = reportMeta; + + return this.success('ok', { + report_id: id, + ...rest, + }); + } + + /** + * 查询报表导出任务进度。 + * @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; diff --git a/app/service/systemMethods/report/definition.js b/app/service/systemMethods/report/definition.js new file mode 100644 index 0000000..94ce9af --- /dev/null +++ b/app/service/systemMethods/report/definition.js @@ -0,0 +1,137 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.definition(报表定义管理接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/report。 + */ +class ReportDefinitionMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // typeList 为只读公共元数据:免权限/免鉴权/免日志(与 report.meta 惯例一致),仍要求登录; + // save/list/delete 属定义管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = 'typeList'; + const _noNeedLog = 'typeList'; + const _noNeedAuth = 'typeList'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询报表类型注册清单(内置查询器 + 标题/描述/窗口参数 + 全量字段清单)。 + * 免权限只读(仅登录),供前端报表配置页渲染类型下拉与字段勾选。 + * @param {Object} data 请求体(无必填参数,兼容空对象) + * @return {Promise} 统一 success 包装,data 为 { list: Array } 注册类型清单 + */ + async typeList(data = {}) { + void data; + const { service } = this; + const types = await service.systems.report.listRegisteredTypes(); + return this.success('ok', { + list: types, + }); + } + + /** + * 新增/更新报表定义(按 id upsert:未传 id 视为新增,未传字段不覆盖)。 + * @param {Object} data 请求体 + * @param {number} [data.id] 报表定义ID(正整数;不传视为新增) + * @param {string} data.name 报表名称(必填,≤100) + * @param {string} data.type 报表类型(注册方法 key,如 stockFlow;新增必填) + * @param {string} data.file_name 导出文件名模板(支持 {date};新增必填,≤200,兼容 fileName) + * @param {Array} data.fields 勾选字段 key 数组(新增必填,须为该类型注册字段子集) + * @param {number} [data.is_enabled] 是否启用(0/1) + * @param {string} [data.remark] 备注(≤500) + * @return {Promise} 统一 success 包装,data 为保存后的报表定义视图 + */ + async save(data = {}) { + const { service } = this; + const { + id, + name, + type, + file_name: fileNameSnake, + fileName: fileNameCamel, + fields, + is_enabled: isEnabled, + remark, + } = data; + + // 仅附加入参中存在的字段(undefined 不进入参数对象),保持「未传不覆盖」语义 + const saveArgs = { id, name, type }; + const normalizedFileName = fileNameCamel !== undefined ? fileNameCamel : fileNameSnake; + if (normalizedFileName !== undefined) { + saveArgs.fileName = normalizedFileName; + } + if (fields !== undefined) { + saveArgs.fields = fields; + } + if (isEnabled !== undefined) { + saveArgs.isEnabled = isEnabled; + } + if (remark !== undefined) { + saveArgs.remark = remark; + } + + try { + const result = await service.systems.report.saveDefinition(saveArgs); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义保存失败'); + } + } + + /** + * 分页查询报表定义列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(name 模糊关键字、type/is_enabled 精确) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder }(白名单:id/name/type/is_enabled/created_at/updated_at) + * @return {Promise} 统一 success 包装,data 为 { list, total, page, pageSize } + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + name: nameKeyword, + type, + is_enabled: isEnabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + try { + const result = await service.systems.report.listDefinitions({ + nameKeyword, + type, + isEnabled, + pagination, + sort, + }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义列表查询失败'); + } + } + + /** + * 软删除报表定义(存在启用中的投递计划引用时拦截)。 + * @param {Object} data 请求体 + * @param {number} data.id 报表定义ID(必填,正整数) + * @return {Promise} 统一 success 包装,data 为 { id, deleted } + */ + async delete(data = {}) { + const { service } = this; + const { id } = data; + + try { + const result = await service.systems.report.deleteDefinition({ id }); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '报表定义删除失败'); + } + } +} + +module.exports = ReportDefinitionMethodService; diff --git a/app/service/systemMethods/report/deliveryLog.js b/app/service/systemMethods/report/deliveryLog.js new file mode 100644 index 0000000..e9f0179 --- /dev/null +++ b/app/service/systemMethods/report/deliveryLog.js @@ -0,0 +1,50 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryLog(货主报表投递记录审计查询接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryLogMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 审计查询属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/status) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + status, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listLogs({ + storeId, + reportId, + status, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryLogMethodService; diff --git a/app/service/systemMethods/report/deliveryPlan.js b/app/service/systemMethods/report/deliveryPlan.js new file mode 100644 index 0000000..e75a63b --- /dev/null +++ b/app/service/systemMethods/report/deliveryPlan.js @@ -0,0 +1,130 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:report.deliveryPlan(货主报表投递计划接口包装层)。 + * 仅做出口包装与参数解构,业务逻辑下沉 systems/reportDelivery。 + */ +class ReportDeliveryPlanMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + // 计划管理属于管理类操作:不声明免权限,仅通配符角色(超级管理员/仓库管理员)可用, + // 后续由 wms_permission 同步流程按需授权,不扩大任何角色授权范围 + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 新增/更新投递计划(货主+报表定义ID唯一,存在则更新)。 + * @param {Object} data 请求体 + * @param {number} data.store_id 货主ID(必填) + * @param {number} data.report_id 报表定义ID(必填,兼容 reportId) + * @param {Array} data.schedule_times 每日投递时间点数组(HH:mm,自动去重排序) + * @param {string} [data.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [data.late_grace_minutes=60] 补投宽限分钟(0-1440) + * @param {string|null} [data.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [data.remark] 备注 + * @param {string} [data.notify_template] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array} [data.notify_group_ids] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array} [data.notify_member_ids] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 统一 success 包装 + */ + async save(data = {}) { + const { service } = this; + const { + store_id: storeId, + report_id: reportIdSnake, + reportId: reportIdCamel, + schedule_times: scheduleTimes, + channel, + late_grace_minutes: lateGraceMinutes, + name, + remark, + notify_template: notifyTemplate, + notify_group_ids: notifyGroupIds, + notify_member_ids: notifyMemberIds, + } = data; + + // 基础参数解构透传;通知类参数仅在入参存在时附加, + // 保持旧调用形状与既有回归断言一致(undefined 不进入参数对象) + const saveArgs = { + storeId, + reportId: reportIdCamel !== undefined ? reportIdCamel : reportIdSnake, + scheduleTimes, + channel, + lateGraceMinutes, + remark, + }; + if (name !== undefined) { + saveArgs.name = name; + } + if (notifyTemplate !== undefined) { + saveArgs.notifyTemplate = notifyTemplate; + } + if (notifyGroupIds !== undefined) { + saveArgs.notifyGroupIds = notifyGroupIds; + } + if (notifyMemberIds !== undefined) { + saveArgs.notifyMemberIds = notifyMemberIds; + } + + const result = await service.systems.reportDelivery.savePlan(saveArgs); + return this.success('ok', result); + } + + /** + * 快速复制投递计划到其他货主(目标已存在相同报表定义计划时跳过,不覆盖不报错)。 + * @param {Object} data 请求体 + * @param {number} data.id 源计划ID(必填,正整数) + * @param {Array} data.store_ids 目标货主ID数组(必填,兼容 storeIds 驼峰) + * @return {Promise} 统一 success 包装,data={ created, skipped } + */ + async copy(data = {}) { + const { service } = this; + const { + id, + store_ids: storeIdsSnake, + storeIds: storeIdsCamel, + } = data; + + // 兼容 storeIds 驼峰入参,优先取驼峰形式,保持与 save 的 reportId 兼容口径一致 + const storeIds = storeIdsCamel !== undefined ? storeIdsCamel : storeIdsSnake; + + const result = await service.systems.reportDelivery.copyPlan({ id, storeIds }); + return this.success('ok', result); + } + + /** + * 分页查询投递计划列表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件(store_id/report_id/enabled) + * @param {Object} [data.pagination] 分页 { page, pageSize } + * @param {Object} [data.sort] 排序 { sortField, sortOrder } + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + store_id: storeId, + report_id: reportId, + enabled, + } = whereValue; + const { pagination = {}, sort = {} } = data; + + const result = await service.systems.reportDelivery.listPlans({ + storeId, + reportId, + enabled, + pagination, + sort, + }); + return this.success('ok', result); + } +} + +module.exports = ReportDeliveryPlanMethodService; diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js index ac26405..64ab415 100644 --- a/app/service/systems/excel.js +++ b/app/service/systems/excel.js @@ -135,6 +135,7 @@ class ExcelService extends Service { buildWorksheet(sheetConfig = {}) { const { merges = [], + textColumns = [], } = sheetConfig; const { aoaData, @@ -151,6 +152,8 @@ class ExcelService extends Service { worksheet['!merges'] = merges; } + this.applyTextColumnsToSheetJs(worksheet, textColumns); + return worksheet; } @@ -198,6 +201,7 @@ class ExcelService extends Service { merges = [], embeddedImages = [], styledRows = [], + textColumns = [], } = sheetConfig; const { normalizedColumns, @@ -258,6 +262,10 @@ class ExcelService extends Service { this.applyStyledRows(worksheet, styledRows); } + if (Array.isArray(textColumns) && textColumns.length > 0) { + this.applyTextColumnsToExcelJs(worksheet, textColumns); + } + if (Array.isArray(embeddedImages) && embeddedImages.length > 0) { await this.addEmbeddedImages(workbook, worksheet, embeddedImages); } @@ -437,6 +445,74 @@ class ExcelService extends Service { }); } + /** + * SheetJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格类型强制为文本(t:'s')、值转字符串,并附加文本数字格式(z:'@'), + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet SheetJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToSheetJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(0, Math.floor(Number(index) || 0))) + ); + const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1'); + + for (let row = range.s.r; row <= range.e.r; row += 1) { + for (const column of columnSet) { + if (column > range.e.c) { + continue; + } + const address = XLSX.utils.encode_cell({ r: row, c: column }); + const cell = worksheet[address]; + if (!cell) { + continue; + } + if (cell.v !== null && cell.v !== undefined) { + cell.t = 's'; + cell.v = String(cell.v); + } + cell.z = '@'; + } + } + } + + /** + * ExcelJS 路径:将 textColumns 指定列落地为文本单元格。 + * 单元格值转为字符串(原始对象类型除外),并设置文本数字格式 numFmt='@', + * 防止长数字串被 Excel 按数值展示成科学计数法。 + * @param {Object} worksheet ExcelJS 工作表对象 + * @param {Array} [textColumns=[]] 0 基文本列索引列表 + * @return {void} 无返回值 + */ + applyTextColumnsToExcelJs(worksheet, textColumns = []) { + if (!worksheet || !Array.isArray(textColumns) || textColumns.length === 0) { + return; + } + + const columnSet = new Set( + textColumns.map(index => Math.max(1, Math.floor(Number(index) || 0) + 1)) + ); + + for (let row = 1; row <= worksheet.rowCount; row += 1) { + worksheet.getRow(row).eachCell({ includeEmpty: false }, (cell, columnNumber) => { + if (!columnSet.has(columnNumber)) { + return; + } + const value = cell.value; + if (value !== null && value !== undefined && typeof value !== 'object') { + cell.value = String(value); + } + cell.numFmt = '@'; + }); + } + } + async addEmbeddedImages(workbook, worksheet, embeddedImages = []) { for (const imageConfig of embeddedImages) { if (!imageConfig) { diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 192958b..ed67f7d 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -263,14 +263,19 @@ class NoticeService extends Service { const codes = notificationWebhookModel.getAvailableEventCodes() .map(item => String(item || '').trim().toLowerCase()) .filter(Boolean); - return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + // 默认注册事件码始终生效(与模型配置合并,便于服务内按现有模式追加新事件码) + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) { const codes = notificationWebhookModel.AVAILABLE_EVENTS .map(item => String(item && item.code || '').trim().toLowerCase()) .filter(Boolean); - return codes.length > 0 ? codes : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; + return codes.length > 0 + ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] + : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; diff --git a/app/service/systems/report.js b/app/service/systems/report.js new file mode 100644 index 0000000..318c041 --- /dev/null +++ b/app/service/systems/report.js @@ -0,0 +1,610 @@ +'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 模板的 {date} 占位)。 + * @param {Object} definition 报表定义视图 + * @param {string} [bizDate=''] 数据日期(YYYY-MM-DD,缺省用今天) + * @return {string} 文件名 + */ + buildFilename(definition, bizDate = '') { + const dateText = String(bizDate || '').trim() || scheduleDateOf(new Date()); + const template = String((definition && definition.file_name) || '').trim() + || `${String((definition && definition.name) || 'report')}_${dateText}.xlsx`; + const filename = template.includes('{date}') + ? template.replace(/\{date\}/g, dateText) + : template; + 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, + }); + + const uploadResult = await this.ctx.service.systems.excel.generateAndUpload({ + filename, + dir: `exports/report/${String(reportId).trim()}`, + 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', + }; + } + + /** + * 读取报表前端可读的列元数据(全量注册字段 + 勾选标记 + 窗口参数,不执行真实数据查询)。 + * @param {Object} options 入参 + * @param {number|string} options.reportId 报表定义ID + * @return {Promise} { id, name, type, file_name, window: {dayCount, cutoverHour}, fields } + */ + async getMeta({ reportId }) { + const definition = await this.getDefinition(reportId); + const entry = this.resolveTypeEntry(definition.type); + const selectedSet = new Set(definition.fields); + + return { + id: definition.id, + name: definition.name, + type: definition.type, + file_name: definition.file_name, + window: { + dayCount: Number((entry.window && entry.window.dayCount) || 7), + cutoverHour: Number((entry.window && entry.window.cutoverHour) || 7), + }, + fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({ + ...field, + selected: selectedSet.has(field.key), + })), + }; + } + + /** + * 新增/更新报表定义(按 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; diff --git a/app/service/systems/report/queries/index.js b/app/service/systems/report/queries/index.js new file mode 100644 index 0000000..45c85a5 --- /dev/null +++ b/app/service/systems/report/queries/index.js @@ -0,0 +1,57 @@ +'use strict'; + +const sevenDayStockFlow = require('./sevenDayStockFlow'); + +/** + * 报表内置查询器注册表。 + * key 对应 wms_report_definition.type; + * 新增查询器时在此登记,签名统一为 + * async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })。 + * 每个查询器需在模块上挂载静态字段清单 `fields`(如 module.exports.fields) + * 与缺省窗口参数 `defaultWindow`,供报表引擎 report.meta / report.definition.typeList 读取。 + * 注意:该对象会作为 service 模块导出,egg 加载器需要在其上挂载 + * `Symbol(EGG_LOADER_ITEM_FULLPATH)` 等内部符号,因此禁止对导出对象使用 + * Object.freeze / Object.seal / Object.preventExtensions。 + * @type {Object} + */ +const QUERIES = { + stockFlow: sevenDayStockFlow, +}; + +/** + * 注册表描述元数据:key/title/description/window/fields。 + * @type {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} + */ +const DESCRIPTIONS = [ + { + key: 'stockFlow', + title: '库存变化以及补货报表', + description: '按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、' + + '锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警', + window: { + ...(sevenDayStockFlow.defaultWindow || { dayCount: 7, cutoverHour: 7 }), + }, + fields: (Array.isArray(sevenDayStockFlow.fields) ? sevenDayStockFlow.fields : []).map(field => ({ ...field })), + }, +]; + +/** + * 输出注册表可读描述(含全量字段清单),供 report.definition.typeList / report.meta 复用。 + * 返回副本,避免调用方误改注册表元数据。 + * @return {Array<{key: string, title: string, description: string, window: Object, fields: Array}>} 注册描述列表 + */ +function describe() { + return DESCRIPTIONS.map(entry => ({ + ...entry, + window: { ...(entry.window || {}) }, + fields: (Array.isArray(entry.fields) ? entry.fields : []).map(field => ({ + ...field, + children: Array.isArray(field.children) ? field.children.map(child => ({ ...child })) : undefined, + })), + })); +} + +// egg 加载器要求导出对象可扩展,describe 作为方法属性挂在 QUERIES 上 +QUERIES.describe = describe; + +module.exports = QUERIES; diff --git a/app/service/systems/report/queries/sevenDayStockFlow.js b/app/service/systems/report/queries/sevenDayStockFlow.js new file mode 100644 index 0000000..6d541d4 --- /dev/null +++ b/app/service/systems/report/queries/sevenDayStockFlow.js @@ -0,0 +1,282 @@ +'use strict'; + +const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window'); +const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters'); + +/** + * 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据)。 + * key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段; + * asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法); + * daily 为数组类型,children 描述每日出入库子字段。 + * @type {Array} + */ +const FIELDS = Object.freeze([ + { key: 'stock_id', label: '库存ID', type: 'number' }, + { key: 'item_code', label: '商品编码', type: 'string', asText: true }, + { key: 'item_name', label: '商品名称', type: 'string' }, + { key: 'barcode', label: '条码', type: 'string', asText: true }, + { + key: 'daily', + label: '每日出入库', + type: 'array', + children: [ + { key: 'ck', label: '出库数', type: 'number' }, + { key: 'rk', label: '入库数', type: 'number' }, + ], + }, + { key: 'ck_total', label: '出库合计', type: 'number' }, + { key: 'rk_total', label: '入库合计', type: 'number' }, + { key: 'available', label: '可用库存', type: 'number' }, + { key: 'total', label: '总库存', type: 'number' }, + { key: 'pending', label: '待出库存', type: 'number' }, + { key: 'locked', label: '锁定数', type: 'number' }, + { key: 'ck_avg', label: '出库日均(×10)', type: 'number', computed: true }, + { key: 'rk_avg', label: '入库日均(×10)', type: 'number', computed: true }, + { key: 'stock_days', label: '预计可售天数', type: 'number', computed: true }, + { key: 'suggest', label: '建议补货量', type: 'number', computed: true }, + { key: 'warn', label: '库存预警', type: 'boolean', computed: true }, +]); + +/** + * stockFlow 查询器缺省窗口参数(与旧 7 日出入库口径一致,可被 params 覆盖)。 + * @type {{dayCount: number, cutoverHour: number}} + */ +const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 }); + +/** + * 内置查询器:库存变化以及补货报表(旧 PHP《7日出入库数据》Wms.php putout_putin_storage7 口径)。 + * + * 口径与假设(供测试复核): + * 1. 窗口:dayCount 个 [D cutoverHour:00, D+1 cutoverHour:00) 本地时区窗口 + * (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖); + * 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK, + * 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck; + * 3. 可用/总库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除, + * SUM(quantity)=总库存、SUM(available_quantity)=可用库存、SUM(locked_quantity)=锁定数, + * 待出库存=总库存-可用库存;与 wms_stock_warehouse 主表的 quantity/locked_quantity 可能存在口径差异; + * 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义); + * 5. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序; + * 6. 日均口径:ck_avg/rk_avg = int(合计/天数×10)(formatters.avgDaysPerWeek); + * 7. 预计可售天数:出库日均>0 时 int(可用库存×10/出库日均×10),无出库时为 null; + * 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20)。 + * + * @param {Object} args 查询器入参 + * @param {Object} args.ctx Egg 上下文 + * @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤) + * @param {number|null} args.warehouseId 仓库ID(必填) + * @param {Object} [args.params={}] 业务参数(dayCount/cutoverHour 窗口覆盖等) + * @return {Promise<{windows: Array, rows: Array, meta: Object}>} 查询结果 + */ +async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, params = {} }) { + const { app } = ctx; + const { Op } = app.Sequelize; + + const { dayCount, cutoverHour } = resolveWindowConfig(params || {}); + const windows = buildDayWindows({ dayCount, cutoverHour }); + + const normalizedWarehouseId = Number(warehouseId) || 0; + if (normalizedWarehouseId <= 0) { + throw new Error('stockFlow 查询器缺少仓库维度 warehouseId'); + } + const normalizedStoreId = Number(storeId) || 0; + + const windowStart = windows[0].start; + const windowEnd = windows[windows.length - 1].end; + + // 1) 流水聚合(排除 LOCK/UNLOCK) + const transactionWhere = { + warehouse_id: normalizedWarehouseId, + transaction_type: { [Op.in]: [ 'INBOUND', 'OUTBOUND' ] }, + created_at: { + [Op.gte]: new Date(windowStart), + [Op.lt]: new Date(windowEnd), + }, + }; + if (normalizedStoreId > 0) { + transactionWhere.store_id = normalizedStoreId; + } + + const transactionRows = await ctx.model.StockTransaction.findAll({ + where: transactionWhere, + attributes: [ 'stock_id', 'transaction_type', 'quantity', 'created_at' ], + raw: true, + }); + + // stockId → { daily: [{ck, rk}], ckTotal, rkTotal } + const flowMap = new Map(); + const upsertSlot = stockId => { + if (!flowMap.has(stockId)) { + flowMap.set(stockId, { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }); + } + return flowMap.get(stockId); + }; + + for (const row of transactionRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const quantity = Number(row.quantity) || 0; + const createdMs = new Date(row.created_at).getTime(); + let windowIndex = -1; + for (let index = 0; index < windows.length; index += 1) { + if (createdMs >= windows[index].start && createdMs < windows[index].end) { + windowIndex = index; + break; + } + } + if (windowIndex < 0) { + continue; + } + const slot = upsertSlot(stockId); + if (row.transaction_type === 'OUTBOUND') { + slot.daily[windowIndex].ck += quantity; + slot.ckTotal += quantity; + } else { + slot.daily[windowIndex].rk += quantity; + slot.rkTotal += quantity; + } + } + + // 2) 可用/总库存(正品库位明细聚合) + const storageWhere = { + warehouse_id: normalizedWarehouseId, + inventory_type: 'ZP', + is_enabled: 1, + }; + if (normalizedStoreId > 0) { + storageWhere.store_id = normalizedStoreId; + } + + const inventoryRows = await ctx.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'stock_id', + [ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ], + [ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ], + ], + group: [ 'stock_id' ], + raw: true, + }); + + const inventoryMap = new Map(); + for (const row of inventoryRows) { + const stockId = Number(row.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const totalQuantity = Number(row.total_quantity) || 0; + const totalAvailable = Number(row.total_available) || 0; + inventoryMap.set(stockId, { + total: totalQuantity, + available: totalAvailable, + locked: Number(row.total_locked) || 0, + pending: totalQuantity - totalAvailable, + }); + } + + // 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode)) + const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ]; + let stockRows = []; + let barcodeRows = []; + if (stockIds.length > 0) { + [ stockRows, barcodeRows ] = await Promise.all([ + ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }), + ctx.model.StockBarcode.findAll({ + where: { stock_id: { [Op.in]: stockIds } }, + attributes: [ 'stock_id', 'barcode' ], + order: [[ 'barcode', 'ASC' ]], + raw: true, + }), + ]); + } + + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), { + itemCode: String(row.item_code || '').trim(), + itemName: String(row.item_name || '').trim(), + }); + } + + const barcodeMap = new Map(); + for (const row of barcodeRows) { + const stockId = Number(row.stock_id); + const barcode = String(row.barcode || '').trim(); + // 查询已按 barcode 升序,首个即字典序第一条 + if (!barcodeMap.has(stockId) && barcode) { + barcodeMap.set(stockId, barcode); + } + } + + // 4) 组装数据行 + const rows = stockIds.map(stockId => { + const flow = flowMap.get(stockId) || { + daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })), + ckTotal: 0, + rkTotal: 0, + }; + const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 }; + const stock = stockMap.get(stockId) || { itemCode: '', itemName: '' }; + const available = inventory.available; + const total = inventory.total; + const ckTotal = flow.ckTotal; + const rkTotal = flow.rkTotal; + const ckAvg = avgDaysPerWeek(ckTotal, dayCount); + const rkAvg = avgDaysPerWeek(rkTotal, dayCount); + // 预计可售天数:日均出库 = ckAvg/10,避免浮点误差改用 (available×10)/ckAvg 取整 + const stockDays = ckAvg > 0 ? Math.floor((available * 10) / ckAvg) : null; + + return { + stock_id: stockId, + item_code: stock.itemCode, + item_name: stock.itemName, + barcode: barcodeMap.get(stockId) || '', + daily: flow.daily, + ck_total: ckTotal, + rk_total: rkTotal, + available, + total, + pending: inventory.pending, + locked: inventory.locked, + ck_avg: ckAvg, + rk_avg: rkAvg, + stock_days: stockDays, + suggest: suggestWithCompensate(ckTotal, available, rkTotal), + warn: warnOf(ckTotal, available, rkTotal), + }; + }); + + rows.sort((left, right) => { + if (left.item_code !== right.item_code) { + return left.item_code < right.item_code ? -1 : 1; + } + return left.stock_id - right.stock_id; + }); + + return { + windows, + rows, + meta: { + warehouseId: normalizedWarehouseId, + storeId: normalizedStoreId, + dayCount, + cutoverHour, + }, + }; +} + +module.exports = sevenDayStockFlow; +// 静态字段清单挂到查询器模块上,供报表引擎与注册表 describe 读取(不执行真实数据查询) +module.exports.fields = FIELDS; +// 缺省窗口参数挂到查询器模块上,供注册表 describe 与 report.meta 读取 +module.exports.defaultWindow = DEFAULT_WINDOW; diff --git a/app/service/systems/reportDelivery.js b/app/service/systems/reportDelivery.js new file mode 100644 index 0000000..ee00c6b --- /dev/null +++ b/app/service/systems/reportDelivery.js @@ -0,0 +1,1475 @@ +'use strict'; + +const { Service } = require('egg'); +const { scheduleDateOf } = require('../../lib/report/day_window'); +const { + validateNotifyTemplate, + renderNotifyTemplate, + formatNotifyTime, +} = require('../../lib/report/notifyTemplate'); + +/** + * 货主报表定时投递编排服务(systems 层)。 + * + * 职责: + * 1. dispatch:分钟级扫描 wms_report_delivery_plan(enabled=1),按 HH:mm + 宽限窗口命中后 + * 对每个(货主+报表+数据日期+时间点)幂等生成报表并投递; + * 2. 投递记录状态机与 wms_report_delivery_log.status 一致: + * pending → exporting → delivered / failed / cancelled; + * 3. 失败退避重试(照搬 wms_waybill_allocate_queue 风格:MAX_RETRY=3, + * 退避 = retry_count × 60s);重试扫描条件:status=failed 且 retry_count<3 且 next_retry_at<=now; + * 4. 投递计划/投递记录的增改查(供 systemMethods 薄出口调用)。 + */ + +const DELIVERY_STATUS = Object.freeze({ + PENDING: 'pending', + EXPORTING: 'exporting', + DELIVERED: 'delivered', + FAILED: 'failed', + CANCELLED: 'cancelled', +}); + +/** 投递渠道(渠道已收敛:仅支持 inbox,wecom/link 已弃用) */ +const DELIVERY_CHANNELS = Object.freeze([ 'inbox' ]); +const DEFAULT_CHANNEL = 'inbox'; +const DEFAULT_GRACE_MINUTES = 60; +const MAX_RETRY_COUNT = 3; +const RETRY_BASE_DELAY_MS = 60 * 1000; +const EXPORTING_STALE_MS = 30 * 60 * 1000; +const MAX_ERROR_MESSAGE_LENGTH = 500; +const HHMM_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; +/** 通知模板长度上限(与表结构 STRING(500) 一致) */ +const NOTIFY_TEMPLATE_MAX_LENGTH = 500; +/** 计划名称长度上限(与表结构 STRING(100) 一致) */ +const PLAN_NAME_MAX_LENGTH = 100; +/** 通知群多选上限 */ +const MAX_NOTIFY_GROUP_IDS = 20; +/** 通知成员多选上限 */ +const MAX_NOTIFY_MEMBER_IDS = 100; + +class ReportDeliveryService extends Service { + // ==================== 计划/记录查询(供 method 层复用) ==================== + + /** + * 校验并规范化投递时间点(HH:mm 格式、去重、升序排序)。 + * @param {Array|string} rawTimes 原始时间点(数组或 JSON 字符串) + * @return {Array} 规范化时间点数组 + * @throws {Error} 含非法格式时抛出 + */ + normalizeScheduleTimes(rawTimes) { + let list = rawTimes; + if (typeof list === 'string') { + try { + list = JSON.parse(list); + } catch (error) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组'); + } + } + if (!Array.isArray(list) || list.length === 0) { + throw new Error('schedule_times 必须为 HH:mm 字符串数组且不能为空'); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const timePoint = String(item || '').trim(); + if (!HHMM_PATTERN.test(timePoint)) { + throw new Error(`schedule_times 含非法时间点(需 HH:mm 24 小时制): ${timePoint}`); + } + if (!seen.has(timePoint)) { + seen.add(timePoint); + normalized.push(timePoint); + } + } + normalized.sort(); + return normalized; + } + + /** + * 解析 JSON 数组字段:数组原样、JSON 字符串解析、null/undefined/'' 返回 null。 + * @param {*} value 原始值 + * @param {string} label 字段名(错误提示用) + * @return {Array|null} 数组或 null + * @throws {Error} 非数组或 JSON 解析失败时抛出业务可读错误 + */ + parseJsonArray(value, label) { + if (value === null || value === undefined || value === '') { + return null; + } + let list = value; + if (typeof value === 'string') { + try { + list = JSON.parse(value); + } catch (error) { + throw new Error(`${label} 必须为数组`); + } + } + if (!Array.isArray(list)) { + throw new Error(`${label} 必须为数组`); + } + return list; + } + + /** + * 视图安全的 JSON 数组读取(兼容字符串/数组/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Array|null} 数组或 null + */ + readJsonArray(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 视图安全的 JSON 对象读取(兼容对象/字符串/null,无法解析时返回 null)。 + * @param {*} value 字段原始值 + * @return {Object|null} 对象或 null + */ + readJsonObject(value) { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch (error) { + return null; + } + } + return null; + } + + /** + * 校验并规范化文本通知模板(长度 ≤500 + 标签白名单)。 + * 空值/null/空串均视为未启用(返回空字符串)。 + * @param {*} value 原始模板值 + * @return {string} 规范化后的模板(未配置时为空字符串) + * @throws {Error} 超长或含白名单外标签时抛出业务可读错误 + */ + normalizeNotifyTemplate(value) { + if (value === null || value === undefined || value === '') { + return ''; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > NOTIFY_TEMPLATE_MAX_LENGTH) { + throw new Error(`通知模板 notify_template 长度不能超过 ${NOTIFY_TEMPLATE_MAX_LENGTH} 字符`); + } + const check = validateNotifyTemplate(normalized); + if (!check.valid) { + throw new Error( + `通知模板含未知标签(仅支持 {time}/{url}/{report_name}/{biz_date}): ${check.invalidTags.join(', ')}` + ); + } + return normalized; + } + + /** + * 校验并规范化计划名称(仅展示字段,不参与幂等/关联逻辑)。 + * undefined=未传入(不覆盖既有值);null/空串/全空白=显式清空(返回 null); + * 非空时 trim 且长度 ≤ PLAN_NAME_MAX_LENGTH,超长抛出业务可读错误。 + * @param {*} value 原始名称值 + * @return {string|null|undefined} 规范化名称(未传入返回 undefined,清空返回 null) + * @throws {Error} 非空且超长时抛出业务可读错误 + */ + normalizePlanName(value) { + if (value === undefined) { + return undefined; + } + if (value === null || value === '') { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return null; + } + if (normalized.length > PLAN_NAME_MAX_LENGTH) { + throw new Error(`计划名称 name 长度不能超过 ${PLAN_NAME_MAX_LENGTH} 字符`); + } + return normalized; + } + + /** + * 校验并规范化通知群ID列表(wms_inbox_group.id 数组)。 + * 元素需为正整数、自动去重并升序排序、上限 MAX_NOTIFY_GROUP_IDS;null/空数组均允许(表示未选择群)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的正整数数组(去重升序),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyGroupIds(value) { + const list = this.parseJsonArray(value, '通知群 notify_group_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_GROUP_IDS) { + throw new Error(`通知群 notify_group_ids 最多选择 ${MAX_NOTIFY_GROUP_IDS} 个群`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const id = Number(item); + if (!Number.isInteger(id) || id <= 0) { + throw new Error(`通知群 notify_group_ids 含非法群ID(需正整数): ${item}`); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + normalized.sort((a, b) => a - b); + return normalized; + } + + /** + * 校验并规范化通知成员ID列表(外部 IM 用户 ID 字符串数组)。 + * 元素需为非空字符串、自动去重、上限 MAX_NOTIFY_MEMBER_IDS;null/空数组均允许(表示未选择成员)。 + * @param {*} value 原始值(数组或 JSON 字符串) + * @return {Array|null} 规范化后的字符串数组(去重),未选择返回 null + * @throws {Error} 元素非法或超上限时抛出业务可读错误 + */ + normalizeNotifyMemberIds(value) { + const list = this.parseJsonArray(value, '通知成员 notify_member_ids'); + if (list === null) { + return null; + } + if (list.length > MAX_NOTIFY_MEMBER_IDS) { + throw new Error(`通知成员 notify_member_ids 最多选择 ${MAX_NOTIFY_MEMBER_IDS} 个成员`); + } + const seen = new Set(); + const normalized = []; + for (const item of list) { + const memberId = String(item || '').trim(); + if (!memberId) { + throw new Error('通知成员 notify_member_ids 含空成员ID(需非空字符串)'); + } + if (!seen.has(memberId)) { + seen.add(memberId); + normalized.push(memberId); + } + } + return normalized; + } + + /** + * 校验通知群ID是否全部存在(软删自动排除,不校验 is_blocked: + * 屏蔽属于发送时过滤维度,保存时允许暂被屏蔽的群仍可选中)。 + * @param {Array} groupIds 群ID列表 + * @return {Promise} + * @throws {Error} 存在无效群ID时抛出(列出不存在或已删除的ID) + */ + async validateNotifyGroupExists(groupIds) { + const { ctx } = this; + const model = ctx.model && ctx.model.InboxGroup; + if (!model || typeof model.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法校验通知群配置'); + } + const { Op } = ctx.app.Sequelize; + const rows = await model.findAll({ + where: { id: { [Op.in]: groupIds } }, + attributes: [ 'id' ], + raw: true, + }); + const found = new Set((Array.isArray(rows) ? rows : []).map(row => Number(row.id))); + const missing = groupIds.filter(id => !found.has(id)); + if (missing.length > 0) { + throw new Error(`通知群 notify_group_ids 含不存在或已删除的群ID: ${missing.join(', ')}`); + } + } + + /** + * 保存/更新投递计划(存在则更新,不存在则创建;货主+报表定义ID唯一)。 + * @param {Object} options 入参 + * @param {number} options.storeId 货主ID + * @param {number|string} options.reportId 报表定义ID + * @param {Array} options.scheduleTimes 投递时间点(HH:mm) + * @param {string} [options.channel='inbox'] 投递渠道(仅支持 inbox) + * @param {number} [options.lateGraceMinutes=60] 补投宽限分钟 + * @param {string} [options.remark] 备注 + * @param {string|null} [options.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100) + * @param {string} [options.notifyTemplate] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date}) + * @param {Array|string} [options.notifyGroupIds] 通知群ID数组(wms_inbox_group.id,≤20) + * @param {Array|string} [options.notifyMemberIds] 通知成员ID数组(外部IM用户ID,≤100) + * @return {Promise} 保存后的计划记录 + * @throws {Error} 参数非法或并发首次保存撞唯一索引且降级重查不到记录时抛出业务可读错误 + */ + async savePlan({ + storeId, + reportId, + scheduleTimes, + channel = DEFAULT_CHANNEL, + lateGraceMinutes = DEFAULT_GRACE_MINUTES, + remark = '', + name, + notifyTemplate, + notifyGroupIds, + notifyMemberIds, + }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + throw new Error('货主ID store_id 不能为空'); + } + const normalizedReportId = Number(reportId) || 0; + if (!Number.isInteger(normalizedReportId) || normalizedReportId <= 0) { + throw new Error('报表ID report_id 必须为正整数'); + } + // 校验报表定义存在且启用 + await ctx.service.systems.report.getDefinition(normalizedReportId); + + const normalizedTimes = this.normalizeScheduleTimes(scheduleTimes); + const normalizedChannel = String(channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + if (!DELIVERY_CHANNELS.includes(normalizedChannel)) { + throw new Error(`投递渠道仅支持 inbox: ${channel}`); + } + const graceMinutes = Math.max(0, Math.min(1440, Math.floor(Number(lateGraceMinutes) || 0))); + + // 计划名称校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedName; + if (name !== undefined) { + normalizedName = this.normalizePlanName(name); + } + + // 文本通知配置校验(未传入 undefined 时保持既有字段不动,避免更新时误清空) + let normalizedNotifyTemplate; + let normalizedNotifyGroupIds; + let normalizedNotifyMemberIds; + if (notifyTemplate !== undefined) { + normalizedNotifyTemplate = this.normalizeNotifyTemplate(notifyTemplate); + } + if (notifyGroupIds !== undefined) { + normalizedNotifyGroupIds = this.normalizeNotifyGroupIds(notifyGroupIds); + if (normalizedNotifyGroupIds !== null && normalizedNotifyGroupIds.length > 0) { + await this.validateNotifyGroupExists(normalizedNotifyGroupIds); + } + } + if (notifyMemberIds !== undefined) { + normalizedNotifyMemberIds = this.normalizeNotifyMemberIds(notifyMemberIds); + } + + const payload = { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + schedule_times: normalizedTimes, + channel: normalizedChannel, + late_grace_minutes: graceMinutes, + remark: String(remark || '').slice(0, 500), + }; + if (normalizedName !== undefined) { + payload.name = normalizedName; + } + if (normalizedNotifyTemplate !== undefined) { + payload.notify_template = normalizedNotifyTemplate; + } + if (normalizedNotifyGroupIds !== undefined) { + payload.notify_group_ids = normalizedNotifyGroupIds; + } + if (normalizedNotifyMemberIds !== undefined) { + payload.notify_member_ids = normalizedNotifyMemberIds; + } + + const existing = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (existing) { + await existing.update(payload); + return this.planToView(existing); + } + try { + const created = await model.create(payload); + return this.planToView(created); + } catch (error) { + // 并发首次保存撞 uk_store_report_definition 唯一索引:降级为重查并更新(与 processOne 的 findOrCreate 降级一致) + if (error && error.name === 'SequelizeUniqueConstraintError') { + const winner = await model.findOne({ + where: { + store_id: normalizedStoreId, + report_definition_id: normalizedReportId, + }, + }); + if (winner) { + await winner.update(payload); + return this.planToView(winner); + } + throw new Error('该货主已存在此报表的投递计划,保存冲突,请重试'); + } + throw error; + } + } + + /** + * 快速复制投递计划到其他货主(货主+报表定义ID唯一,目标已存在同报表定义计划时跳过)。 + * + * 规则: + * 1. id 必须为正整数,源计划不存在(含软删)时抛出业务可读错误; + * 2. storeIds 必须为非空数组且元素为正整数,自动去重; + * 与源计划 store_id 相同的项计入 skipped(原因:与源计划货主相同), + * 全部剔除后为空时仍正常返回(created=[],skipped 标注原因); + * 3. 目标货主必须在 wms_store 存在且状态正常(status=1,软删自动排除), + * 不存在或不合法者计入 skipped(原因:货主不存在或状态异常); + * 4. 目标货主已存在同 report_definition_id 的计划(软删排除)时跳过 + * (原因:已存在同报表定义计划),不覆盖不报错; + * 5. 新建计划时 notify_group_ids / notify_member_ids 置空(null,通知配置不复制), + * enabled 等其余配置字段原样复制(enabled 保持“复制”语义,复制源计划启停状态); + * 6. 批量创建使用事务包裹,保证一致性;并发撞唯一索引时降级为 skipped 不中断其余创建。 + * + * @param {Object} options 入参 + * @param {number|string} options.id 源计划ID(正整数) + * @param {Array} options.storeIds 目标货主ID数组(元素需正整数,允许 JSON 字符串) + * @return {Promise<{created: Array<{id: number, store_id: number}>, skipped: Array<{store_id: number, reason: string}>}>} + * 复制结果:created 为新建成功的计划(id=新计划ID,store_id=目标货主ID), + * skipped 为跳过项(store_id=目标货主ID,reason=跳过原因) + * @throws {Error} id 非法、源计划不存在、storeIds 非空数组校验失败或元素非法时抛出业务可读错误 + */ + async copyPlan({ id, storeIds }) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + // 源计划校验(findByPk 受 paranoid 约束,软删自动排除,不存在返回 null) + const normalizedId = Number(id) || 0; + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + throw new Error('计划ID无效'); + } + const source = await model.findByPk(normalizedId); + if (!source) { + throw new Error('计划不存在'); + } + + // 目标货主数组校验:非空数组、元素为正整数、自动去重(JSON 字符串兼容,与 save 口径一致) + const rawList = this.parseJsonArray(storeIds, '目标货主 store_ids'); + if (rawList === null || rawList.length === 0) { + throw new Error('目标货主 store_ids 必须为非空数组'); + } + const seen = new Set(); + const targetStoreIds = []; + for (const item of rawList) { + const storeId = Number(item) || 0; + if (!Number.isInteger(storeId) || storeId <= 0) { + throw new Error(`目标货主 store_ids 含非法货主ID(需正整数): ${item}`); + } + if (!seen.has(storeId)) { + seen.add(storeId); + targetStoreIds.push(storeId); + } + } + + const sourceStoreId = Number(source.store_id) || 0; + const skipped = []; + const candidates = []; + for (const storeId of targetStoreIds) { + if (storeId === sourceStoreId) { + skipped.push({ store_id: storeId, reason: '与源计划货主相同' }); + } else { + candidates.push(storeId); + } + } + + // 目标货主存在性校验(wms_store 状态正常 status=1,软删自动排除) + const validTargets = []; + if (candidates.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + throw new Error('货主模型 Store 不可用,无法校验目标货主'); + } + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: candidates }, status: 1 }, + attributes: [ 'id' ], + raw: true, + }); + const foundSet = new Set((Array.isArray(storeRows) ? storeRows : []).map(row => Number(row.id) || 0)); + for (const storeId of candidates) { + if (foundSet.has(storeId)) { + validTargets.push(storeId); + } else { + skipped.push({ store_id: storeId, reason: '货主不存在或状态异常' }); + } + } + } + + const created = []; + if (validTargets.length > 0) { + // 已存在同报表定义计划的目标货主跳过(软删排除,与唯一索引口径一致) + const { Op } = ctx.app.Sequelize; + const existingRows = await model.findAll({ + where: { + store_id: { [Op.in]: validTargets }, + report_definition_id: Number(source.report_definition_id) || 0, + }, + attributes: [ 'store_id' ], + raw: true, + }); + const existingSet = new Set((Array.isArray(existingRows) ? existingRows : []).map(row => Number(row.store_id) || 0)); + const toCreate = []; + for (const storeId of validTargets) { + if (existingSet.has(storeId)) { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + toCreate.push(storeId); + } + } + + if (toCreate.length > 0) { + // 其余配置字段原样复制;通知配置不复制(置空);enabled 原样复制保持“复制”语义 + const payload = { + report_definition_id: Number(source.report_definition_id) || 0, + schedule_times: Array.isArray(source.schedule_times) ? source.schedule_times : [], + channel: String(source.channel || DEFAULT_CHANNEL), + late_grace_minutes: Number(source.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: source.name == null ? null : String(source.name), + remark: source.remark == null ? null : String(source.remark), + notify_template: source.notify_template == null ? null : String(source.notify_template), + notify_group_ids: null, + notify_member_ids: null, + enabled: Number(source.enabled ?? 1), + }; + + const transaction = await ctx.model.transaction(); + try { + for (const storeId of toCreate) { + try { + const row = await model.create({ ...payload, store_id: storeId }, { transaction }); + created.push({ id: Number(row.id) || 0, store_id: storeId }); + } catch (error) { + // 并发下撞 uk_store_report_definition 唯一索引:降级为 skipped,不中断其余创建 + if (error && error.name === 'SequelizeUniqueConstraintError') { + skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' }); + } else { + throw error; + } + } + } + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + } + } + + return { created, skipped }; + } + + /** + * 计划记录转视图对象。 + * @param {Object} plan 计划记录(实例或 raw) + * @return {Object} 视图对象 + */ + planToView(plan) { + if (!plan) { + return null; + } + return { + id: Number(plan.id) || 0, + store_id: Number(plan.store_id) || 0, + report_definition_id: Number(plan.report_definition_id) || 0, + schedule_times: Array.isArray(plan.schedule_times) ? plan.schedule_times : [], + channel: String(plan.channel || DEFAULT_CHANNEL), + enabled: Number(plan.enabled ?? 1), + late_grace_minutes: Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(plan.name || ''), + remark: String(plan.remark || ''), + notify_template: String(plan.notify_template || ''), + notify_group_ids: this.readJsonArray(plan.notify_group_ids), + notify_member_ids: this.readJsonArray(plan.notify_member_ids), + created_at: plan.created_at || null, + updated_at: plan.updated_at || null, + }; + } + + /** + * 分页查询投递计划列表。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {number|string} [options.enabled] 启用状态(0/1) + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果, + * 每条计划含 store_name(货主公司全称,货主已删除或不存在时为空串) + */ + async listPlans({ storeId = null, reportId = null, enabled = null, pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryPlan; + if (!model) { + throw new Error('投递计划模型 ReportDeliveryPlan 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + if (enabled !== null && enabled !== undefined && enabled !== '') { + where.enabled = Number(enabled) ? 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', 'created_at', 'updated_at', 'store_id', 'report_definition_id' ]; + 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 }), + ]); + + const planRows = Array.isArray(rows) ? rows : []; + + // 批量查询货主名称(一次 IN 查询避免 N+1):软删除货主自动排除, + // 货主已删除或不存在时 store_name 回退为空串 + const storeIds = [ ...new Set(planRows.map(row => Number(row.store_id) || 0).filter(id => id > 0)) ]; + const storeNameMap = new Map(); + if (storeIds.length > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findAll === 'function') { + const { Op } = ctx.app.Sequelize; + const storeRows = await storeModel.findAll({ + where: { id: { [Op.in]: storeIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const storeRow of Array.isArray(storeRows) ? storeRows : []) { + storeNameMap.set(Number(storeRow.id) || 0, String(storeRow.company_name || '')); + } + } + } + + return { + list: planRows.map(row => ({ + id: Number(row.id) || 0, + store_id: Number(row.store_id) || 0, + store_name: storeNameMap.get(Number(row.store_id) || 0) || '', + report_definition_id: Number(row.report_definition_id) || 0, + schedule_times: Array.isArray(row.schedule_times) ? row.schedule_times : [], + channel: String(row.channel || DEFAULT_CHANNEL), + enabled: Number(row.enabled ?? 1), + late_grace_minutes: Number(row.late_grace_minutes ?? DEFAULT_GRACE_MINUTES), + name: String(row.name || ''), + remark: String(row.remark || ''), + notify_template: String(row.notify_template || ''), + notify_group_ids: this.readJsonArray(row.notify_group_ids), + notify_member_ids: this.readJsonArray(row.notify_member_ids), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + /** + * 分页查询投递记录(审计)。 + * @param {Object} [options={}] 入参 + * @param {number} [options.storeId] 货主ID + * @param {number|string} [options.reportId] 报表定义ID + * @param {string} [options.status] 状态过滤 + * @param {Object} [options.pagination={}] 分页 { page, pageSize } + * @param {Object} [options.sort={}] 排序 { sortField, sortOrder } + * @return {Promise<{list: Array, total: number, page: number, pageSize: number}>} 列表结果 + */ + async listLogs({ storeId = null, reportId = null, status = '', pagination = {}, sort = {} } = {}) { + const { ctx } = this; + const model = ctx.model && ctx.model.ReportDeliveryLog; + if (!model) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + const where = {}; + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId > 0) { + where.store_id = normalizedStoreId; + } + const normalizedReportId = Number(reportId) || 0; + if (normalizedReportId > 0) { + where.report_definition_id = normalizedReportId; + } + const normalizedStatus = String(status || '').trim(); + if (normalizedStatus && Object.values(DELIVERY_STATUS).includes(normalizedStatus)) { + where.status = normalizedStatus; + } + + 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', 'created_at', 'updated_at', 'biz_date', 'delivered_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 => ({ + id: Number(row.id) || 0, + warehouse_id: Number(row.warehouse_id) || 0, + store_id: Number(row.store_id) || 0, + report_definition_id: Number(row.report_definition_id) || 0, + report_name: String(row.report_name || ''), + biz_date: row.biz_date || '', + time_point: String(row.time_point || ''), + status: String(row.status || DELIVERY_STATUS.PENDING), + channel: String(row.channel || DEFAULT_CHANNEL), + file_url: String(row.file_url || ''), + retry_count: Number(row.retry_count) || 0, + next_retry_at: row.next_retry_at || null, + error_message: String(row.error_message || ''), + delivered_at: row.delivered_at || null, + notify_targets: this.readJsonObject(row.notify_targets), + created_at: row.created_at || null, + updated_at: row.updated_at || null, + })), + total: Number(total) || 0, + page, + pageSize, + }; + } + + // ==================== 投递调度 ==================== + + /** + * 计算当前时刻命中的时间点(含 late_grace_minutes 宽限窗口)。 + * 宽限跨零点场景:now 为次日凌晨时,昨日深夜时间点仍可在宽限内命中。 + * @param {Array} scheduleTimes 计划时间点(HH:mm) + * @param {Date} now 触发时刻 + * @param {number} graceMinutes 宽限分钟 + * @return {Array} 命中的时间点 + */ + hitTimePoints(scheduleTimes, now, graceMinutes) { + const normalizedGrace = Math.max(0, Math.min(1440, Math.floor(Number(graceMinutes) || 0))); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const hits = []; + for (const timePoint of scheduleTimes) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const diff = nowMinutes - timeMinutes; + const wrapDiff = nowMinutes + 24 * 60 - timeMinutes; + if ((diff >= 0 && diff <= normalizedGrace) || wrapDiff <= normalizedGrace) { + hits.push(timePoint); + } + } + return hits; + } + + /** + * 计算触发时刻的数据日期(T-1 本地自然日)。 + * @param {Date} now 触发时刻 + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTrigger(now) { + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)); + } + + /** + * 计算命中时间点对应的数据日期(报表数据截止日 = 时间点所属自然日的 T-1)。 + * + * 口径:同一时间点在「正常投递」与「跨零点补投」时必须落在相同 biz_date, + * 保证幂等键 (store_id, report_definition_id, biz_date, time_point) 防重不防漏: + * - 当日命中(timePoint 的 HH:mm <= now 的 HH:mm):时间点属于触发自然日, + * biz_date = 触发日 - 1; + * - 跨零点补投(timePoint 的 HH:mm > now 的 HH:mm,即昨日深夜时间点): + * 时间点属于昨日自然日,biz_date = 昨日 - 1(触发日 - 2), + * 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + * + * @param {Date} now 触发时刻 + * @param {string} timePoint 命中的投递时间点(HH:mm) + * @return {string} 'YYYY-MM-DD' + */ + bizDateOfTimePoint(now, timePoint) { + const parts = String(timePoint).split(':'); + const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const scheduleDayOffset = timeMinutes > nowMinutes ? -2 : -1; + return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() + scheduleDayOffset)); + } + + /** + * 解析货主所属仓库:优先首条有效合约(auth_status=2 且未停用),否则回退最早一条合约。 + * 假设:货主报表按单仓库生成,取最早合约的仓库维度(供测试复核)。 + * @param {number} storeId 货主ID + * @return {Promise} 仓库ID,未找到返回 0 + */ + async resolveStoreWarehouse(storeId) { + const { ctx } = this; + const model = ctx.model && ctx.model.StoreWarehouse; + if (!model || typeof model.findAll !== 'function') { + return 0; + } + const normalizedStoreId = Number(storeId) || 0; + if (normalizedStoreId <= 0) { + return 0; + } + const rows = await model.findAll({ + where: { store_id: normalizedStoreId }, + attributes: [ 'store_id', 'warehouse_id', 'auth_status', 'warehouse_use_status' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const list = Array.isArray(rows) ? rows : []; + const active = list.find(row => Number(row.auth_status) === 2 && Number(row.warehouse_use_status) !== 0); + const chosen = active || list[0]; + return chosen ? Number(chosen.warehouse_id) || 0 : 0; + } + + /** + * 投递成功回写(delivered),并落文本通知目标快照(可选)。 + * @param {Object} log 投递记录实例 + * @param {Object} fileResult 生成结果 { fileKey, url, filename } + * @param {Object|null} [notifyTargets=null] 文本通知目标快照 { group_ids, member_ids, notify_text } + * @return {Promise} + */ + async markDelivered(log, fileResult, notifyTargets = null) { + await log.update({ + status: DELIVERY_STATUS.DELIVERED, + // 表结构仅 file_url 一列承载产物地址(无 file_key/task_id 列),url 缺失时退化为 fileKey + file_url: String(fileResult.url || fileResult.fileKey || '').slice(0, 500), + error_message: null, + next_retry_at: null, + delivered_at: new Date(), + notify_targets: notifyTargets || null, + }); + } + + /** + * 投递失败回写(failed + 退避重试,MAX_RETRY=3,照搬 wms_waybill_allocate_queue 风格)。 + * @param {Object} log 投递记录实例 + * @param {string} errorMessage 失败原因 + * @return {Promise} + */ + async markFailed(log, errorMessage) { + const retryCount = Number(log.retry_count) || 0; + const nextCount = retryCount + 1; + const normalizedMessage = String(errorMessage || '报表投递失败').slice(0, MAX_ERROR_MESSAGE_LENGTH); + await log.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: nextCount, + next_retry_at: nextCount >= MAX_RETRY_COUNT + ? null + : new Date(Date.now() + nextCount * RETRY_BASE_DELAY_MS), + error_message: normalizedMessage, + }); + } + + /** + * 置为导出中(exporting),并回填生成报表使用的仓库维度与报表名称快照。 + * @param {Object} log 投递记录实例 + * @param {number} warehouseId 仓库ID + * @param {string} [reportName=''] 报表名称快照 + * @return {Promise} + */ + async markExporting(log, warehouseId, reportName = '') { + await log.update({ + status: DELIVERY_STATUS.EXPORTING, + warehouse_id: Number(warehouseId) || 0, + report_name: String(reportName || '').slice(0, 100), + error_message: null, + }); + } + + /** + * 构建投递通知正文(站内信 inbox 文案)。 + * @param {Object} definition 报表定义 + * @param {string} bizDate 数据日期 + * @param {string} fileUrl 文件链接 + * @return {string} 通知正文 + */ + buildMessageContent(definition, bizDate, fileUrl) { + const reportName = String((definition && definition.name) || '报表'); + return `【${reportName}】${bizDate} 数据报表已生成,点击查看:${fileUrl}`; + } + + /** + * 按渠道投递(渠道已收敛,仅支持 inbox 站内信群推送)。 + * + * 规则: + * 1. 历史计划残留 wecom/link 等已弃用渠道时,按 inbox 兜底执行并记录 warn 日志 + * (不直接抛错:避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死); + * 2. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用 + * ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推, + * ext_id 幂等复用同一条消息记录,不重复写); + * 3. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环 + * (MAX_RETRY=3,退避 = retry_count × 60s); + * 4. 完成后按计划配置附带发送文本通知(与投递渠道独立)。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now=new Date()] 触发时刻(渲染 {time} 用) + * @return {Promise} 文本通知目标快照(未配置通知时返回 null) + * @throws {Error} 投递失败且重推失败时抛出 + */ + async deliverByChannel({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const rawChannel = String(plan.channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL; + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportDefinitionId = Number(plan.report_definition_id) || 0; + const idempotentKey = `report:${reportDefinitionId}:${bizDate}:${timePoint}`; + + // 渠道收敛:wecom/link 已弃用,历史残留数据按 inbox 兜底执行,避免历史计划投递卡死 + if (rawChannel !== 'inbox') { + ctx.logger.warn( + `[reportDelivery] 计划投递渠道 ${rawChannel} 已弃用,按 inbox 兜底投递(store_id=${storeId}, report_definition_id=${reportDefinitionId})` + ); + } + + // inbox:站内信群推送(唯一渠道) + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用'); + } + const groupRow = await inboxGroupModel.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + group_type: 'store', + is_blocked: 0, + }, + attributes: [ 'group_id', 'group_name', 'ext_data' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!groupRow || !groupRow.group_id) { + throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`); + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + const pushResult = await warehouseNotify.pushSystemMessage({ + warehouseId, + storeId, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + content: this.buildMessageContent(definition, bizDate, fileUrl), + extId: idempotentKey, + extData: { + report_definition_id: reportDefinitionId, + biz_date: bizDate, + time_point: timePoint, + file_url: fileUrl, + }, + }); + + // 推送失败判定(双保险):success=false;或消息记录回写 push_status=3(推送链路异常时兜底识别) + const messageId = (pushResult && Number(pushResult.messageId)) || 0; + let pushFailed = !pushResult || pushResult.success === false; + if (!pushFailed && messageId > 0) { + const InboxMessage = ctx.model && ctx.model.InboxMessage; + if (InboxMessage && typeof InboxMessage.findOne === 'function') { + try { + const row = await InboxMessage.findOne({ + where: { id: messageId }, + attributes: [ 'push_status' ], + raw: true, + }); + if (row && Number(row.push_status) === 3) { + pushFailed = true; + } + } catch (statusErr) { + ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`); + } + } + } + + if (pushFailed) { + const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败'; + // 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用 + // 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环 + const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message; + if (messageId > 0 && retryService && typeof retryService.retry === 'function') { + try { + await retryService.retry({ warehouseId, id: messageId }); + ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`); + } catch (retryErr) { + const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`; + throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`); + } + } else { + throw new Error(reason); + } + } + + // 文本通知(可选):与投递渠道独立;未配置时返回 null 保持既有行为不变 + return this.sendNotifyIfConfigured({ + plan, + definition, + fileResult, + warehouseId, + storeId, + bizDate, + timePoint, + now, + }); + } + + /** + * 按计划配置发送文本通知(模板渲染 + 定向群/成员推送)。 + * + * 规则: + * 1. 未配置模板或未选择任何群/成员时直接返回 null(保持既有投递行为不变); + * 2. 通知群(notify_group_ids 内部ID)→ 查 wms_inbox_group 取外部 group_id/group_name, + * 过滤 is_blocked=1、软删自动排除、仓库维度一致;逐群推送(群维度协议字段为单值); + * 3. 通知成员(notify_member_ids 外部IM用户ID)→ 推送体 user_id 直接传数组,不循环拆发; + * 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送; + * 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递; + * 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重)。 + * + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {Object} options.definition 报表定义 + * @param {Object} options.fileResult 生成结果 + * @param {number} options.warehouseId 仓库ID + * @param {number} options.storeId 货主ID + * @param {string} options.bizDate 数据日期 + * @param {string} options.timePoint 命中时间点 + * @param {Date} [options.now] 触发时刻 + * @return {Promise} 快照 { group_ids, member_ids, notify_text },未配置返回 null + * @throws {Error} 目标不可达或推送失败时抛出 + */ + async sendNotifyIfConfigured({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) { + const { ctx } = this; + const template = String((plan && plan.notify_template) || '').trim(); + if (!template) { + return null; + } + const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || []; + const memberIds = this.readJsonArray(plan && plan.notify_member_ids) || []; + if (groupIds.length === 0 && memberIds.length === 0) { + return null; + } + + const reportDefinitionId = Number((plan && plan.report_definition_id) || 0); + const fileUrl = String(fileResult.url || fileResult.fileKey || ''); + const reportName = String((definition && definition.name) || '报表'); + const notifyText = renderNotifyTemplate(template, { + time: formatNotifyTime(now || new Date()), + url: fileUrl, + reportName, + bizDate, + }); + + // 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致) + let groups = []; + if (groupIds.length > 0) { + const inboxGroupModel = ctx.model && ctx.model.InboxGroup; + if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') { + throw new Error('站内信群模型 InboxGroup 不可用,无法发送文本通知'); + } + const { Op } = ctx.app.Sequelize; + const rows = await inboxGroupModel.findAll({ + where: { + id: { [Op.in]: groupIds }, + warehouse_id: Number(warehouseId) || 0, + is_blocked: 0, + }, + attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ], + raw: true, + }); + groups = Array.isArray(rows) ? rows : []; + } + + if (groups.length === 0 && memberIds.length === 0) { + throw new Error('文本通知目标不可达(通知群不存在、已删除、被屏蔽或未选择群/成员)'); + } + + const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; + if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') { + throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用'); + } + + const notifyExtId = `report:notify:${reportDefinitionId}:${bizDate}:${timePoint}`; + const commonOptions = { + warehouseId, + storeId, + userIds: memberIds, + content: notifyText, + extId: notifyExtId, + extData: { + report_definition_id: reportDefinitionId, + biz_date: bizDate, + time_point: timePoint, + file_url: fileUrl, + }, + }; + + const sentGroupIds = []; + const results = []; + // 群多选:群维度协议字段为单值(group_id/group_name),逐群推送;成员 user_id 数组随群推送整体透传 + for (const groupRow of groups) { + results.push(await warehouseNotify.pushSystemMessage({ + ...commonOptions, + group: { + group_id: groupRow.group_id, + group_name: groupRow.group_name || '货主群', + ext_data: groupRow.ext_data || null, + }, + })); + sentGroupIds.push(Number(groupRow.id)); + } + // 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发 + if (memberIds.length > 0 && results.length === 0) { + results.push(await warehouseNotify.pushSystemMessage(commonOptions)); + } + + const failed = results.filter(result => !result || result.success === false); + if (failed.length > 0) { + const reason = (failed[0] && (failed[0].reason || failed[0].error)) || '文本通知推送失败'; + throw new Error(`文本通知推送失败: ${reason}`); + } + + return { + group_ids: sentGroupIds, + member_ids: memberIds, + notify_text: notifyText, + }; + } + + /** + * 处理单个(计划 × 时间点)的幂等生成与投递。 + * @param {Object} options 入参 + * @param {Object} options.plan 投递计划 + * @param {number} options.storeId 货主ID + * @param {number} options.reportId 报表定义ID + * @param {string} options.timePoint 命中时间点 + * @param {string} options.bizDate 数据日期 + * @param {Date} options.now 触发时刻 + * @return {Promise} 处理结果标记(delivered/failed/skipped) + */ + async processOne({ plan, storeId, reportId, timePoint, bizDate, now }) { + const { ctx } = this; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!logModel) { + throw new Error('投递记录模型 ReportDeliveryLog 不可用'); + } + + const uniqueWhere = { + store_id: storeId, + report_definition_id: reportId, + biz_date: bizDate, + time_point: timePoint, + }; + + let log = await logModel.findOne({ where: uniqueWhere }); + + if (log) { + const status = String(log.status || ''); + if (status !== DELIVERY_STATUS.FAILED) { + // 已投递/投递中/取消的记录直接跳过(幂等) + return 'skipped'; + } + const retryCount = Number(log.retry_count) || 0; + if (retryCount >= MAX_RETRY_COUNT) { + return 'skipped'; + } + const nextRetryAt = log.next_retry_at ? new Date(log.next_retry_at) : null; + if (nextRetryAt && nextRetryAt.getTime() > now.getTime()) { + // 退避未到期 + return 'skipped'; + } + } else { + try { + [ log ] = await logModel.findOrCreate({ + where: uniqueWhere, + defaults: { + ...uniqueWhere, + warehouse_id: 0, + report_name: '', + status: DELIVERY_STATUS.PENDING, + channel: String(plan.channel || DEFAULT_CHANNEL), + }, + }); + } catch (error) { + // 并发撞唯一键时降级为查询 + log = await logModel.findOne({ where: uniqueWhere }); + } + if (log && String(log.status || '') !== DELIVERY_STATUS.PENDING && String(log.status || '') !== DELIVERY_STATUS.FAILED) { + return 'skipped'; + } + } + + if (!log) { + return 'skipped'; + } + + const warehouseId = await this.resolveStoreWarehouse(storeId); + if (warehouseId <= 0) { + await this.markFailed(log, `货主 ${storeId} 未找到有效合约仓库`); + return 'failed'; + } + + // 读取报表定义一次(报表名称快照 + 投递通知文案共用,生成步骤内部会再按 id 读取) + const definition = await ctx.service.systems.report.getDefinition(reportId); + await this.markExporting(log, warehouseId, definition.name); + + // 生成上传(失败进入退避重试) + let fileResult; + try { + fileResult = await ctx.service.systems.report.generate({ + reportId, + storeId, + warehouseId, + params: { + bizDate, + timePoint, + }, + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表生成失败: ${errorMessage}`); + return 'failed'; + } + + // 投递(失败进入退避重试) + try { + const notifyTargets = await this.deliverByChannel({ + plan, + definition, + fileResult, + warehouseId, + storeId, + bizDate, + timePoint, + now, + }); + await this.markDelivered(log, fileResult, notifyTargets); + return 'delivered'; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${reportId}/${storeId}/${bizDate}/${timePoint}: ${errorMessage}`); + await this.markFailed(log, `报表投递失败: ${errorMessage}`); + return 'failed'; + } + } + + /** + * 计划时间点解析:兼容数组与 JSON 字符串(防止手工数据写成字符串)。 + * @param {Array|string} value 原始值 + * @return {Array} 时间点数组 + */ + parseScheduleTimes(value) { + if (Array.isArray(value)) { + return value; + } + if (typeof value === 'string' && value.trim()) { + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch (error) { + return []; + } + } + return []; + } + + /** + * 分钟级投递调度入口(schedule 调用)。 + * + * 流程: + * 1. 兜底回退:exporting 超过 EXPORTING_STALE_MS 的记录视为进程中断,置为 failed + * 并重置 retry_count=0、next_retry_at=now,交由重试扫描立即重排(防卡死); + * 2. 计划扫描:对每个命中时间点按「时间点归属自然日 - 1」计算 biz_date + * (跨零点补投落漏跑日),幂等生成并投递; + * 3. 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录直接重试, + * 不依赖计划时间点再次命中。 + * @return {Promise} 本轮扫描汇总 { scanned, delivered, failed, skipped } + */ + async dispatch() { + const { ctx, app } = this; + const planModel = ctx.model && ctx.model.ReportDeliveryPlan; + const logModel = ctx.model && ctx.model.ReportDeliveryLog; + if (!planModel || !logModel) { + return { scanned: 0, delivered: 0, failed: 0, skipped: 0 }; + } + + const { Op } = app.Sequelize; + const now = new Date(); + + // 兜底:导出中超过 30 分钟视为进程中断,置为 failed 并重置退避参数(retry_count=0、 + // next_retry_at=now)交给重试链路立即重排。不能回退为 pending:既有 pending 会被 + // processOne 幂等跳过,且重试扫描只捡 failed,会导致该记录永久卡死(缺陷 D1)。 + await logModel.update({ + status: DELIVERY_STATUS.FAILED, + retry_count: 0, + next_retry_at: now, + error_message: '报表导出超时中断,已自动重排投递', + updated_at: now, + }, { + where: { + status: DELIVERY_STATUS.EXPORTING, + updated_at: { + [Op.lt]: new Date(now.getTime() - EXPORTING_STALE_MS), + }, + }, + }); + + const plans = await planModel.findAll({ + where: { enabled: 1 }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const summary = { + scanned: Array.isArray(plans) ? plans.length : 0, + delivered: 0, + failed: 0, + skipped: 0, + }; + + for (const plan of plans || []) { + const scheduleTimes = this.parseScheduleTimes(plan.schedule_times); + if (scheduleTimes.length === 0) { + continue; + } + const graceMinutes = Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES); + const hits = this.hitTimePoints(scheduleTimes, now, graceMinutes); + if (hits.length === 0) { + continue; + } + + const storeId = Number(plan.store_id) || 0; + const reportId = Number(plan.report_definition_id) || 0; + if (storeId <= 0 || reportId <= 0) { + ctx.logger.warn(`[reportDelivery] 跳过无效计划 id=${plan.id}(store_id=${storeId}, report_definition_id=${reportId})`); + continue; + } + + for (const timePoint of hits) { + try { + // 按命中时间点归属自然日计算 biz_date:跨零点补投落在漏跑日(T-2), + // 与次日正常投递的幂等键互不碰撞(缺陷 D2) + const hitBizDate = this.bizDateOfTimePoint(now, timePoint); + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate: hitBizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + } + + // 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录 + // (不依赖计划时间点再次命中,退避到期即重试) + const failedLogs = await logModel.findAll({ + where: { + status: DELIVERY_STATUS.FAILED, + retry_count: { [Op.lt]: MAX_RETRY_COUNT }, + next_retry_at: { [Op.lte]: now }, + }, + order: [[ 'id', 'ASC' ]], + limit: 200, + raw: true, + }); + + const retryPlans = new Map(); + for (const failedLog of failedLogs || []) { + const storeId = Number(failedLog.store_id) || 0; + const reportId = Number(failedLog.report_definition_id) || 0; + const bizDate = String(failedLog.biz_date || ''); + const timePoint = String(failedLog.time_point || ''); + if (storeId <= 0 || reportId <= 0 || !bizDate || !timePoint) { + continue; + } + const planKey = `${storeId}:${reportId}`; + let plan = retryPlans.get(planKey); + if (plan === undefined) { + plan = await planModel.findOne({ + where: { + store_id: storeId, + report_definition_id: reportId, + enabled: 1, + }, + raw: true, + }); + retryPlans.set(planKey, plan || null); + } + if (!plan) { + // 计划已停用/删除:不再重试 + continue; + } + try { + const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate, now }); + if (mark === 'delivered') { + summary.delivered += 1; + } else if (mark === 'failed') { + summary.failed += 1; + } else { + summary.skipped += 1; + } + } catch (error) { + summary.failed += 1; + const errorMessage = error && error.message ? error.message : `${error}`; + ctx.logger.error(`[reportDelivery] 重试处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`); + } + } + + return summary; + } +} + +module.exports = ReportDeliveryService; diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js index ed22760..81d794b 100644 --- a/app/service/systems/warehouseNotify.js +++ b/app/service/systems/warehouseNotify.js @@ -224,26 +224,55 @@ class WarehouseNotifyService extends Service { } /** - * 向指定群推送系统级业务通知(复用 notify.reply,type=system)。 + * 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。 * 对方接口只处理 content 内容,推送体仅保留协议必需字段: - * type / content / ext_id / group_id / group_name / timestamp。 + * type / content / ext_id / group_id / group_name / user_id / timestamp。 * 推送前写入 wms_inbox_message(direction=outbound,source_type=system), * 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。 + * + * 向后兼容:不传 userIds 且传入 group 时,行为与旧版本完全一致 + * (校验、幂等 ext_id、落库字段、推送体均不变)。 + * * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {number} [options.storeId] 货主 ID。 - * @param {Object} options.group 目标群 { group_id, group_name, ext_data }。 + * @param {Object|null} [options.group=null] 目标群 { group_id, group_name, ext_data } + * (新增允许为 null:仅成员推送场景)。 + * @param {Array|null} [options.userIds=null] 目标成员外部 IM 用户 ID 数组 + * (新增,目标侧协议支持 user_id 数组:整体透传不循环拆发)。 * @param {string} [options.content=''] 通知正文。 * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 * @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。 * @return {Promise} 推送结果(含 messageId)。 */ - async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null, extData = null } = {}) { + async pushSystemMessage({ + warehouseId, + storeId = null, + group = null, + userIds = null, + content = '', + extId = null, + extData = null, + } = {}) { const { ctx } = this; const groupId = String((group && group.group_id) || '').trim(); const groupName = String((group && group.group_name) || '').trim(); + // 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组) + const normalizedUserIds = Array.isArray(userIds) + ? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ] + : []; - if (!groupId || !groupName) { + // 向后兼容:无群且无成员时保持旧版 skip 语义(原判断 !groupId || !groupName) + if (!groupId && normalizedUserIds.length === 0) { + return { + success: false, + skipped: true, + reason: '目标群缺少 group_id 或 group_name', + warehouseId, + }; + } + // 指定了群但缺群名:与旧版一致返回 skip(群维度协议要求 group_name) + if (groupId && !groupName) { return { success: false, skipped: true, @@ -252,11 +281,13 @@ class WarehouseNotifyService extends Service { }; } - // 幂等 ext_id:业务单号 + 事件 + 群维度,网络重推时复用同一条消息记录;超长时降级哈希兜底 + // 幂等 ext_id:业务单号 + 事件 + 目标维度(群优先、仅成员时按成员集合), + // 网络重推时复用同一条消息记录;超长时降级哈希兜底 const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); - let uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`; + const memberKey = normalizedUserIds.length > 0 ? `members:${normalizedUserIds.join(',')}` : ''; + const targetKey = groupId || memberKey; + let uniqueExtId = `sys:notice:${sourceExtId}:${targetKey}`; if (uniqueExtId.length > 128) { - const crypto = require('crypto'); const digest = crypto.createHash('md5') .update(uniqueExtId) .digest('hex') @@ -287,9 +318,11 @@ class WarehouseNotifyService extends Service { source_type: 'system', source_extra: 'notice', target_type: 'api', - group_id: groupId, + group_id: groupId || null, + // 成员数组仅随推送体 user_id 透传并记录在 report_delivery_log.notify_targets 快照中, + // 消息表 user_id 列(STRING(100))不承载数组,避免超长截断 user_id: null, - group_name: groupName, + group_name: groupName || null, user_name: null, content: normalizedContent, ext_data: extData || null, @@ -304,18 +337,26 @@ class WarehouseNotifyService extends Service { } } + // 推送体:群字段仅指定群时携带;成员 user_id 直接传数组(目标侧协议支持),不循环拆发 + const pushData = { + type: 'system', + content: normalizedContent, + ext_id: sourceExtId, + ext_data: extData || null, + timestamp: Math.floor(Date.now() / 1000), + }; + if (groupId) { + pushData.group_id = groupId; + pushData.group_name = groupName; + } + if (normalizedUserIds.length > 0) { + pushData.user_id = normalizedUserIds; + } + const result = await this.push({ warehouseId, method: 'notify.reply', - data: { - type: 'system', - content: normalizedContent, - ext_id: sourceExtId, - ext_data: extData || null, - group_id: groupId, - group_name: groupName, - timestamp: Math.floor(Date.now() / 1000), - }, + data: pushData, }); // 回写推送状态(失败仅记日志,不影响业务) diff --git a/database/migrations/20260829120000-create-wms-report-delivery-tables.js b/database/migrations/20260829120000-create-wms-report-delivery-tables.js new file mode 100644 index 0000000..5ff551a --- /dev/null +++ b/database/migrations/20260829120000-create-wms-report-delivery-tables.js @@ -0,0 +1,321 @@ +'use strict'; + +/** + * 创建报表投递三表:报表模板定义 / 货主投递计划 / 投递记录。 + * + * 背景:货主侧 7 日出入库报表采用「配置驱动 + 定时投递」方案: + * 报表模板可配置上新(免发版),每个货主可配置每日多个投递时间点, + * 由分钟级扫描调度命中后生成报表并按渠道投递。 + * + * 三表职责: + * - wms_report_definition:报表模板定义(code/name/scope + output/source/sheet 三段 JSON 配置) + * - wms_report_delivery_plan:货主每日投递计划(schedule_times JSON 时间点数组) + * - wms_report_delivery_log:投递记录(pending→exporting→delivered/failed/cancelled 状态机 + 退避重试) + * + * 约定: + * - 逻辑关联、无物理外键(与项目现状一致) + * - 唯一索引按项目惯例含 deleted_at,避免软删后重建撞唯一键 + * - 幂等键 uk_store_report_biz_time 保证同一货主同一报表同一数据日期同一时间点不重复投递 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, TINYINT, DATE, DATEONLY, ENUM } = Sequelize; + const tables = await queryInterface.showAllTables(); + const tableNames = tables.map(t => (typeof t === 'string' ? t : t.tableName)); + + if (!tableNames.includes(TABLE_DEFINITION)) { + await queryInterface.createTable(TABLE_DEFINITION, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + code: { + type: STRING(100), + allowNull: false, + comment: '报表编码,全局唯一(如 week_inout_7d)', + }, + name: { + type: STRING(100), + allowNull: false, + comment: '报表名称', + }, + scope: { + type: ENUM('warehouse', 'store', 'open'), + allowNull: false, + defaultValue: 'warehouse', + comment: '适用维度:warehouse=仓库 store=货主 open=通用', + }, + description: { + type: STRING(500), + allowNull: true, + comment: '报表描述', + }, + output_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '输出配置(文件名/目录等)', + }, + source_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '数据源配置(查询器 key + 窗口参数)', + }, + sheet_config: { + type: Sequelize.JSON, + allowNull: true, + comment: '工作表配置(列定义/合并/样式/行过滤/列级 format)', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表模板定义表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_DEFINITION, [ 'code', 'deleted_at' ], { + unique: true, + name: 'uk_code', + }); + await queryInterface.addIndex(TABLE_DEFINITION, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_PLAN)) { + await queryInterface.createTable(TABLE_PLAN, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + schedule_times: { + type: Sequelize.JSON, + allowNull: false, + comment: '每日投递时间点数组,如 ["08:30","17:00"](HH:mm)', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }, + enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用:0=停用 1=启用', + }, + late_grace_minutes: { + type: INTEGER(11), + allowNull: false, + defaultValue: 60, + comment: '补投宽限分钟:重启/漏跑后在该窗口内补投,超窗作废', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '货主报表投递计划表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_PLAN, [ 'store_id', 'report_code', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_code', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'enabled', 'deleted_at' ], { + name: 'idx_enabled_deleted', + }); + await queryInterface.addIndex(TABLE_PLAN, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + if (!tableNames.includes(TABLE_LOG)) { + await queryInterface.createTable(TABLE_LOG, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '仓库ID(生成报表时注入的仓库维度)', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID(wms_store.id)', + }, + report_code: { + type: STRING(100), + allowNull: false, + comment: '报表编码(wms_report_definition.code)', + }, + biz_date: { + type: DATEONLY, + allowNull: false, + comment: '数据日期(T-1 自然日)', + }, + time_point: { + type: STRING(5), + allowNull: false, + comment: '命中的投递时间点(HH:mm)', + }, + status: { + type: STRING(20), + allowNull: false, + defaultValue: 'pending', + comment: '状态:pending/exporting/delivered/failed/cancelled', + }, + channel: { + type: STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }, + file_url: { + type: STRING(500), + allowNull: true, + comment: '报表文件下载链接(COS 带有效期)', + }, + retry_count: { + type: INTEGER(3), + allowNull: false, + defaultValue: 0, + comment: '重试次数', + }, + next_retry_at: { + type: DATE, + allowNull: true, + comment: '下次可投递时间(失败退避)', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '最近一次失败原因', + }, + delivered_at: { + type: DATE, + allowNull: true, + comment: '投递成功时间', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + comment: '报表投递记录表', + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + }); + + await queryInterface.addIndex(TABLE_LOG, [ 'store_id', 'report_code', 'biz_date', 'time_point', 'deleted_at' ], { + unique: true, + name: 'uk_store_report_biz_time', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'id' ], { + name: 'idx_status_id', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'status', 'updated_at' ], { + name: 'idx_status_updated_at', + }); + await queryInterface.addIndex(TABLE_LOG, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + }, + + async down(queryInterface) { + await queryInterface.dropTable(TABLE_LOG); + await queryInterface.dropTable(TABLE_PLAN); + await queryInterface.dropTable(TABLE_DEFINITION); + }, +}; diff --git a/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js new file mode 100644 index 0000000..d167664 --- /dev/null +++ b/database/migrations/20260829160000-add-notify-fields-to-wms-report-delivery.js @@ -0,0 +1,77 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递通知能力增强: + * - wms_report_delivery_plan 新增 notify_template(文本通知模板)、 + * notify_group_ids(通知群ID数组)、notify_member_ids(通知成员ID数组) + * - wms_report_delivery_log 新增 notify_targets(本次实际投递的群/成员快照,审计回放) + * + * 全部字段可空,不影响存量投递计划与投递记录。 + */ +module.exports = { + /** + * 执行迁移:依次新增通知相关字段(幂等:已存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + up: async (queryInterface, Sequelize) => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (!planColumns.notify_template) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_template', { + type: Sequelize.STRING(500), + allowNull: true, + comment: '文本通知模板,支持 {time}/{url}/{report_name}/{biz_date} 标签', + }); + } + if (!planColumns.notify_group_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_group_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知群ID数组(wms_inbox_group.id,多选;空=不指定群)', + }); + } + if (!planColumns.notify_member_ids) { + await queryInterface.addColumn(TABLE_PLAN, 'notify_member_ids', { + type: Sequelize.JSON, + allowNull: true, + comment: '通知成员ID数组(外部IM用户ID,多选;目标侧支持数组)', + }); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (!logColumns.notify_targets) { + await queryInterface.addColumn(TABLE_LOG, 'notify_targets', { + type: Sequelize.JSON, + allowNull: true, + comment: '投递目标快照:{group_ids:[],member_ids:[]}(本次实际发送的群/成员,审计回放)', + }); + } + }, + + /** + * 回滚迁移:按新增顺序的逆序删除字段(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + down: async queryInterface => { + const planColumns = await queryInterface.describeTable(TABLE_PLAN); + if (planColumns.notify_member_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_member_ids'); + } + if (planColumns.notify_group_ids) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_group_ids'); + } + if (planColumns.notify_template) { + await queryInterface.removeColumn(TABLE_PLAN, 'notify_template'); + } + + const logColumns = await queryInterface.describeTable(TABLE_LOG); + if (logColumns.notify_targets) { + await queryInterface.removeColumn(TABLE_LOG, 'notify_targets'); + } + }, +}; diff --git a/database/migrations/20260829170000-normalize-report-channel-to-inbox.js b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js new file mode 100644 index 0000000..4390062 --- /dev/null +++ b/database/migrations/20260829170000-normalize-report-channel-to-inbox.js @@ -0,0 +1,55 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +/** + * 报表投递渠道收敛为 inbox(wecom/link 已弃用)。 + * + * - wms_report_delivery_plan.channel:默认值 wecom → inbox,comment 收敛 + * - wms_report_delivery_log.channel:默认值 wecom → inbox,comment 收敛 + * - 存量数据归一化:channel IN ('wecom','link') 的行统一更新为 'inbox' + * + * down 仅回退列默认值与 comment;数据 UPDATE 不回退(历史行无法还原原渠道)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + // 1. 计划表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_PLAN} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + + // 2. 记录表:默认值 + comment 收敛 + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '投递渠道快照:inbox=站内信群(wecom/link 已弃用)', + }); + await queryInterface.sequelize.query( + `UPDATE ${TABLE_LOG} SET channel = 'inbox' WHERE channel IN ('wecom', 'link')` + ); + }, + + async down(queryInterface, Sequelize) { + // 仅回退默认值与 comment;存量数据不回退(已归一化为 inbox 的行无法还原原渠道) + await queryInterface.changeColumn(TABLE_PLAN, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道:wecom=企业微信 inbox=站内信群 link=链接', + }); + await queryInterface.changeColumn(TABLE_LOG, 'channel', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'wecom', + comment: '投递渠道快照:wecom=企业微信 inbox=站内信群 link=链接', + }); + }, +}; diff --git a/database/migrations/20260830120000-restructure-report-definition-by-id.js b/database/migrations/20260830120000-restructure-report-definition-by-id.js new file mode 100644 index 0000000..3ca6f12 --- /dev/null +++ b/database/migrations/20260830120000-restructure-report-definition-by-id.js @@ -0,0 +1,166 @@ +'use strict'; + +/** + * 报表定义模型重构:code 关联 → 主键 id 关联。 + * + * 背景:报表定义模型已重构(definition 以主键 id 唯一,删除 code/scope/description + * 及 output_config/source_config/sheet_config 三个 JSON 配置列,新增 type/file_name/fields; + * plan/log 改用 report_definition_id 关联定义),本迁移同步数据库结构。 + * + * 三步改造: + * 1. wms_report_definition:删 uk_code,加 type/file_name/fields 三列,回填 id=1 + * 存量数据,物理删除已软删的 e2e 演示行(id=2),删除 code/scope/description + * 及三个 JSON 配置列,最后去掉 type 默认值(新配置必须显式声明类型); + * 2. wms_report_delivery_plan:加 report_definition_id 并回填,唯一键 + * uk_store_report_code → uk_store_report_definition; + * 3. wms_report_delivery_log:加 report_definition_id/report_name 并回填, + * 唯一键 uk_store_report_biz_time 改为基于 report_definition_id。 + * + * 执行顺序说明(关键约束):plan/log 的回填依赖 definition.code 关联 + * (JOIN ... ON d.code = p.report_code),因此 definition 旧列(含 code)的删除 + * 被延后到 plan/log 回填核验通过之后执行,最终表结构与规格逐项一致。 + * + * down 不可逆:旧列及其数据已被物理删除,无法从库内还原,故 down 直接抛错, + * 如需回退请从备份恢复。 + */ + +const TABLE_DEFINITION = 'wms_report_definition'; +const TABLE_PLAN = 'wms_report_delivery_plan'; +const TABLE_LOG = 'wms_report_delivery_log'; + +// id=1 存量报表勾选字段 key 数组(与代码侧 stockFlow 查询器字段规格一致) +const STOCK_FLOW_FIELDS = [ + 'item_code', 'item_name', 'barcode', 'daily', 'ck_total', 'rk_total', 'available', + 'total', 'pending', 'locked', 'ck_avg', 'rk_avg', 'stock_days', 'suggest', 'warn', +]; + +module.exports = { + async up(queryInterface) { + const { sequelize } = queryInterface; + const q = sql => sequelize.query(sql); + const log = msg => console.log(`[report-definition-by-id] ${msg}`); + + /** + * 执行计数校验 SQL,返回行数;不满足期望时抛错,阻止后续破坏性 DDL。 + * @param {string} sql 返回 cnt 列的 SELECT COUNT 语句。 + * @param {number} expected 期望的行数。 + * @param {string} message 校验失败时的错误描述。 + */ + const assertCount = async (sql, expected, message) => { + const [ rows ] = await q(sql); + const count = Number(rows[0].cnt); + console.log(`[report-definition-by-id] 核验:${message}(实际 ${count},期望 ${expected})`); + if (count !== expected) { + throw new Error(`[report-definition-by-id] ${message} 核验失败:实际 ${count},期望 ${expected}`); + } + }; + + // ============ Step 1(前半):wms_report_definition 结构准备 ============ + // 1.1 删除 uk_code 唯一索引(code 即将废弃) + await queryInterface.removeIndex(TABLE_DEFINITION, 'uk_code'); + log('definition:已删除唯一索引 uk_code'); + + // 1.2 新增 type / file_name / fields 三列(按规格顺序放在 name 之后) + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + ADD COLUMN \`type\` VARCHAR(50) NOT NULL DEFAULT 'stockFlow' COMMENT '报表类型(内置查询器注册 key)' AFTER \`name\`, + ADD COLUMN \`file_name\` VARCHAR(200) NOT NULL DEFAULT '' COMMENT '导出文件名模板(支持 {date} 占位)' AFTER \`type\`, + ADD COLUMN \`fields\` JSON NULL COMMENT '勾选字段 key 数组' AFTER \`file_name\``); + log('definition:已新增 type/file_name/fields 三列'); + + // 1.3 回填 id=1 存量数据(7日出入库报表) + await q(`UPDATE \`${TABLE_DEFINITION}\` SET + \`type\` = 'stockFlow', + \`file_name\` = '7日出入库_{date}', + \`fields\` = JSON_ARRAY(${STOCK_FLOW_FIELDS.map(f => `'${f}'`).join(', ')}) + WHERE \`id\` = 1`); + log('definition:已回填 id=1 的 type/file_name/fields'); + + // 1.4 物理删除已软删的 e2e 演示行(id=2) + await q(`DELETE FROM \`${TABLE_DEFINITION}\` + WHERE \`id\` = 2 AND \`deleted_at\` IS NOT NULL AND \`code\` = 'e2e_demo_report'`); + log('definition:已删除软删状态下的 e2e 演示行(id=2)'); + + // ============ Step 2:wms_report_delivery_plan 改 id 关联 ============ + // 2.1 新增 report_definition_id(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\``); + log('plan:已新增 report_definition_id'); + + // 2.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_PLAN}\` p + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = p.\`report_code\` + SET p.\`report_definition_id\` = d.\`id\``); + log('plan:已按 code 关联回填 report_definition_id'); + + // 2.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_PLAN}\` WHERE \`report_definition_id\` = 0`, + 0, + 'plan 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 2.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_PLAN, 'uk_store_report_code'); + await q(`ALTER TABLE \`${TABLE_PLAN}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_PLAN}\` + ADD UNIQUE INDEX \`uk_store_report_definition\` (\`store_id\`, \`report_definition_id\`, \`deleted_at\`)`); + log('plan:已切换唯一键 uk_store_report_definition 并删除 report_code'); + + // ============ Step 3:wms_report_delivery_log 改 id 关联 ============ + // 3.1 新增 report_definition_id / report_name(按规格顺序放在 store_id 之后) + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD COLUMN \`report_definition_id\` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 + COMMENT '报表定义ID(wms_report_definition.id)' AFTER \`store_id\`, + ADD COLUMN \`report_name\` VARCHAR(100) NULL + COMMENT '报表名称快照(投递时定义 name)' AFTER \`report_definition_id\``); + log('log:已新增 report_definition_id/report_name'); + + // 3.2 按 code 关联回填(必须在 definition.code 删除前完成) + await q(`UPDATE \`${TABLE_LOG}\` l + JOIN \`${TABLE_DEFINITION}\` d ON d.\`code\` = l.\`report_code\` + SET l.\`report_definition_id\` = d.\`id\`, l.\`report_name\` = d.\`name\``); + log('log:已按 code 关联回填 report_definition_id/report_name'); + + // 3.3 核验:report_definition_id=0 的行数必须为 0,否则抛出异常 + await assertCount( + `SELECT COUNT(*) AS cnt FROM \`${TABLE_LOG}\` WHERE \`report_definition_id\` = 0`, + 0, + 'log 回填后 report_definition_id=0 的行数必须为 0' + ); + + // 3.4 删除旧唯一键与 report_code,建立新唯一键 + await queryInterface.removeIndex(TABLE_LOG, 'uk_store_report_biz_time'); + await q(`ALTER TABLE \`${TABLE_LOG}\` DROP COLUMN \`report_code\``); + await q(`ALTER TABLE \`${TABLE_LOG}\` + ADD UNIQUE INDEX \`uk_store_report_biz_time\` + (\`store_id\`, \`report_definition_id\`, \`biz_date\`, \`time_point\`, \`deleted_at\`)`); + log('log:已切换唯一键 uk_store_report_biz_time 并删除 report_code'); + + // ============ Step 1(后半):删除 definition 旧列并收尾 ============ + // plan/log 回填已核验通过,此时删除 definition 旧列(含 code)是安全的 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` + DROP COLUMN \`code\`, + DROP COLUMN \`scope\`, + DROP COLUMN \`description\`, + DROP COLUMN \`output_config\`, + DROP COLUMN \`source_config\`, + DROP COLUMN \`sheet_config\``); + log('definition:已删除 code/scope/description 及三个 JSON 配置列'); + + // 去掉 type 默认值:新配置行必须显式声明报表类型 + await q(`ALTER TABLE \`${TABLE_DEFINITION}\` ALTER COLUMN \`type\` DROP DEFAULT`); + log('definition:已去掉 type 默认值'); + + log('全部完成'); + }, + + async down() { + // 本迁移破坏性删除旧列数据(code/scope/description 及三个 JSON 配置列、 + // e2e 演示行、plan/log 的 report_code 列),库内已无原始数据可还原,不可自动回滚。 + throw new Error( + '[report-definition-by-id] 本迁移不可逆:definition 旧列及其数据、e2e 演示行、plan/log 的 report_code 列已被删除,' + + '库内无法还原原始数据。如需回退,请从备份恢复数据库或手工重建相关列与数据。' + ); + }, +}; diff --git a/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js new file mode 100644 index 0000000..e928331 --- /dev/null +++ b/database/migrations/20260830130000-add-name-to-wms-report-delivery-plan.js @@ -0,0 +1,56 @@ +'use strict'; + +const TABLE_PLAN = 'wms_report_delivery_plan'; + +/** + * 为报表投递计划表新增计划名称字段 name。 + * + * 背景:报表投递计划在管理端列表/详情展示时需要展示计划名称(前端展示用), + * 因此为 wms_report_delivery_plan 新增 name 列,按规格位于 report_definition_id 之后。 + * + * 全部存量计划允许 name 为空(可空列),不影响既有投递计划与投递逻辑。 + */ +module.exports = { + /** + * 执行迁移:新增 name 列(幂等:已存在则跳过)。 + * + * 说明:sequelize 的 addColumn 不支持指定列位置(AFTER), + * 为满足「位于 report_definition_id 之后」的规格要求, + * 使用原生 DDL 控制列位置,与项目既有迁移 + * (restructure-report-definition-by-id)的做法一致。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async up(queryInterface) { + const { sequelize } = queryInterface; + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:已存在 name 列时跳过 + if (columns.name) { + return; + } + + await sequelize.query( + `ALTER TABLE \`${TABLE_PLAN}\` + ADD COLUMN \`name\` VARCHAR(100) NULL COMMENT '计划名称(前端展示用)' + AFTER \`report_definition_id\`` + ); + }, + + /** + * 回滚迁移:删除 name 列(幂等:不存在则跳过)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const columns = await queryInterface.describeTable(TABLE_PLAN); + + // 幂等保护:不存在 name 列时跳过 + if (!columns.name) { + return; + } + + await queryInterface.removeColumn(TABLE_PLAN, 'name'); + }, +}; diff --git a/docs/report-config-guide.md b/docs/report-config-guide.md new file mode 100644 index 0000000..f3fdb05 --- /dev/null +++ b/docs/report-config-guide.md @@ -0,0 +1,342 @@ +# 配置驱动通用报表与货主定时投递 — 配置结构说明 + +> 本文档与代码实现保持一致(模型:`app/model/report_definition.js`;引擎:`app/service/systems/report.js`; +> 渲染翻译层:`app/lib/report/render.js`;内置查询器:`app/service/systems/report/queries/*`; +> 投递编排:`app/service/systems/reportDelivery.js`)。 +> 接口定义见 `methods/system.json` 分组「通用报表模块」(module=report)。 + +> 破坏性变更(2026-08-30 模型重构):报表定义由 `code` 编码改为主键 `id` 关联,接口入参 `report_code` +> 全部替换为 `report_id`(=报表定义ID,兼容 `reportId` 驼峰);`code/scope/description` 与 +> `output_config/source_config/sheet_config` 三段 JSON 配置字段已随模型删除, +> 列渲染由注册类型硬编码字段规格自动完成(无自定义列配置)。 + +## 1. 总览 + +报表采用「配置驱动」:`wms_report_definition` 一行配置 = 一个报表(`type` + `fields` 极简配置), +大部分新报表场景只需加配置行或新增内置查询器类型,免发版。 + +模型 `app/model/report_definition.js` 关键字段: + +| 列 | 类型 | 说明 | +|---|---|---| +| `id` | BIGINT UNSIGNED | 主键,报表定义ID(接口入参 `report_id`,唯一性由主键承担) | +| `name` | STRING(100) | 报表名称 | +| `type` | STRING(50) | 报表类型(内置查询器注册 key,如 `stockFlow`) | +| `file_name` | STRING(200) | 导出文件名模板(支持 `{date}` 占位,如 `7日出入库_{date}.xlsx`) | +| `fields` | JSON | 勾选的字段 key 数组(该类型注册字段的子集;列头/合并/样式/格式化由类型硬编码字段规格决定) | +| `is_enabled` | TINYINT(1) | 是否启用:0=停用 1=启用(导出只读 is_enabled=1 的定义) | +| `remark` | STRING(500) | 备注 | +| `created_at`/`updated_at`/`deleted_at` | DATE | 时间戳与软删标记 | + +生成链路: + +```text +report.generate(method 层,异步任务,入参 report_id) + -> systems/report.js getDefinition(读定义,is_enabled=1,软删自动排除) + -> resolveTypeEntry / resolveQuerier(type 查注册表) + -> 内置查询器取数 {windows, rows, meta} + -> lib/report/render.js renderSheetByType(按类型硬编码字段规格渲染) + -> excel.generateAndUpload(产物 fileKey/url/filename/size) +``` + +## 2. 注册类型(report.definition.typeList / wms_report_definition.type) + +查询器注册表 `app/service/systems/report/queries/index.js`,`type` 即注册方法 key; +查询器签名统一:`async ({ ctx, storeId, warehouseId, params }) => ({ windows, rows, meta })`, +每个查询器模块挂载静态字段清单 `fields` 与缺省窗口参数 `defaultWindow`。 + +当前注册类型: + +| key | 标题 | 说明 | +|---|---|---| +| `stockFlow` | 库存变化以及补货报表 | 按日窗口聚合出入库流水与正品库存,输出每 SKU 每日出/入库、可用/总库存、锁定数、待出、日均出/入库、预计可售天数、建议补货量与库存预警 | + +`stockFlow` 缺省窗口参数:`window = { dayCount: 7, cutoverHour: 7 }`。 + +`stockFlow` 全量字段清单(16 个顶层字段,`report.definition.typeList` / `report.meta` 直接返回该规格): + +| key | label | type | computed | asText | 说明 | +|---|---|---|---|---|---| +| `stock_id` | 库存ID | number | - | - | | +| `item_code` | 商品编码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `item_name` | 商品名称 | string | - | - | | +| `barcode` | 条码 | string | - | ✅ | 文本单元格落地,防科学计数法 | +| `daily` | 每日出入库 | array | - | - | children:`ck`(出库数,number)/ `rk`(入库数,number) | +| `ck_total` | 出库合计 | number | - | - | | +| `rk_total` | 入库合计 | number | - | - | | +| `available` | 可用库存 | number | - | - | | +| `total` | 总库存 | number | - | - | | +| `pending` | 待出库存 | number | - | - | | +| `locked` | 锁定数 | number | - | - | | +| `ck_avg` | 出库日均(×10) | number | ✅ | - | 预计算字段 | +| `rk_avg` | 入库日均(×10) | number | ✅ | - | 预计算字段 | +| `stock_days` | 预计可售天数 | number | ✅ | - | 预计算字段 | +| `suggest` | 建议补货量 | number | ✅ | - | 预计算字段 | +| `warn` | 库存预警 | boolean | ✅ | - | 预计算字段 | + +### 2.1 stockFlow 口径与假设(8 条,供测试复核) + +1. **窗口**:`dayCount` 个 `[D cutoverHour:00, D+1 cutoverHour:00)` 本地时区半开区间 + (缺省 7 天、07:00 切点,可由请求 `params.dayCount/cutoverHour` 覆盖)。 +2. **流水**:`wms_stock_transaction`,`transaction_type IN (INBOUND, OUTBOUND)`,显式排除 LOCK/UNLOCK, + 按 `created_at` 落入窗口,INBOUND→rk、OUTBOUND→ck。 +3. **库存口径**:`wms_storage`(库位级正品明细),`inventory_type='ZP'`、`is_enabled=1`、未删除, + `SUM(quantity)`=总库存、`SUM(available_quantity)`=可用库存、`SUM(locked_quantity)`=锁定数、 + 待出库存=总库存-可用库存;与 `wms_stock_warehouse` 主表的 `quantity/locked_quantity` 可能存在口径差异。 +4. **条码**:`wms_stock_barcodes` 多值取字典序第一条(表内无主条码标志,等价旧 PHP `MIN(barcode)` 语义)。 +5. **行范围**:窗口内有流水或有正品库存的 SKU 均出列,按 `item_code` 升序、`stock_id` 升序。 +6. **日均口径**:`ck_avg/rk_avg = int(合计/天数×10)`(`formatters.avgDaysPerWeek`)。 +7. **预计可售天数**:出库日均>0 时 `int(可用库存×10/出库日均×10)`(`available×10/ckAvg` 取整),无出库时为 null。 +8. **suggest/warn**:由 `formatters` 注册表计算。低库存补偿:`available < 20` 且 `rk_total < 20` 时 + 建议补货量补偿到不低于 30;预警判定由 `warnOf(ck_total, available, rk_total)` 计算。 + +## 3. 渲染规则(renderSheetByType,无 sheet_config) + +列定义不再由 `sheet_config.columns` 配置,而由**注册类型字段规格硬编码自动生成** +(`app/lib/report/render.js` `renderSheetByType`,按定义勾选字段顺序渲染): + +| 字段类型 | 渲染规则 | +|---|---| +| `string` | 静态列(表头=label);字段规格 `asText: true` 时整列落地为 Excel 文本单元格 | +| `number` | 静态列,统一 `zeroToDash`(`0 / '0' / null / ''` 显示 `-`) | +| `boolean` | 静态列,统一 `yesNo`(真→'是'、假→'否',PHP 布尔语义) | +| `array` | 窗口展开列:per=窗口数(缺省 7)、pair=children 字段键;表头第 1 行每窗口输出窗口开始日期 `'Y/n/j'`(无前导零,如 `2026/8/23`),pair 数>1 时每窗口表头横向合并(如 D1:E1 … P1:Q1);表头第 2 行按 children label 填充;子字段 number 统一 `zeroToDash` | + +- 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2),合并区域**自动生成**,无需配置。 +- **asText(文本单元格)**:由类型字段规格硬编码(如 `item_code`/`barcode` 声明 `asText: true`), + 渲染层 `renderSheetByType` 将声明 `asText` 的列收集为 `textColumns`(0 基列索引数组,未声明任何 `asText` 列时不输出该字段), + 由 `app/service/systems/excel.js` 落地:ExcelJS 路径逐单元格 `numFmt='@'` 并把值转为字符串(原始对象除外), + SheetJS 路径逐单元格 `t:'s'`、`z:'@'` 并把值字符串化。适用于条码、商品编码等长数字串 + (防止被 Excel 按数值展示成科学计数法),**无需**再配合 `textPrefix` 的 `'` 前缀 + (`textPrefix` 格式化器保留注册仅向后兼容)。 +- sheet 名称为类型标题(如「库存变化以及补货报表」);`columns` 恒输出空数组 + (数据以 AOA 二维数组形式输出,表头行内联在 rows 首位)。 + +## 4. 导出文件名(file_name) + +- `file_name` 为文件名模板,`{date}` 替换为数据日期(请求 `params.bizDate`,缺省服务器当天,`YYYY-MM-DD`)。 +- 缺省模板:`_.xlsx`;不以 `.xlsx`/`.xls` 结尾时自动补 `.xlsx`。 +- 上传目录:`exports/report//`。 + +## 5. 货主定时投递(wms_report_delivery_plan / wms_report_delivery_log) + +- **投递计划** `wms_report_delivery_plan`:`store_id + report_definition_id` 唯一(唯一索引 `uk_store_report_definition`, + `report_definition_id` 即报表定义ID、接口入参 `report_id`);`schedule_times`(HH:mm 数组,去重升序)、 + `channel`(**仅支持 `inbox`,默认 `inbox`**;wecom/link 已弃用,保存时传非法渠道报错「投递渠道仅支持 inbox: 」)、 + `late_grace_minutes`(补投宽限 0-1440,默认 60)、`name`(计划名称,仅展示字段,≤100 字符,可空)、`enabled`。 +- **计划名称 `name`**(2026-08-30 新增,仅展示字段,不参与 `store_id + report_definition_id` 幂等/关联逻辑): + `report.deliveryPlan.save` 可选入参(未传不覆盖既有值;`null`/空串/全空白归一化为 `null` 显式清空; + 非空 `trim` 后最长 100 字符,超长报错「计划名称 name 长度不能超过 100 字符」); + `save` 成功响应与 `report.deliveryPlan.list` 列表项均返回 `name`(未设置时为空字符串)。 + +```json +// report.deliveryPlan.save(name 可选) +{ + "store_id": 1001, + "report_id": 1, + "schedule_times": ["09:00", "17:30"], + "name": "每日库存报表投递", + "late_grace_minutes": 60 +} +``` +- **渠道收敛兜底**:历史计划残留的 wecom/link 渠道在投递时**按 inbox 兜底执行**(仅记录 warn 日志,不抛错,避免历史计划卡死)。 +- **迁移归一化**:迁移 `20260829170000` 已把两表 `channel` 列默认值 wecom → inbox、comment 收敛, + 存量 `channel IN ('wecom','link')` 行统一 UPDATE 为 `inbox`(模型 `defaultValue: 'inbox'` 同步); + `report.deliveryPlan.list` / `report.deliveryLog.list` 响应 `channel` 恒为 `inbox`。 +- **投递记录** `wms_report_delivery_log`:状态机与 `status` 一致: + `pending → exporting → delivered / failed / cancelled`;`report_definition_id` 关联报表定义ID, + `report_name` 为投递时报表名称快照(审计回放,定义删除后仍可追溯)。 +- **调度**(`reportDelivery.dispatch`,分钟级):按 HH:mm + 宽限窗口命中后, + 对每个 `(store_id, report_definition_id, biz_date, time_point)` 幂等生成报表并投递(防重不防漏)。 +- **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用 + `inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入 + `failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件 + `status=failed 且 retry_count<3 且 next_retry_at<=now`;卡在 exporting 超过 30 分钟视为陈旧可重扫。 +- **biz_date 口径**:正常投递为触发日 T-1;跨零点补投(时间点晚于当前时刻)为触发日 T-2, + 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。 + +### 5.1 文本通知模板与定向群/成员(notify_template / notify_group_ids / notify_member_ids) + +投递计划可在投递完成后附带发送一条文本通知(与投递渠道独立,inbox 渠道投递后同样生效;未配置时行为与旧版完全一致)。 +三个字段均为可选,仅在 `report.deliveryPlan.save` 入参存在时生效(更新时未传保持原值)。 + +#### 5.1.1 notify_template(文本通知模板) + +- 最长 **500** 字符,超出报错;空值/未传视为未启用。 +- 标签白名单(仅以下 4 个标签会被渲染,其余 `{xxx}` 视为未知标签,保存时报错并列出非法标签): + +| 标签 | 渲染内容 | +|---|---| +| `{time}` | 发送时间,格式 `YYYY-MM-DD HH:mm` | +| `{url}` | 报表文件下载链接;链接为空时替换为兜底文案「文件生成中,稍后可在投递记录中查看」 | +| `{report_name}` | 报表名称 | +| `{biz_date}` | 数据日期 `YYYY-MM-DD` | + +- 示例模板:`【{report_name}】{biz_date} 数据报表已生成,下载:{url}(生成时间 {time})` + +#### 5.1.2 notify_group_ids(通知群,定向内部群) + +- 元素为 `wms_inbox_group.id`(内部群 ID),**正整数**、自动去重并升序,最多 **20** 个。 +- 保存时校验存在性:软删(已删除)的群报错并**列出缺失 ID**;被屏蔽(`is_blocked=1`)的群仍可选中, + 屏蔽属于发送时过滤维度。 +- 发送时逐群推送(群维度协议字段 `group_id`/`group_name` 为单值),并再次过滤 + `is_blocked=1`、软删、仓库维度不一致的群;此类群不发送且不进入投递记录快照。 + +#### 5.1.3 notify_member_ids(通知成员,定向外部成员) + +- 元素为**外部 IM 用户 ID**,**非空字符串**、自动去重,最多 **100** 个。 +- 推送时 `user_id` **数组整体透传**(目标侧协议支持 user_id 数组),不循环拆发; + 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送。 + +#### 5.1.4 发送规则与投递记录快照 + +- 未配置模板或未选择任何群/成员时**不发送**(投递行为不变)。 +- 发送时机:报表生成并完成渠道投递后(`delivered` 回写前),失败抛异常走失败退避重试 + (`MAX_RETRY=3`,退避 `retry_count × 60s`)。 +- 发送结果快照 `notify_targets` 随投递记录落库并在 `report.deliveryLog.list` 返回: + +```json +{ + "group_ids": [1, 3], + "member_ids": ["user-1001", "user-1002"], + "notify_text": "【7日出入库数据】2026-08-28 数据报表已生成,下载:https://...(生成时间 2026-08-29 09:00)" +} +``` + +- `group_ids` 为**实际发送**的群内部 ID 列表;`member_ids` 为实际发送的成员 ID 列表; + `notify_text` 为标签替换后的最终文本;未发送文本通知时快照为 `null`。 + +## 6. 报表定义保存示例(report.definition.save) + +```json +{ + "name": "库存变化以及补货报表", + "type": "stockFlow", + "fileName": "库存变化_{date}.xlsx", + "fields": ["item_code", "item_name", "barcode", "daily", "ck_total", "rk_total", "available", "total", "pending", "locked", "ck_avg", "suggest", "warn"], + "is_enabled": 1, + "remark": "" +} +``` + +- `type` 必须命中注册表(当前仅 `stockFlow`,未知报「未知的报表类型: 」); + `fields` 必须为该类型注册字段子集(16 个顶层字段任意勾选,含非法 key 报可读错误并列出可用字段)。 +- `file_name` 兼容 `fileName` 驼峰写法(驼峰优先);新增必填 `name`/`type`/`file_name`/`fields`; + 更新按 `id` upsert,未传字段不覆盖;软删记录命中时自动恢复。 +- 保存成功后响应即报表定义视图: + `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`。 + +## 7. report.definition.typeList / report.meta(前端元数据接口) + +### 7.1 用途 + +- `report.definition.typeList`:免权限只读(仅登录),返回注册类型清单 + `[{ key, title, description, window, fields }]`,供前端报表设计器渲染「报表类型」选择与字段树。 +- `report.meta`:免权限只读(仅登录,保留审计日志),按 `report_id` 返回 + `report_id/name/type/file_name/window/fields`(fields 含 `selected` 勾选标记与 `asText` 标记), + **不执行真实数据查询**。 + +实现:`report.definition.typeList` → `app/service/systemMethods/report/definition.js` → `systems/report.js listRegisteredTypes`; +`report.meta` → `app/service/systemMethods/report.js` → `systems/report.js getMeta`。 + +> 鉴权/日志口径:`report.definition.typeList` 在 `definition.js` 的 `systemInit` 名单内 +> (`_noNeedRight/_noNeedAuth/_noNeedLog='typeList'`:免权限 + 免鉴权 + 不写审计日志,仅登录; +> 同模块 `save/list/delete` 未声明免权限,仍需授权);`report.meta` 在 `_noNeedRight/_noNeedAuth` 名单内 +> (免权限 + 免仓库有效期校验,仅登录),未列入 `_noNeedLog` → **保留审计日志** +> (`generate`/`generateTaskProgress` 不写审计日志,二者行为不同)。 + +### 7.2 请求示例 + +```json +// report.definition.typeList(无必填参数) +{} + +// report.meta +{ "report_id": 1 } +``` + +- `report_id` 与 `reportId` 二选一(均传时优先 `reportId`);为空返回 + `flag=failure, code=0, message=报表ID report_id 必须为正整数`(HTTP 200)。 +- 定义不存在或已停用 → HTTP 500,`接口错误: 报表定义不存在或已停用: id=`。 + +### 7.3 响应示例 + +```json +// report.definition.typeList +{ + "flag": "success", + "code": 1, + "message": "ok", + "list": [ + { + "key": "stockFlow", + "title": "库存变化以及补货报表", + "description": "按日窗口聚合出入库流水与正品库存,……", + "window": { "dayCount": 7, "cutoverHour": 7 }, + "fields": [ + { "key": "item_code", "label": "商品编码", "type": "string", "asText": true }, + { "key": "daily", "label": "每日出入库", "type": "array", "children": [ + { "key": "ck", "label": "出库数", "type": "number" }, + { "key": "rk", "label": "入库数", "type": "number" } + ]}, + { "key": "suggest", "label": "建议补货量", "type": "number", "computed": true } + ] + } + ] +} + +// report.meta +{ + "flag": "success", + "code": 1, + "message": "ok", + "report_id": 1, + "name": "库存变化以及补货报表", + "type": "stockFlow", + "file_name": "库存变化_{date}.xlsx", + "window": { "dayCount": 7, "cutoverHour": 7 }, + "fields": [ + { "key": "item_code", "label": "商品编码", "type": "string", "asText": true, "selected": true }, + { "key": "barcode", "label": "条码", "type": "string", "asText": true, "selected": false } + ] +} +``` + +字段元素结构:`{ key, label, type, computed?, asText?, children?, selected? }`: + +- `type`:`string` / `number` / `boolean` / `array`; +- `computed: true`:预计算字段(非原始表字段,如 `suggest`/`warn`); +- `asText: true`:该列以文本单元格落地(由类型字段规格硬编码,如 `item_code`/`barcode`); +- `children`:数组类型字段的子字段(如 `daily` 的 `ck`/`rk`); +- `selected`(仅 `report.meta` 返回):该报表定义是否勾选此字段。 + +### 7.4 前端如何获取可用字段 + +1. 调用 `method=report.definition.typeList`(`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`) + 获取全部注册类型与字段树; +2. 保存报表定义时按类型字段树勾选 `fields`(`method=report.definition.save`); +3. 渲染/导出前调用 `method=report.meta`(入参 `report_id`)取窗口参数 `window.dayCount/cutoverHour` 与勾选标记 `selected`; +4. 导出 sheet 的列由「勾选字段 × 类型硬编码规格」自动生成,前端无需下发任何列配置。 + +## 8. 报表定义管理接口(report.definition.save / list / delete) + +管理侧维护 `wms_report_definition` 的 3 个接口,均需登录且需鉴权(`isNeedAuth=true`、`isNeedLogin=true`, +`POST /system`,header 带 `Authorization: Bearer ` 与 `platform`)。 + +- `report.definition.save`:按 `id` upsert(未传 id 新增),入参 + `{ id?, name, type, file_name/fileName, fields, is_enabled?, remark? }`; + `type` 必须命中注册表、`fields` 必须为该类型注册字段子集(非法 key 报可读错误列出); + 新增必填 `name/type/file_name/fields`;软删记录命中时自动恢复。 +- `report.definition.list`:`where { name, type, is_enabled }` + `pagination` + `sort` + (sort 白名单 `id/name/type/is_enabled/created_at/updated_at`,默认 id DESC); + 响应每行 `{ id, name, type, file_name, fields, is_enabled, remark, created_at, updated_at }`,软删自动排除。 +- `report.definition.delete`:入参 `id`;删除前按 `report_definition_id` 统计投递计划引用, + 仅拦截「启用中」的计划(`enabled=1`,报「存在 N 个启用的投递计划引用该报表,请先停用计划」), + 停用计划不阻断;重复删除同一 ID 幂等成功(`deleted` 恒为 1)。 +实现:`app/service/systemMethods/report/definition.js` → `app/service/systems/report.js` 的 +`saveDefinition` / `listDefinitions` / `deleteDefinition`。 + +> 鉴权口径:三个接口 `systemInit` 均未声明免权限(`isNeedAuth=true`),仅通配符角色 +> (超级管理员/仓库管理员)或已授权角色可用;本次仅文档同步,未扩任何角色授权 +> (权限缺口可用 `npm run permission:sync:system-api -- --dry-run` 预演)。 +