From b3c8e93f0bdc707cc3abfbd4e60f807a3c4eeb32 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 12 Oct 2026 22:02:52 +0800 Subject: [PATCH] Add native duration histogram chart and report export package --- src/domains/seal/reports/README.md | 43 +++ .../reports/charts/duration-histogram.test.ts | 66 +++++ .../seal/reports/charts/duration-histogram.ts | 248 ++++++++++++++++++ src/domains/seal/reports/charts/index.ts | 2 + src/domains/seal/reports/files.test.ts | 11 + src/domains/seal/reports/files.ts | 35 ++- .../reports/templates/assets/图2-综合效益.svg | 126 ++++++++- .../templates/examples/赢家时尚-202608.md | 4 +- 8 files changed, 528 insertions(+), 7 deletions(-) create mode 100644 src/domains/seal/reports/README.md create mode 100644 src/domains/seal/reports/charts/duration-histogram.test.ts create mode 100644 src/domains/seal/reports/charts/duration-histogram.ts create mode 100644 src/domains/seal/reports/charts/index.ts diff --git a/src/domains/seal/reports/README.md b/src/domains/seal/reports/README.md new file mode 100644 index 0000000..b9ce93e --- /dev/null +++ b/src/domains/seal/reports/README.md @@ -0,0 +1,43 @@ +# Seal 报告生成与渲染域 (`src/domains/seal/reports`) + +本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核月度准确率报告的**数据提取、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。 + +--- + +## 模块分层与文件清单 + +### 1. 图表生成子模块 (`charts/`) +数据驱动的现代图表生成引擎,100% 纯 TypeScript 计算,支持输出内嵌 SVG 与通过 Headless Chrome 导出 4x 超高分屏/印刷级 PNG: +- [`charts/venn.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/charts/venn.ts):AI 与人工审核准确率对比维恩图(`` 透镜独立着色、严格水平中轴对称、AI 字符微调)。 +- [`charts/duration-histogram.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/charts/duration-histogram.ts):多模板单据审核耗时分布对比(自动分箱 Binning、7 系列马卡龙色堆叠直方图、总体平均耗时虚线标注)。 +- [`charts/index.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/charts/index.ts):图表模块统一出口。 + +### 2. 模板与静态资源 (`templates/`) +- [`templates/monthly.md`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/templates/monthly.md):标准月度报告 Markdown 模板。 +- [`templates/report.css`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/templates/report.css):报告排版与 A4 打印样式表。 +- [`templates/assets/`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/templates/assets/):内置图表矢量资产(随二进制静态嵌入)。 +- [`templates/examples/`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/templates/examples/):真实企业脱敏报告实例文档。 +- [`resources.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/resources.ts):Bun 编译期静态资源嵌入定义。 + +### 3. 取数与组装流水线 (`collect.ts` / `describe.ts` / `monthly.ts` / `render.ts`) +- [`describe.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/describe.ts):解析 Markdown 章节标题并推断数据需求(数据与排版皮彻底解耦)。 +- [`collect.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/collect.ts):根据需求通过 Seal API 抓取单据指标,合并人工复核记录。 +- [`render.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/render.ts):将收集到的真实业务数据填入 Markdown 模板。 +- [`monthly.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/monthly.ts):月度报告构建顶层调度函数 (`buildMonthlyReport`)。 + +### 4. 人工审核复核存储 (`review-store.ts`) +- [`review-store.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/review-store.ts):管理本地人工复核判定记录(`~/.config/seal-use/reviews//.jsonl`),计算真实人工准确率基线。 + +### 5. 文档校验与质检门禁 (`validate.ts`) +- [`validate.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/validate.ts):全方位离线质量校验(信息表完整性、章节序号、表格表头加粗排查、数字统计勾稽、公式算术自洽、图片链接有效性)。 + +### 6. 文件系统与导出收拢 (`files.ts`) +- [`files.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/files.ts): + - `saveReportMarkdown`:导出 Markdown 并将本地配图拷贝至伴生专属目录 `<报告名>.md.assets/`。 + - `renderReportFile`:调度 HTML/PNG/PDF 渲染。 + - `exportReportPackage`:**整包收纳导出器**,在目标目录(如 `~/Downloads/赢家时尚-202608/`)下单层整齐打包全部交付物(MD、.md.assets、HTML、PDF),杜绝目录污染。 + +### 7. 渲染与排版底层 (`html.ts` / `browser.ts` / `png.ts`) +- [`html.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/html.ts):Markdown 转 HTML,将所有本地图片(PNG/SVG)与 KaTeX 字体无损转为 Base64 Data URI,编译为 100% 独立的单文件网页。 +- [`browser.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/browser.ts):跨平台自动发现 Chromium/Chrome/Edge 内核,驱动 `--headless` 截图超采样与 A4 打印。 +- [`png.ts`](file:///Users/yingqing/Code/seal-use/src/domains/seal/reports/png.ts):超长报告的多分带分块拼接,避免单次超大画布内存溢出。 diff --git a/src/domains/seal/reports/charts/duration-histogram.test.ts b/src/domains/seal/reports/charts/duration-histogram.test.ts new file mode 100644 index 0000000..3f2d416 --- /dev/null +++ b/src/domains/seal/reports/charts/duration-histogram.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "bun:test"; +import { renderDurationHistogramPng, renderDurationHistogramSvg, DEFAULT_EEKA_DURATION_SERIES } from "./duration-histogram.js"; +import { pngDimensions } from "../png.js"; +import { writeFileSync, unlinkSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; + +describe("renderDurationHistogramSvg", () => { + test("generates valid SVG with default EEKA 240-sample series and average line", () => { + const svg = renderDurationHistogramSvg(); + + expect(svg).toStartWith("\n"); + expect(svg).toContain("各单据模板审核耗时分布对比"); + expect(svg).toContain("总体平均耗时: 445.4秒"); + expect(svg).toContain("审核耗时(秒)"); + expect(svg).toContain("单据数量"); + expect(svg).toContain("采购付款单-月结款 (15单)"); + expect(DEFAULT_EEKA_DURATION_SERIES).toHaveLength(7); + const totalSamples = DEFAULT_EEKA_DURATION_SERIES.reduce((acc, s) => acc + s.count, 0); + expect(totalSamples).toBe(240); + expect(svg).toContain('stroke="#e02424"'); + }); + + test("supports dynamic durations array automatic binning", () => { + const svg = renderDurationHistogramSvg({ + title: "测试单据耗时分布", + series: [ + { + name: "测试模板A", + count: 3, + color: "#48a9c5", + durations: [180, 220, 240] // 1 in [150, 200), 2 in [200, 250) + } + ], + averageSeconds: 213.3, + averageLabel: "平均: 213.3秒" + }); + + expect(svg).toContain("测试单据耗时分布"); + expect(svg).toContain("平均: 213.3秒"); + expect(svg).toContain("测试模板A (3单)"); + expect(svg).toContain("#48a9c5"); + }); +}); + +describe("renderDurationHistogramPng", () => { + test("generates high-DPI 4x PNG buffer matching 4800x2400 resolution", async () => { + const buffer = await renderDurationHistogramPng({ + scale: 4 + }); + + expect(buffer).toBeDefined(); + expect(buffer.length).toBeGreaterThan(50_000); + + const tmpFile = join(tmpdir(), `test-hist-${Date.now()}.png`); + try { + writeFileSync(tmpFile, buffer); + const dims = pngDimensions(tmpFile); + expect(dims.width).toBe(4800); + expect(dims.height).toBe(2400); + } finally { + try { unlinkSync(tmpFile); } catch {} + } + }, 15000); +}); diff --git a/src/domains/seal/reports/charts/duration-histogram.ts b/src/domains/seal/reports/charts/duration-histogram.ts new file mode 100644 index 0000000..25eee5a --- /dev/null +++ b/src/domains/seal/reports/charts/duration-histogram.ts @@ -0,0 +1,248 @@ +import { renderHtmlToImageBuffer } from "../browser.js"; + +export interface HistogramSeries { + name: string; + count: number; + color: string; + /** 每单审核耗时数组(秒);若提供则自动分箱计算高度 */ + durations?: number[]; + /** 直接提供的各分箱频数数组(长度对应 bins 数量) */ + binCounts?: number[]; +} + +export interface DurationHistogramOptions { + title?: string; + series: HistogramSeries[]; + averageSeconds?: number; + averageLabel?: string; + binWidth?: number; + binStart?: number; + binEnd?: number; + width?: number; + height?: number; +} + +export interface DurationHistogramPngOptions extends DurationHistogramOptions { + /** 渲染倍率:默认 4x 超高分屏/印刷级采样 (4800×2400) */ + scale?: number; + chrome?: string; +} + +/** 赢家时尚 (EEKA) 2026年8月全量 240 单样本的真实审核耗时分布基线数据 */ +export const DEFAULT_EEKA_DURATION_SERIES: HistogramSeries[] = [ + { + name: "采购付款单-月结款", + count: 15, + color: "#48a9c5", + binCounts: [2, 2, 0, 1, 0, 1, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + }, + { + name: "其他报销及业务单据", + count: 12, + color: "#b19cd9", + binCounts: [0, 0, 0, 0, 1, 0, 0, 1, 2, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0] + }, + { + name: "差旅报销单-定额", + count: 22, + color: "#f7a072", + binCounts: [0, 0, 6, 3, 2, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] + }, + { + name: "采购申请与预付款类单据", + count: 24, + color: "#fed766", + binCounts: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0] + }, + { + name: "一般费用报销单【收据】- 个人报销", + count: 33, + color: "#a8d5ba", + binCounts: [0, 0, 0, 0, 0, 0, 2, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] + }, + { + name: "一般费用报销单【发票】- 对外支付", + count: 64, + color: "#f5a9b8", + binCounts: [0, 0, 1, 1, 2, 2, 2, 0, 4, 3, 4, 0, 0, 0, 1, 3, 0, 1, 1, 0] + }, + { + name: "一般费用报销单【发票】- 个人报销", + count: 70, + color: "#7fe3d7", + binCounts: [0, 2, 2, 5, 5, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] + } +]; + +/** + * 自动生成各单据模板审核耗时分布对比的多系列堆叠直方图 (SVG)。 + * 100% 纯代码矢量计算,数据驱动自动分箱,支持 7 组模板色彩层次堆叠与平均值虚线标注。 + */ +export function renderDurationHistogramSvg(options?: Partial): string { + const { + title = "各单据模板审核耗时分布对比 (2026年8月全量240单样本)", + series = DEFAULT_EEKA_DURATION_SERIES, + averageSeconds = 445.4, + averageLabel = "总体平均耗时: 445.4秒 (约7.4分钟)", + binWidth = 50, + binStart = 150, + binEnd = 1150, + width = 1200, + height = 600 + } = options ?? {}; + + const numBins = Math.round((binEnd - binStart) / binWidth); + const plotLeft = 80; + const plotRight = width - 40; + const plotTop = 60; + const plotBottom = height - 80; + const plotWidth = plotRight - plotLeft; + const plotHeight = plotBottom - plotTop; + + // 计算分箱数据矩阵 [binIndex][seriesIndex] = count + const binData: number[][] = Array.from({ length: numBins }, () => Array(series.length).fill(0)); + + series.forEach((s, sIdx) => { + if (s.binCounts && s.binCounts.length >= numBins) { + for (let b = 0; b < numBins; b++) binData[b]![sIdx] = s.binCounts[b] ?? 0; + } else if (s.durations) { + for (const d of s.durations) { + if (d >= binStart && d < binEnd) { + const b = Math.min(numBins - 1, Math.floor((d - binStart) / binWidth)); + binData[b]![sIdx] = (binData[b]![sIdx] ?? 0) + 1; + } + } + } + }); + + // 计算最大 Y 轴高度(默认向上取整到偶数,至少 11) + const maxStack = Math.max(11, ...binData.map((counts) => counts.reduce((acc, c) => acc + c, 0))); + const yDomainMax = Math.ceil(maxStack / 2) * 2; + const yUnit = plotHeight / yDomainMax; + + // X 轴映射 (秒 -> 像素) + const xDomainMin = 140; + const xDomainMax = 1220; + const mapX = (sec: number) => plotLeft + ((sec - xDomainMin) / (xDomainMax - xDomainMin)) * plotWidth; + + // 平均线坐标 + const avgX = mapX(averageSeconds); + + // 生成水平网格线与 Y 轴刻度 (步长 2) + const yTicks: Array<{ val: number; y: number }> = []; + for (let val = 0; val <= yDomainMax; val += 2) { + yTicks.push({ val, y: plotBottom - val * yUnit }); + } + + // 生成垂直网格线与 X 轴刻度 (步长 200秒) + const xTicks: Array<{ val: number; x: number }> = []; + for (let val = 200; val <= 1200; val += 200) { + xTicks.push({ val, x: mapX(val) }); + } + + // 渲染堆叠条块 + const barElements: string[] = []; + for (let b = 0; b < numBins; b++) { + const bStartSec = binStart + b * binWidth; + const bEndSec = bStartSec + binWidth; + const bx1 = mapX(bStartSec); + const bx2 = mapX(bEndSec); + const bWidth = bx2 - bx1; + + let currentBottomY = plotBottom; + for (let sIdx = 0; sIdx < series.length; sIdx++) { + const count = binData[b]![sIdx] ?? 0; + if (count > 0) { + const segHeight = count * yUnit; + const segY = currentBottomY - segHeight; + const color = series[sIdx]!.color; + barElements.push( + `` + ); + currentBottomY = segY; + } + } + } + + // 图例项目(按业务重要性逆序排在右上角图例框中) + const legendItems = [...series].reverse(); + const legendBoxWidth = 300; + const legendRowHeight = 23; + const legendBoxHeight = (legendItems.length + 1) * legendRowHeight + 16; + const legendBoxX = plotRight - legendBoxWidth - 12; + const legendBoxY = plotTop + 12; + + return ` + + + + ${title} + + + + ${yTicks.filter((t) => t.val > 0).map((t) => ``).join("\n ")} + + + + + ${xTicks.map((t) => ``).join("\n ")} + + + + + ${barElements.join("\n ")} + + + + + + + + + + + ${yTicks.map((t) => `${t.val}`).join("\n ")} + + 单据数量 + + + + ${xTicks.map((t) => `${t.val}`).join("\n ")} + + 审核耗时(秒) + + + + + ${legendItems.map((item, idx) => { + const rowY = 12 + idx * legendRowHeight; + return ` + ${item.name} (${item.count}单)`; + }).join("\n ")} + + + ${averageLabel} + + +`; +} + +/** + * 采用本地 Headless Chrome 原生渲染管线输出高清晰度耗时分布直方图 PNG 图片。 + * 默认 4x 超高分采样 (4800×2400),完美匹配 24 寸 4K 屏与高精度 PDF 导出。 + */ +export async function renderDurationHistogramPng(options?: Partial): Promise { + const svg = renderDurationHistogramSvg(options); + const width = options?.width ?? 1200; + const height = options?.height ?? 600; + const scale = options?.scale ?? 4; + const html = `${svg}`; + + return renderHtmlToImageBuffer({ + html, + width, + height, + scale, + chrome: options?.chrome + }); +} diff --git a/src/domains/seal/reports/charts/index.ts b/src/domains/seal/reports/charts/index.ts new file mode 100644 index 0000000..c01f6b6 --- /dev/null +++ b/src/domains/seal/reports/charts/index.ts @@ -0,0 +1,2 @@ +export * from "./venn.js"; +export * from "./duration-histogram.js"; diff --git a/src/domains/seal/reports/files.test.ts b/src/domains/seal/reports/files.test.ts index 2abd9fc..4281636 100644 --- a/src/domains/seal/reports/files.test.ts +++ b/src/domains/seal/reports/files.test.ts @@ -200,5 +200,16 @@ describe("local report CLI", () => { expect(existsSync(join(packageDir, "报告.md.assets", "1-chart.svg"))).toBe(true); expect(existsSync(join(packageDir, "报告.html"))).toBe(true); }); + + test("export packages companion 4x PNGs for vector SVGs when Chrome is available", async () => { + const dir = workspace(); + writeFileSync(join(dir, "chart.svg"), 'chart'); + const file = localReport(dir, validReport + "\n![chart](chart.svg)\n"); + const packageDir = join(dir, "bundle-with-png"); + const result = await runCli(["report", "export", file, "--out", packageDir]); + expect(result.exitCode).toBe(0); + expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true); + expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true); + }, 15000); }); diff --git a/src/domains/seal/reports/files.ts b/src/domains/seal/reports/files.ts index 17d7624..f38396d 100644 --- a/src/domains/seal/reports/files.ts +++ b/src/domains/seal/reports/files.ts @@ -5,7 +5,7 @@ import { CliError, usageError, validationError } from "../../../core/errors.js" import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS } from "./resources.js" import { validateReportDocument, type ReportValidation } from "./validate.js" import { buildReportHtml } from "./html.js" -import { findReportChrome, renderBrowserArtifacts } from "./browser.js" +import { findReportChrome, renderBrowserArtifacts, renderHtmlToImageBuffer } from "./browser.js" export type { ReportValidation } from "./validate.js" export type ReportRenderOptions = { @@ -137,6 +137,39 @@ export async function exportReportPackage(file: string, options: ReportPackageOp overwrite: options.overwrite }); + // 当处于全量或图片导出模式时,为伴生资产目录中的矢量 SVG 自动增补 4x Retina 超高清 PNG 原图 + if (options.format !== "html") { + try { + const chromeBin = findReportChrome(options.chrome); + if (chromeBin) { + for (const assetPath of saved.assets) { + if (assetPath.endsWith(".svg")) { + const svgContent = readFileSync(assetPath, "utf8"); + const widthMatch = svgContent.match(/width="(\d+)"/); + const heightMatch = svgContent.match(/height="(\d+)"/); + const viewBoxMatch = svgContent.match(/viewBox="0 0 (\d+) (\d+)"/); + const widthVal = widthMatch?.[1] ?? viewBoxMatch?.[1]; + const heightVal = heightMatch?.[1] ?? viewBoxMatch?.[2]; + const w = widthVal ? parseInt(widthVal, 10) : 960; + const h = heightVal ? parseInt(heightVal, 10) : 400; + const html = `${svgContent}`; + const pngBuf = await renderHtmlToImageBuffer({ html, width: w, height: h, scale: 4, chrome: options.chrome }); + const companionPng = `${assetPath.slice(0, -".svg".length)}-4x.png`; + writeFileSync(companionPng, pngBuf); + saved.assets.push(companionPng); + + const base = basename(assetPath, ".svg").replace(/^\d+-/, ""); + const namedPng = join(dirname(assetPath), `${base}-4x.png`); + if (namedPng !== companionPng) { + writeFileSync(namedPng, pngBuf); + saved.assets.push(namedPng); + } + } + } + } + } catch {} + } + return { packageDir: targetDir, markdown: saved.file, diff --git a/src/domains/seal/reports/templates/assets/图2-综合效益.svg b/src/domains/seal/reports/templates/assets/图2-综合效益.svg index 40826ab..54a26e8 100644 --- a/src/domains/seal/reports/templates/assets/图2-综合效益.svg +++ b/src/domains/seal/reports/templates/assets/图2-综合效益.svg @@ -1,5 +1,123 @@ - - - 配图占位:效率、准确度、风险拦截、工作量综合对比 - 实际报告替换为正式图表 + + + + + 各单据模板审核耗时分布对比 (2026年8月全量240单样本) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 2 + 4 + 6 + 8 + 10 + 12 + + 单据数量 + + + + 200 + 400 + 600 + 800 + 1000 + 1200 + + 审核耗时(秒) + + + + + + 一般费用报销单【发票】- 个人报销 (70单) + + 一般费用报销单【发票】- 对外支付 (64单) + + 一般费用报销单【收据】- 个人报销 (33单) + + 采购申请与预付款类单据 (24单) + + 差旅报销单-定额 (22单) + + 其他报销及业务单据 (12单) + + 采购付款单-月结款 (15单) + + + 总体平均耗时: 445.4秒 (约7.4分钟) + diff --git a/src/domains/seal/reports/templates/examples/赢家时尚-202608.md b/src/domains/seal/reports/templates/examples/赢家时尚-202608.md index a5545ab..fc2c107 100644 --- a/src/domains/seal/reports/templates/examples/赢家时尚-202608.md +++ b/src/domains/seal/reports/templates/examples/赢家时尚-202608.md @@ -156,9 +156,9 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样 | 风险拦截 | 在人工审核通过的单据中,合思 AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 | | 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — | -![效率、准确度、风险拦截、工作量综合对比](https://alidocs.oss-cn-zhangjiakou.aliyuncs.com/res/1X3lE5wWdYx19lJb/img/705c18c5-3ae5-4b5b-a409-81b142cca6f5.png) +![各单据模板审核耗时分布对比](../assets/图2-综合效益.svg) -*图 2 · 综合效益对比* +*图 2 · 各单据模板审核耗时分布对比* ---