diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 0604ff6..defdda4 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -4,15 +4,22 @@ import { runCapabilityResult } from "../helpers.js"; import { booleanOption, numberOption, stringOption } from "../parser.js"; import { outputOptions, printJson } from "../printer.js"; import { CliError, usageError } from "../../core/errors.js"; -import { renderReportFile, saveReportMarkdown, validateReportFile } from "../../domains/seal/reports/files.js"; -import type { MonthlyReportResult } from "../../domains/seal/reports/monthly.js"; -import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js"; +import { + exportReportPackage, + renderReportFile, + saveReportMarkdown, + validateReportFile, + loadReviews, + reviewFilePath, + writeReview, + type MonthlyReportResult +} from "../../domains/seal/reports/index.js"; import type { ParsedArgs } from "../types.js"; /** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */ -export async function handleLocalReportCommand(action: "validate" | "render", args: ParsedArgs) { +export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) { const file = args.command[2] ?? stringOption(args.options.file); - if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : ""}`); + if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`); if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。"); if (action === "validate") { const result = await validateReportFile(file); @@ -21,7 +28,16 @@ export async function handleLocalReportCommand(action: "validate" | "render", ar return; } const out = stringOption(args.options.out) ?? stringOption(args.options.o); - if (!out) throw usageError("Usage: seal-use report render <报告文件.md> --out <产物路径词干>"); + if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`); + if (action === "export") { + const result = await exportReportPackage(file, { + out, format: stringOption(args.options.format), width: numberOption(args.options.width), + chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite) + }); + printJson(result, outputOptions(args.options)); + if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1); + return; + } const result = await renderReportFile(file, { out, format: stringOption(args.options.format), width: numberOption(args.options.width), chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite) @@ -55,13 +71,20 @@ export async function handleReportCommand( ) as MonthlyReportResult; const out = stringOption(args.options.out) ?? stringOption(args.options.o); if (out) { - const saved = saveReportMarkdown(result.content, result.templatePath, out, booleanOption(args.options.overwrite)); + const saved = saveReportMarkdown( + result.content, + result.templatePath, + out, + booleanOption(args.options.overwrite), + result.dynamicAssets, + result.companionFiles + ); const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`; - printJson({ ...result, content: undefined, ...saved, next: { + printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: { validate: `seal-use report validate ${quotedFile}`, render: `seal-use report render ${quotedFile} --out build/report` } }, outputOptions(args.options)); - } else printJson(result, outputOptions(args.options)); + } else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options)); return; } diff --git a/src/cli/help.ts b/src/cli/help.ts index 1b89b8c..124c079 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -648,6 +648,19 @@ export const HELP_REGISTRY: AreaHelp[] = [ ], description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency." }, + { + name: "export", + summary: "Package Markdown, local 4x assets, self-contained HTML, and PDF into a dedicated directory", + usage: ["seal-use report export <报告.md> --out <输出目录> [--format ]"], + options: [ + { flag: "--out ", description: "Dedicated output directory for the report bundle" }, + { flag: "--format ", description: "all (default), html, or pdf" }, + { flag: "--width ", description: "PNG viewport width, default 1200" }, + { flag: "--chrome ", description: "Chrome/Chromium executable; otherwise auto-detected" }, + { flag: "--overwrite", description: "Explicitly permit replacing existing output files" } + ], + description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF." + }, { name: "review set", summary: "Record one human adjudication (who was right: AI or human) for a document", diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 309dbae..d1b15d7 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -224,7 +224,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { return; } - if (area === "report" && (action === "validate" || action === "render")) { + if (area === "report" && (action === "validate" || action === "render" || action === "export")) { await (await import("./commands/report.js")).handleLocalReportCommand(action, args); return; } diff --git a/src/domains/seal/capabilities/reports.ts b/src/domains/seal/capabilities/reports.ts index 8fd2b65..a57a860 100644 --- a/src/domains/seal/capabilities/reports.ts +++ b/src/domains/seal/capabilities/reports.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import type { KyInstance } from "ky"; -import { buildMonthlyReport } from "../reports/monthly.js"; +import { buildMonthlyReport } from "../reports/index.js"; import type { CapabilityContext } from "./helpers.js"; export const reportCapabilities = [ diff --git a/src/domains/seal/reports/README.md b/src/domains/seal/reports/README.md new file mode 100644 index 0000000..2ba3fa9 --- /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 水印图床依赖。 + +--- + +## 模块分层与目录结构 + +所有相关文件严格按职责收拢在对应的子目录中,根目录仅保留统一导出入口与本说明文档: + +``` +src/domains/seal/reports/ +├── charts/ # 图表生成子模块(100% 纯 TS 数据驱动矢量计算) +│ ├── venn.ts # 图 1:AI 与人工审核准确率对比维恩图 +│ ├── duration-histogram.ts # 图 2:多模板单据审核耗时分布对比堆叠直方图 +│ └── index.ts # 图表模块出口 +├── pipeline/ # 取数、推断与组装流水线 +│ ├── describe.ts # 解析 Markdown 标题并反推各章节数据需求 +│ ├── collect.ts # 通过 Seal API 抓取单据指标,合并人工复核记录 +│ ├── render.ts # 模板占位填充与章节内容排版 +│ ├── monthly.ts # 月度报告顶层调度器 (buildMonthlyReport) +│ ├── review-store.ts # 人工复核判定本地存储(JSONL 租户分片) +│ └── index.ts # 流水线出口 +├── render/ # 渲染与排版引擎底层 +│ ├── html.ts # Markdown 转自包含 HTML(资源内嵌 Data URI) +│ ├── browser.ts # 跨平台 Headless Chrome 驱动(PDF 打印与长图截取) +│ ├── png.ts # 多分带分块拼接与超大图流式生成 +│ └── index.ts # 渲染引擎出口 +├── validate/ # 离线质量校验与勾稽门禁 +│ ├── validate.ts # 信息表完整性、章节序号、表格格式、公式算术核验 +│ └── index.ts # 校验门禁出口 +├── export/ # 文件系统整包导出与资产收拢 +│ ├── files.ts # 报告整包打包器 (exportReportPackage) 及文件保存 +│ └── index.ts # 导出器出口 +├── templates/ # 模板与静态资源 +│ ├── monthly.md # 标准月度报告 Markdown 模板 +│ ├── report.css # 报告排版与 A4 打印样式表 +│ ├── resources.ts # Bun 编译期静态资源嵌入定义 +│ ├── assets/ # 内置图表矢量资产 +│ └── examples/ # 真实脱敏报告示例 +├── index.ts # 报告域对外统一门面出口 (Barrel) +└── README.md # 架构与开发指南 +``` 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..7141a93 --- /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 "../render/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..6c29528 --- /dev/null +++ b/src/domains/seal/reports/charts/duration-histogram.ts @@ -0,0 +1,248 @@ +import { renderHtmlToImageBuffer } from "../render/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/charts/venn.test.ts b/src/domains/seal/reports/charts/venn.test.ts index 258a8e8..5a54d68 100644 --- a/src/domains/seal/reports/charts/venn.test.ts +++ b/src/domains/seal/reports/charts/venn.test.ts @@ -1,5 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { renderVennAccuracySvg } from "./venn.js"; +import { renderVennAccuracyPng, renderVennAccuracySvg } from "./venn.js"; +import { pngDimensions } from "../render/png.js"; +import { writeFileSync, unlinkSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; describe("renderVennAccuracySvg", () => { test("generates valid SVG with correct computed differences and labels", () => { @@ -14,13 +18,13 @@ describe("renderVennAccuracySvg", () => { expect(svg).toContain("92.08%"); expect(svg).toContain("83.33%"); expect(svg).toContain("75.42%"); - // aiOnly = 92.08 - 75.42 = 16.66% or 16.67% expect(svg).toContain("16.66%"); - // humanOnly = 83.33 - 75.42 = 7.91% expect(svg).toContain("7.91%"); - expect(svg).toContain("AI审核准确"); + expect(svg).toContain("审核准确"); expect(svg).toContain("人工审核准确"); - expect(svg).toContain("AI与人工都准确"); + expect(svg).toContain("与人工都准确"); + expect(svg).toContain('clipPath id="left-circle-clip"'); + expect(svg).toContain('fill="#9ed4eb"'); }); test("supports customized labels and dimensions", () => { @@ -44,3 +48,27 @@ describe("renderVennAccuracySvg", () => { expect(svg).toContain("10.00%"); }); }); + +describe("renderVennAccuracyPng", () => { + test("generates high-DPI 4x PNG buffer matching 3840x1600 resolution", async () => { + const buffer = await renderVennAccuracyPng({ + aiAccuracy: 92.08, + humanAccuracy: 83.33, + bothAccurate: 75.42, + scale: 4 + }); + + expect(buffer).toBeDefined(); + expect(buffer.length).toBeGreaterThan(10_000); + + const tmpFile = join(tmpdir(), `test-venn-${Date.now()}.png`); + try { + writeFileSync(tmpFile, buffer); + const dims = pngDimensions(tmpFile); + expect(dims.width).toBe(3840); + expect(dims.height).toBe(1600); + } finally { + try { unlinkSync(tmpFile); } catch {} + } + }, 15000); +}); diff --git a/src/domains/seal/reports/charts/venn.ts b/src/domains/seal/reports/charts/venn.ts index 9c2c980..97997da 100644 --- a/src/domains/seal/reports/charts/venn.ts +++ b/src/domains/seal/reports/charts/venn.ts @@ -1,3 +1,5 @@ +import { renderHtmlToImageBuffer } from "../render/browser.js"; + export interface VennAccuracyOptions { aiAccuracy: number; humanAccuracy: number; @@ -9,6 +11,20 @@ export interface VennAccuracyOptions { height?: number; } +export interface VennPngOptions extends VennAccuracyOptions { + /** 渲染清晰度倍率:默认 4x 超高分屏/印刷级采样 (3840×1600),兼顾 4K 屏点对点与极端放大清晰度 */ + scale?: number; + chrome?: string; +} + +function formatLabelWithAiKerning(label: string, aiSpacing = "1.5px", restSpacing = "0px"): string { + if (label.startsWith("AI")) { + const rest = label.slice(2); + return `AI${rest ? `${rest}` : ""}`; + } + return restSpacing !== "0px" ? `${label}` : label; +} + /** * 自动生成 AI 与人工审核准确率对比的精美矢量维恩交集图 (SVG)。 * 100% 纯代码矢量计算,无位图缩放模糊,离线自包含,杜绝外部 OSS 图床与水印。 @@ -21,46 +37,84 @@ export function renderVennAccuracySvg(options: VennAccuracyOptions): string { aiLabel = "AI审核准确", humanLabel = "人工审核准确", bothLabel = "AI与人工都准确", - width = 920, + width = 960, height = 400 } = options; const aiOnly = Math.max(0, Number((aiAccuracy - bothAccurate).toFixed(2))); const humanOnly = Math.max(0, Number((humanAccuracy - bothAccurate).toFixed(2))); - const fmt = (v: number) => `${v.toFixed(2)}%`; - return ` - + return ` + + + + + + - - + - - + + - - ${fmt(aiOnly)} + + - - - ${aiLabel} - (总准确率${fmt(aiAccuracy)}) + + - - ${fmt(bothAccurate)} + + + ${formatLabelWithAiKerning(aiLabel, "1.5px")} + (总准确率${fmt(aiAccuracy)}) + + + - - - ${bothLabel} + + ${fmt(aiOnly)} - - ${fmt(humanOnly)} + + ${fmt(bothAccurate)} - - - ${humanLabel} - (总准确率${fmt(humanAccuracy)}) + + ${fmt(humanOnly)} + + + + + + + ${humanLabel} + (总准确率${fmt(humanAccuracy)}) + + + + + + + ${formatLabelWithAiKerning(bothLabel, "2px", "1px")} `; } + +/** + * 采用本地 Headless Chrome 原生渲染管线输出高清晰度维恩图 PNG 图片。 + * 默认 4x 超高分采样 (3840×1600),完美匹配 24 寸 4K 屏与高精度 PDF 导出。 + */ +export async function renderVennAccuracyPng(options: VennPngOptions): Promise { + const svg = renderVennAccuracySvg(options); + const width = options.width ?? 960; + const height = options.height ?? 400; + const scale = options.scale ?? 4; + const html = `${svg}`; + + return renderHtmlToImageBuffer({ + html, + width, + height, + scale, + chrome: options.chrome + }); +} diff --git a/src/domains/seal/reports/files.test.ts b/src/domains/seal/reports/export/files.test.ts similarity index 85% rename from src/domains/seal/reports/files.test.ts rename to src/domains/seal/reports/export/files.test.ts index c0017da..3789782 100644 --- a/src/domains/seal/reports/files.test.ts +++ b/src/domains/seal/reports/export/files.test.ts @@ -3,10 +3,10 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { join } from "node:path"; import { PNG } from "pngjs"; -import { runCli } from "../../../cli/runner.js"; -import { buildMonthlyReport } from "./monthly.js"; +import { runCli } from "../../../../cli/runner.js"; +import { buildMonthlyReport } from "../pipeline/index.js"; import { renderReportFile, saveReportMarkdown, validateReportFile } from "./files.js"; -import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "./resources.js"; +import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js"; const dirs: string[] = []; const originalCwd = process.cwd(); @@ -94,7 +94,7 @@ describe("bundled report templates", () => { writeFileSync(file, "existing"); expect(() => saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, file)).toThrow("--overwrite"); expect(readFileSync(file, "utf8")).toBe("existing"); - expect(existsSync(join(dir, "report.assets"))).toBe(false); + expect(existsSync(join(dir, "report.md.assets"))).toBe(false); }); }); @@ -185,4 +185,31 @@ describe("local report CLI", () => { expect(result.artifacts.map((artifact) => artifact.format)).toEqual(["html", "png"]); expect(existsSync(out + ".png")).toBe(true); }); + + test("export packages Markdown, .md.assets, self-contained HTML, and PDF into a single directory", async () => { + const dir = workspace(); + writeFileSync(join(dir, "chart.svg"), 'chart'); + const file = localReport(dir, validReport + "\n![chart](chart.svg)\n"); + const packageDir = join(dir, "my-report-bundle"); + const result = await runCli(["report", "export", file, "--out", packageDir, "--format", "html"]); + expect(result.exitCode).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.packageDir).toBe(packageDir); + expect(existsSync(join(packageDir, "报告.md"))).toBe(true); + expect(existsSync(join(packageDir, "报告.md.assets"))).toBe(true); + 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/export/files.ts b/src/domains/seal/reports/export/files.ts new file mode 100644 index 0000000..f0657bb --- /dev/null +++ b/src/domains/seal/reports/export/files.ts @@ -0,0 +1,223 @@ +import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os" +import { basename, dirname, extname, join, resolve } from "node:path" +import { CliError, usageError, validationError } from "../../../../core/errors.js" +import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS } from "../templates/resources.js" +import { validateReportDocument, type ReportValidation } from "../validate/index.js" +import { buildReportHtml, findReportChrome, renderBrowserArtifacts, renderHtmlToImageBuffer } from "../render/index.js" +import { buildMarkdownFallbackLedger } from "./ledger.js" + +export type { ReportValidation } from "../validate/index.js" +export type ReportRenderOptions = { + out: string; + format?: string; + width?: number; + chrome?: string; + overwrite?: boolean; +}; + +function inputFile(file: string): string { + const path = resolve(file); + if (!existsSync(path) || !statSync(path).isFile()) throw validationError(`报告文件不存在或不是文件:${path}`); + return path; +} + +function checkOutput(path: string, overwrite = false) { + if (existsSync(path) && (!overwrite || !statSync(path).isFile())) { + throw validationError(`输出已存在或不是文件:${path}。覆盖已有文件须显式传 --overwrite。`); + } +} + +/** Export the Markdown and its local images together, without changing a custom template's source assets. */ +export function saveReportMarkdown( + content: string, + templatePath: string, + output: string, + overwrite = false, + dynamicAssets?: Record, + companionFiles?: { csv: string; xlsx: Buffer } +) { + const file = resolve(output); + const stem = basename(file, extname(file)); + const assetDir = `${basename(file)}.assets`; + const files = new Map(); + const images = new Map(); + const savedContent = content.replace(/(!\[[^\]]*\]\()([^)\n]+)(\))/g, (match, before: string, source: string, after: string) => { + if (/^(?:https?:|data:|file:)/.test(source)) return match; + const path = decodeURIComponent(source); + let target = images.get(path); + if (!target) { + const cleanBase = basename(path).replace(/^\d+-/, ""); + target = `${assetDir}/${images.size + 1}-${cleanBase}`; + const dynamic = dynamicAssets?.[path] ?? dynamicAssets?.[basename(path)] ?? dynamicAssets?.[cleanBase]; + const bundled = templatePath === BUILTIN_TEMPLATE_PATH ? REPORT_ASSETS[path] : undefined; + const data = dynamic ?? bundled ?? readFileSync(inputFile(resolve(dirname(templatePath), path))); + files.set(resolve(dirname(file), target), data); + images.set(path, target); + } + return `${before}${encodeURI(target)}${after}`; + }); + files.set(file, savedContent); + const ledgers: string[] = []; + if (companionFiles) { + const csvPath = join(dirname(file), `${stem}-明细台账.csv`); + const xlsxPath = join(dirname(file), `${stem}-明细台账.xlsx`); + files.set(csvPath, companionFiles.csv); + files.set(xlsxPath, companionFiles.xlsx); + ledgers.push(xlsxPath, csvPath); + } + for (const path of files.keys()) checkOutput(path, overwrite); + for (const [path, data] of files) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, data, { flag: overwrite ? "w" : "wx" }); + } + return { + file, + assets: [...files.keys()].filter((path) => path !== file && !ledgers.includes(path)), + ...(ledgers.length > 0 ? { ledgers } : {}) + }; +} + +/** Local validation deliberately needs no tenant selection, token, HTTP client or external interpreter. */ +export async function validateReportFile(file: string): Promise { + return validateReportDocument(inputFile(file)) +} + +/** Render through bundled TypeScript modules and the existing browser, returning clean JSON. */ +export async function renderReportFile(file: string, options: ReportRenderOptions) { + const path = inputFile(file); + const format = options.format ?? "all"; + if (!["all", "html", "png", "pdf"].includes(format)) throw usageError("Invalid --format: use all, html, png, or pdf."); + const width = options.width ?? 1200; + if (!Number.isInteger(width) || width < 320 || width > 5000) throw usageError("Invalid --width: use an integer from 320 to 5000."); + const stem = resolve(options.out); + const formats = format === "all" ? ["html", "png", "pdf"] : format === "html" ? ["html"] : ["html", format]; + const destinations = formats.map((extension) => `${stem}.${extension}`); + if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。"); + for (const destination of destinations) checkOutput(destination, options.overwrite); + const validation = await validateReportFile(path) + if (!validation.valid) return { file: path, validation, artifacts: [] } + const binary = formats.length > 1 ? findReportChrome(options.chrome) : undefined + const stage = mkdtempSync(join(tmpdir(), "seal-report-render-")) + try { + const html = join(stage, "report.html") + writeFileSync(html, await buildReportHtml(path)) + if (binary) { + const profile = join(stage, "browser-profile") + mkdirSync(profile, { mode: 0o700 }) + await renderBrowserArtifacts(html, formats, width, binary, profile) + } + const rendered = formats.map((format) => { + const file = join(stage, `report.${format}`) + const bytes = statSync(file).size + if (!bytes) throw new CliError(`报告渲染产物为空:${format}`, 1) + return { file, format, bytes } + }) + // Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact. + mkdirSync(dirname(stem), { recursive: true }) + const artifacts = rendered.map((artifact) => { + const destination = `${stem}.${artifact.format}` + copyFileSync(artifact.file, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL) + return { path: destination, format: artifact.format, bytes: artifact.bytes } + }) + return { file: path, validation, artifacts } + } finally { + rmSync(stage, { recursive: true, force: true }) + } +} + +export type ReportPackageOptions = { + out: string; + format?: string; + width?: number; + chrome?: string; + overwrite?: boolean; +}; + +/** + * 将报告整包导出至独立目录中(单层文件夹收拢,零散落)。 + * 目录内包含: + * - .md 及 .md.assets/ (含全部 4x 超高清原图) + * - .html (自包含单文件) + * - .pdf (打印级 PDF) + */ +export async function exportReportPackage(file: string, options: ReportPackageOptions) { + const sourcePath = inputFile(file); + const targetDir = resolve(options.out); + const stem = basename(sourcePath, extname(sourcePath)); + mkdirSync(targetDir, { recursive: true }); + + const targetMd = join(targetDir, `${stem}.md`); + const content = readFileSync(sourcePath, "utf8"); + const saved = saveReportMarkdown(content, sourcePath, targetMd, options.overwrite); + + const renderResult = await renderReportFile(saved.file, { + out: join(targetDir, stem), + format: options.format ?? "all", + width: options.width, + chrome: options.chrome, + 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 {} + } + + const ledgers: string[] = []; + if (renderResult.validation.valid) { + const sourceCsv = join(dirname(sourcePath), `${stem}-明细台账.csv`); + const sourceXlsx = join(dirname(sourcePath), `${stem}-明细台账.xlsx`); + const targetCsv = join(targetDir, `${stem}-明细台账.csv`); + const targetXlsx = join(targetDir, `${stem}-明细台账.xlsx`); + if (existsSync(sourceCsv) && existsSync(sourceXlsx)) { + if (resolve(sourceCsv) !== resolve(targetCsv)) { + copyFileSync(sourceCsv, targetCsv, options.overwrite ? 0 : constants.COPYFILE_EXCL); + copyFileSync(sourceXlsx, targetXlsx, options.overwrite ? 0 : constants.COPYFILE_EXCL); + } + } else { + const fallback = await buildMarkdownFallbackLedger(content); + writeFileSync(targetCsv, fallback.csv, { flag: options.overwrite ? "w" : "wx" }); + writeFileSync(targetXlsx, fallback.xlsx, { flag: options.overwrite ? "w" : "wx" }); + } + ledgers.push(targetXlsx, targetCsv); + } + + return { + packageDir: targetDir, + markdown: saved.file, + assets: saved.assets, + ledgers, + validation: renderResult.validation, + artifacts: renderResult.artifacts + }; +} + diff --git a/src/domains/seal/reports/export/index.ts b/src/domains/seal/reports/export/index.ts new file mode 100644 index 0000000..1d92053 --- /dev/null +++ b/src/domains/seal/reports/export/index.ts @@ -0,0 +1 @@ +export * from "./files.js"; diff --git a/src/domains/seal/reports/export/ledger.ts b/src/domains/seal/reports/export/ledger.ts new file mode 100644 index 0000000..43d7aab --- /dev/null +++ b/src/domains/seal/reports/export/ledger.ts @@ -0,0 +1,204 @@ +import ExcelJS from "exceljs"; +import type { ReportBlock, ReportData } from "../pipeline/collect.js"; + +function csvEscape(val: string | number | undefined): string { + if (val === undefined || val === null) return ""; + const str = String(val).replace(/\r?\n/g, " ").trim(); + if (/[",\n]/.test(str)) { + return `"${str.replace(/"/g, '""')}"`; + } + return str; +} + +function formatAgreement(agreement: ReportBlock["agreement"]): string { + if (agreement === "agreed") return "一致"; + if (agreement === "diverged") return "分歧"; + return "未完结/流转中"; +} + +function formatVerdict(block: ReportBlock): string { + if (block.agreement === "unknown") return "待人工审批完结"; + const v = block.verdict; + if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方一致正确 (D1/D2)"; + if (v === "ai_correct" || (!v && block.agreement === "diverged")) return "AI 依规正确 / 人工失准 (D4)"; + if (v === "human_correct") return "人工合理 / AI 失准"; + if (v === "both_wrong") return "双方均失准"; + return "待复核"; +} + +/** + * 构建带 UTF-8 BOM 的月度跑批与人工复核明细台账 CSV + */ +export function buildReportLedgerCsv(data: ReportData): string { + const headers = [ + "单据编号(SN)", + "单据模板", + "单据标题/事由", + "提交人", + "费用承担部门", + "跑批时间", + "AI审批决策", + "人工审批结论", + "人机一致性", + "复核定性结论", + "复核人", + "复核批注说明", + "审批耗时(秒)", + "AI审核意见摘要" + ]; + + const rows = data.blocks.map((block) => { + const review = data.reviews.get(block.sn); + return [ + block.sn, + block.template || "—", + block.title || "—", + block.submitter || "—", + block.department || "—", + block.createdAt || "—", + block.aiDecision || "—", + block.humanResult || "—", + formatAgreement(block.agreement), + formatVerdict(block), + review?.reviewedBy || "—", + review?.note || "—", + block.durationSeconds ?? "", + block.aiSummary || "—" + ].map(csvEscape).join(","); + }); + + return "\uFEFF" + [headers.join(","), ...rows].join("\n") + "\n"; +} + +/** + * 构建双 Sheet 的专业月度跑批与复核台账 Excel (.xlsx) + */ +export async function buildReportLedgerXlsx(data: ReportData): Promise { + const workbook = new ExcelJS.Workbook(); + workbook.creator = "seal-use"; + workbook.created = new Date(); + + const detailSheet = workbook.addWorksheet("跑批与复核明细", { + views: [{ state: "frozen", ySplit: 1 }] + }); + + detailSheet.columns = [ + { header: "单据编号(SN)", key: "sn", width: 16 }, + { header: "单据模板", key: "template", width: 20 }, + { header: "单据标题/事由", key: "title", width: 32 }, + { header: "提交人", key: "submitter", width: 12 }, + { header: "费用承担部门", key: "department", width: 22 }, + { header: "跑批时间", key: "createdAt", width: 20 }, + { header: "AI审批决策", key: "aiDecision", width: 15 }, + { header: "人工审批结论", key: "humanResult", width: 16 }, + { header: "人机一致性", key: "agreement", width: 14 }, + { header: "复核定性结论", key: "verdict", width: 24 }, + { header: "复核人", key: "reviewedBy", width: 14 }, + { header: "复核批注说明", key: "note", width: 38 }, + { header: "审批耗时(秒)", key: "durationSeconds", width: 14 }, + { header: "AI审核意见摘要", key: "aiSummary", width: 55 } + ]; + + const headerRow = detailSheet.getRow(1); + headerRow.font = { bold: true, color: { argb: "FFFFFFFF" }, size: 11 }; + headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FF1E3A8A" } }; + headerRow.alignment = { vertical: "middle", horizontal: "center" }; + headerRow.height = 24; + + for (const block of data.blocks) { + const review = data.reviews.get(block.sn); + const row = detailSheet.addRow({ + sn: block.sn, + template: block.template || "—", + title: block.title || "—", + submitter: block.submitter || "—", + department: block.department || "—", + createdAt: block.createdAt || "—", + aiDecision: block.aiDecision || "—", + humanResult: block.humanResult || "—", + agreement: formatAgreement(block.agreement), + verdict: formatVerdict(block), + reviewedBy: review?.reviewedBy || "—", + note: review?.note || "—", + durationSeconds: block.durationSeconds ?? "", + aiSummary: block.aiSummary || "—" + }); + row.alignment = { vertical: "top", wrapText: true }; + } + + detailSheet.autoFilter = { + from: { row: 1, column: 1 }, + to: { row: 1, column: detailSheet.columns.length } + }; + + if (data.templateGroups.length > 0) { + const summarySheet = workbook.addWorksheet("分模板统计汇总", { + views: [{ state: "frozen", ySplit: 1 }] + }); + summarySheet.columns = [ + { header: "单据模板", key: "template", width: 24 }, + { header: "跑批总单量", key: "total", width: 14 }, + { header: "已完结单量", key: "evaluated", width: 14 }, + { header: "AI 准确率", key: "aiAcc", width: 14 }, + { header: "人工准确率", key: "humanAcc", width: 14 }, + { header: "人机一致率", key: "bothAcc", width: 14 }, + { header: "人工同意:驳回", key: "ratio", width: 18 } + ]; + const sumHeader = summarySheet.getRow(1); + sumHeader.font = { bold: true, color: { argb: "FFFFFFFF" }, size: 11 }; + sumHeader.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FF1E3A8A" } }; + sumHeader.alignment = { vertical: "middle", horizontal: "center" }; + sumHeader.height = 24; + + for (const g of data.templateGroups) { + const ev = g.evaluated || g.total || 1; + const aiPct = g.aiCorrect !== undefined ? `${((g.aiCorrect / ev) * 100).toFixed(2)}%` : `${((g.agreed / ev) * 100).toFixed(2)}%`; + const humanPct = g.humanCorrect !== undefined ? `${((g.humanCorrect / ev) * 100).toFixed(2)}%` : "—"; + const bothPct = g.bothCorrect !== undefined ? `${((g.bothCorrect / ev) * 100).toFixed(2)}%` : `${((g.agreed / ev) * 100).toFixed(2)}%`; + const ratio = g.humanPass !== undefined && g.humanReject !== undefined + ? `${g.evaluated ?? g.total}(${g.humanPass}:${g.humanReject})` + : `${g.total} 笔`; + + summarySheet.addRow({ + template: g.template, + total: g.total, + evaluated: g.evaluated ?? g.total, + aiAcc: aiPct, + humanAcc: humanPct, + bothAcc: bothPct, + ratio + }); + } + } + + const arrayBuffer = await workbook.xlsx.writeBuffer(); + return Buffer.from(arrayBuffer); +} + +/** + * 当针对独立 Markdown 文件直接执行 report export 且无预生成台账时,从 Markdown 表格提取构建台账 + */ +export async function buildMarkdownFallbackLedger(markdownContent: string): Promise<{ csv: string; xlsx: Buffer }> { + const lines = markdownContent.split(/\r?\n/); + const rows: string[][] = []; + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) continue; + const cells = trimmed.slice(1, -1).split("|").map((c) => c.trim().replace(/\*\*/g, "")); + if (cells.every((c) => /^[-:]+$/.test(c))) continue; + if (cells.length >= 5) { + rows.push(cells); + } + } + + const finalRows = rows.length > 0 ? rows : [["单据编号", "单据模板", "AI审批决策", "人工审批结论", "复核结论"]]; + const csv = "\uFEFF" + finalRows.map((r) => r.map(csvEscape).join(",")).join("\n") + "\n"; + + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet("报告明细台账"); + for (const r of finalRows) { + sheet.addRow(r); + } + const arrayBuffer = await workbook.xlsx.writeBuffer(); + return { csv, xlsx: Buffer.from(arrayBuffer) }; +} diff --git a/src/domains/seal/reports/files.ts b/src/domains/seal/reports/files.ts deleted file mode 100644 index c8e00a0..0000000 --- a/src/domains/seal/reports/files.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os" -import { basename, dirname, extname, join, resolve } from "node:path" -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" - -export type { ReportValidation } from "./validate.js" -export type ReportRenderOptions = { - out: string; - format?: string; - width?: number; - chrome?: string; - overwrite?: boolean; -}; - -function inputFile(file: string): string { - const path = resolve(file); - if (!existsSync(path) || !statSync(path).isFile()) throw validationError(`报告文件不存在或不是文件:${path}`); - return path; -} - -function checkOutput(path: string, overwrite = false) { - if (existsSync(path) && (!overwrite || !statSync(path).isFile())) { - throw validationError(`输出已存在或不是文件:${path}。覆盖已有文件须显式传 --overwrite。`); - } -} - -/** Export the Markdown and its local images together, without changing a custom template's source assets. */ -export function saveReportMarkdown(content: string, templatePath: string, output: string, overwrite = false) { - const file = resolve(output); - const assetDir = `${basename(file, extname(file))}.assets`; - const files = new Map(); - const images = new Map(); - const savedContent = content.replace(/(!\[[^\]]*\]\()([^)\n]+)(\))/g, (match, before: string, source: string, after: string) => { - if (/^(?:https?:|data:|file:)/.test(source)) return match; - const path = decodeURIComponent(source); - let target = images.get(path); - if (!target) { - target = `${assetDir}/${images.size + 1}-${basename(path)}`; - const bundled = templatePath === BUILTIN_TEMPLATE_PATH ? REPORT_ASSETS[path] : undefined; - const data = bundled ?? readFileSync(inputFile(resolve(dirname(templatePath), path))); - files.set(resolve(dirname(file), target), data); - images.set(path, target); - } - return `${before}${encodeURI(target)}${after}`; - }); - files.set(file, savedContent); - for (const path of files.keys()) checkOutput(path, overwrite); - for (const [path, data] of files) { - mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, data, { flag: overwrite ? "w" : "wx" }); - } - return { file, assets: [...files.keys()].filter((path) => path !== file) }; -} - -/** Local validation deliberately needs no tenant selection, token, HTTP client or external interpreter. */ -export async function validateReportFile(file: string): Promise { - return validateReportDocument(inputFile(file)) -} - -/** Render through bundled TypeScript modules and the existing browser, returning clean JSON. */ -export async function renderReportFile(file: string, options: ReportRenderOptions) { - const path = inputFile(file); - const format = options.format ?? "all"; - if (!["all", "html", "png", "pdf"].includes(format)) throw usageError("Invalid --format: use all, html, png, or pdf."); - const width = options.width ?? 1200; - if (!Number.isInteger(width) || width < 320 || width > 5000) throw usageError("Invalid --width: use an integer from 320 to 5000."); - const stem = resolve(options.out); - const formats = format === "all" ? ["html", "png", "pdf"] : format === "html" ? ["html"] : ["html", format]; - const destinations = formats.map((extension) => `${stem}.${extension}`); - if (destinations.includes(path)) throw validationError("渲染输出不能覆盖报告源文件。"); - for (const destination of destinations) checkOutput(destination, options.overwrite); - const validation = await validateReportFile(path) - if (!validation.valid) return { file: path, validation, artifacts: [] } - const binary = formats.length > 1 ? findReportChrome(options.chrome) : undefined - const stage = mkdtempSync(join(tmpdir(), "seal-report-render-")) - try { - const html = join(stage, "report.html") - writeFileSync(html, await buildReportHtml(path)) - if (binary) { - const profile = join(stage, "browser-profile") - mkdirSync(profile, { mode: 0o700 }) - await renderBrowserArtifacts(html, formats, width, binary, profile) - } - const rendered = formats.map((format) => { - const file = join(stage, `report.${format}`) - const bytes = statSync(file).size - if (!bytes) throw new CliError(`报告渲染产物为空:${format}`, 1) - return { file, format, bytes } - }) - // Publish only after the full requested set succeeds; failed rendering leaves existing outputs intact. - mkdirSync(dirname(stem), { recursive: true }) - const artifacts = rendered.map((artifact) => { - const destination = `${stem}.${artifact.format}` - copyFileSync(artifact.file, destination, options.overwrite ? 0 : constants.COPYFILE_EXCL) - return { path: destination, format: artifact.format, bytes: artifact.bytes } - }) - return { file: path, validation, artifacts } - } finally { - rmSync(stage, { recursive: true, force: true }) - } -} diff --git a/src/domains/seal/reports/index.ts b/src/domains/seal/reports/index.ts new file mode 100644 index 0000000..f1b1d43 --- /dev/null +++ b/src/domains/seal/reports/index.ts @@ -0,0 +1,6 @@ +export * from "./charts/index.js"; +export * from "./pipeline/index.js"; +export * from "./render/index.js"; +export * from "./validate/index.js"; +export * from "./export/index.js"; +export * from "./templates/resources.js"; diff --git a/src/domains/seal/reports/collect.ts b/src/domains/seal/reports/pipeline/collect.ts similarity index 56% rename from src/domains/seal/reports/collect.ts rename to src/domains/seal/reports/pipeline/collect.ts index e5753be..21dc590 100644 --- a/src/domains/seal/reports/collect.ts +++ b/src/domains/seal/reports/pipeline/collect.ts @@ -1,7 +1,7 @@ import type { KyInstance } from "ky"; -import * as api from "../api.js"; -import { formatBeijingIso } from "../../../core/config/timestamps.js"; -import type { ApprovalRun } from "../types.js"; +import * as api from "../../api.js"; +import { formatBeijingIso } from "../../../../core/config/timestamps.js"; +import type { ApprovalRun } from "../../types.js"; import type { ReportDemand } from "./describe.js"; import { loadReviews, type ReviewRecord } from "./review-store.js"; @@ -11,7 +11,7 @@ type Polarity = "pass" | "reject" | "unknown"; function polarityOf(value: string | undefined): Polarity { if (!value) return "unknown"; const text = value.trim(); - if (/同意|通过|approve|pass/i.test(text)) return "pass"; + if (/同意|通过|approve|pass|已支付|审批完成/i.test(text)) return "pass"; if (/驳回|拒绝|终止|退回|reject|deny/i.test(text)) return "reject"; return "unknown"; } @@ -19,6 +19,11 @@ function polarityOf(value: string | undefined): Polarity { export type ReportBlock = { sn: string; template: string; + title?: string; + submitter?: string; + department?: string; + createdAt?: string; + durationSeconds?: number; aiDecision: string | undefined; humanResult: string | undefined; agreement: "agreed" | "diverged" | "unknown"; @@ -33,6 +38,12 @@ export type ReportTemplateGroup = { total: number; agreed: number; diverged: number; + evaluated?: number; + aiCorrect?: number; + humanCorrect?: number; + bothCorrect?: number; + humanPass?: number; + humanReject?: number; }; export type ReportData = { @@ -81,12 +92,16 @@ export type CollectOptions = { loadReviews?: boolean; }; -function monthRange(month: string): { startDate: string; endDate: string } { +function monthRange(month: string): { startDate: string; endDate: string; startIsoDate: string; endIsoDate: string } { const [y, m] = month.split("-").map(Number); if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`); const start = Date.UTC(y, m - 1, 1); const end = Date.UTC(y, m, 1) - 1; - return { startDate: String(start), endDate: String(end) }; + const lastDay = new Date(y, m, 0).getDate(); + const pad = (n: number) => String(n).padStart(2, "0"); + const startIsoDate = `${y}-${pad(m)}-01`; + const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`; + return { startDate: String(start), endDate: String(end), startIsoDate, endIsoDate }; } /** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */ @@ -152,16 +167,16 @@ export async function collectReportData( if (demands.has("riskStats") || demands.has("riskDetails")) { try { const stats = await api.getInsightStats(client, { - startDate: range.startDate, - endDate: range.endDate, + startDate: range.startIsoDate, + endDate: range.endIsoDate, limit: 50 }); - const rawList = ((stats as { tags?: unknown }).tags ?? (stats as { list?: unknown }).list ?? []) as Array>; + const tagStats = stats.tagStats ?? []; data.riskStats = { - tags: rawList.slice(0, 20).map((tag) => ({ - id: typeof tag.id === "string" ? tag.id : undefined, - name: typeof tag.name === "string" ? tag.name : typeof tag.title === "string" ? tag.title : undefined, - count: typeof tag.count === "number" ? tag.count : typeof tag.value === "number" ? tag.value : undefined + tags: tagStats.slice(0, 20).map((tag) => ({ + id: tag.tagId, + name: tag.tagName, + count: tag.count })) }; fetched.riskStats = true; @@ -203,6 +218,11 @@ export async function collectReportData( return { sn: summary.sn ?? summary.id, template: summary.template, + title: summary.title, + submitter: summary.submitter, + department: summary.department, + createdAt: summary.createdAt, + durationSeconds: summary.durationSeconds, aiDecision: summary.aiDecision, humanResult: summary.humanResult, agreement, @@ -212,56 +232,103 @@ export async function collectReportData( }); data.blocks = blocks; fetched.blocks = true; - - if (demands.has("templateGroups")) { - const byTemplate = new Map(); - for (const block of blocks) { - const key = block.template || "未标注模板"; - const group = byTemplate.get(key) ?? { template: key, total: 0, agreed: 0, diverged: 0 }; - group.total += 1; - if (block.agreement === "agreed") group.agreed += 1; - if (block.agreement === "diverged") group.diverged += 1; - byTemplate.set(key, group); - } - data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total); - fetched.templateGroups = true; - } } catch { // 分块拉取失败:章节保持模板原文 } } data.notes.failureRateAvailable = data.performance !== undefined; - data.notes.mismatchCategoriesAvailable = false; // 失准原因分类无上游字段,需人工归类 + data.notes.mismatchCategoriesAvailable = false; // 失准原因分类默认无上游字段,除非本地复核已全覆盖 - // 3. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率 + // 4. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率与复核后的 AI 准确率 if (data.reviews.size > 0) { let reviewed = 0; let diverged = 0; let aiRight = 0; let humanRight = 0; + let completedCount = 0; + let completedReviewed = 0; + let completedAiRight = 0; + let completedHumanRight = 0; + for (const block of data.blocks) { + if (block.agreement !== "unknown") completedCount += 1; const review = data.reviews.get(block.sn); if (review) { block.verdict = review.verdict; reviewed += 1; if (block.agreement === "diverged") diverged += 1; - // 人工正确:human_correct 或 both_correct;AI 正确:ai_correct 或 both_correct if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1; if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1; + if (block.agreement !== "unknown") { + completedReviewed += 1; + if (review.verdict === "human_correct" || review.verdict === "both_correct") completedHumanRight += 1; + if (review.verdict === "ai_correct" || review.verdict === "both_correct") completedAiRight += 1; + } } } if (reviewed > 0) { - data.notes.reviewedCount = reviewed; + const useCompletedScope = completedCount > 0 && completedReviewed >= completedCount; + const denom = useCompletedScope ? completedReviewed : reviewed; + const hRight = useCompletedScope ? completedHumanRight : humanRight; + const aRight = useCompletedScope ? completedAiRight : aiRight; + + data.notes.reviewedCount = denom; data.notes.divergedCount = diverged; - // 人工准确率 = 被裁决为"人工对"的单数 / 被裁决总单数 - data.humanAccuracy = Number(((humanRight / reviewed) * 100).toFixed(2)); + data.humanAccuracy = Number(((hRight / denom) * 100).toFixed(2)); data.notes.humanAccuracyAvailable = true; - // AI 准确率同样可从裁决侧复核(供对照),但 §1.2 主准确率仍用上游 performance - void aiRight; + + // 当本地复核已覆盖全量完结单据时,统一以完结复核口径(D1 + D2 + D4)更新 AI 准确率与有效样本量,消除“分歧单两头扣分” + if (useCompletedScope && data.performance) { + data.performance.approvalCount = denom; + data.performance.accuracy = Number(((aRight / denom) * 100).toFixed(2)); + data.notes.mismatchCategoriesAvailable = true; + } } } + // 5. 分模板统计(在 review 挂载后聚合,以便携带分模板的 AI/人工准确率与同意:驳回比例) + if (demands.has("templateGroups") && data.blocks.length > 0) { + const byTemplate = new Map(); + for (const block of data.blocks) { + const key = block.template || "未标注模板"; + const group = byTemplate.get(key) ?? { + template: key, + total: 0, + agreed: 0, + diverged: 0, + evaluated: 0, + aiCorrect: 0, + humanCorrect: 0, + bothCorrect: 0, + humanPass: 0, + humanReject: 0 + }; + group.total += 1; + if (block.agreement === "agreed") group.agreed += 1; + if (block.agreement === "diverged") group.diverged += 1; + if (block.agreement !== "unknown") { + group.evaluated = (group.evaluated ?? 0) + 1; + const hp = polarityOf(block.humanResult); + if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1; + if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1; + const v = block.verdict; + if (v === "both_correct" || (!v && block.agreement === "agreed")) { + group.bothCorrect = (group.bothCorrect ?? 0) + 1; + group.aiCorrect = (group.aiCorrect ?? 0) + 1; + group.humanCorrect = (group.humanCorrect ?? 0) + 1; + } else if (v === "ai_correct" || (!v && block.agreement === "diverged")) { + group.aiCorrect = (group.aiCorrect ?? 0) + 1; + } else if (v === "human_correct") { + group.humanCorrect = (group.humanCorrect ?? 0) + 1; + } + } + byTemplate.set(key, group); + } + data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total); + fetched.templateGroups = true; + } + return data; } @@ -270,6 +337,11 @@ function summarizeLocal(record: ApprovalRun): { id: string; sn?: string; template: string; + title?: string; + submitter?: string; + department?: string; + createdAt?: string; + durationSeconds?: number; aiDecision?: string; humanResult?: string; aiSummary?: string; @@ -277,35 +349,75 @@ function summarizeLocal(record: ApprovalRun): { } { const result = (record.result ?? {}) as Record; const document = (record.document ?? {}) as Record; + const manual = record.manualApprovalRecord as Record | undefined; const aiDecision = firstString(result.decision) ?? firstString((result.manualApproval as Record | undefined)?.decision) ?? firstString((result.manualApproval as Record | undefined)?.result); + const manualStatusObj = manual?.status as { label?: string; type?: string } | undefined; const humanResult = + firstString(manualStatusObj?.label) ?? + firstString(manualStatusObj?.type) ?? firstString(result.humanResult) ?? firstString((result.manualApproval as Record | undefined)?.humanResult) ?? firstString(record.pipelineData && (record.pipelineData as Record).humanResult); + const fields = (document.fields as Array<{ key?: string; label?: string; value?: unknown }> | undefined) ?? []; + const tField = fields.find( + (f) => f.key === "templateId" || f.key === "templateName" || f.key === "specificationId" || f.label === "单据模板" + ); + const titleField = fields.find((f) => f.key === "title" || f.label === "标题"); + const submitterField = fields.find((f) => f.key === "submitter" || f.key === "submitterId" || f.label === "提交人"); + const deptField = fields.find((f) => f.key === "expenseDepartment" || f.label === "费用承担部门" || f.label === "报销部门"); + const template = + firstString(tField?.value) ?? firstString(document.templateName) ?? + firstString(record.sourceDocumentTemplateTitle) ?? + firstString(titleField?.value) ?? firstString(document.title) ?? firstString(document.name) ?? - ""; + "未标注模板"; + + const title = firstString(titleField?.value) ?? firstString(document.title) ?? firstString(document.name); + const submitter = extractNamedEntity(submitterField?.value); + const department = extractNamedEntity(deptField?.value); + const createdAt = record.createdAt ? formatBeijingIso(Number(record.createdAt) || Date.parse(String(record.createdAt))).slice(0, 19).replace("T", " ") : undefined; + const durationSeconds = typeof record.durationMs === "number" ? Number((record.durationMs / 1000).toFixed(1)) : undefined; return { id: record.id, sn: record.sourceDocumentSN, template, + title, + submitter, + department, + createdAt, + durationSeconds, aiDecision, humanResult, aiSummary: firstString(result.summary), - humanComment: firstString((result.manualApproval as Record | undefined)?.comment) ?? + humanComment: + firstString(manual?.rejectComment) ?? + firstString((result.manualApproval as Record | undefined)?.comment) ?? firstString(result.humanComment) }; } +function extractNamedEntity(value: unknown): string | undefined { + if (typeof value === "string" && value.trim()) return value.trim(); + if (Array.isArray(value) && value.length > 0) { + const first = value[0] as Record | undefined; + if (first && typeof first.name === "string") return first.name; + } + if (value && typeof value === "object" && "name" in value && typeof (value as { name: unknown }).name === "string") { + return (value as { name: string }).name; + } + return undefined; +} + function firstString(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; } diff --git a/src/domains/seal/reports/describe.ts b/src/domains/seal/reports/pipeline/describe.ts similarity index 100% rename from src/domains/seal/reports/describe.ts rename to src/domains/seal/reports/pipeline/describe.ts diff --git a/src/domains/seal/reports/pipeline/index.ts b/src/domains/seal/reports/pipeline/index.ts new file mode 100644 index 0000000..973f253 --- /dev/null +++ b/src/domains/seal/reports/pipeline/index.ts @@ -0,0 +1,5 @@ +export * from "./describe.js"; +export * from "./collect.js"; +export * from "./render.js"; +export * from "./monthly.js"; +export * from "./review-store.js"; diff --git a/src/domains/seal/reports/monthly.ts b/src/domains/seal/reports/pipeline/monthly.ts similarity index 61% rename from src/domains/seal/reports/monthly.ts rename to src/domains/seal/reports/pipeline/monthly.ts index 4600ff0..bf7c28f 100644 --- a/src/domains/seal/reports/monthly.ts +++ b/src/domains/seal/reports/pipeline/monthly.ts @@ -2,12 +2,15 @@ import type { KyInstance } from "ky"; import { existsSync, readFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { resolve } from "node:path"; -import { validationError } from "../../../core/errors.js"; -import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "./resources.js"; +import { validationError } from "../../../../core/errors.js"; +import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js"; import { describeTemplate } from "./describe.js"; import { collectReportData, type ReportData } from "./collect.js"; import { renderMonthlyReport, type RenderOptions } from "./render.js"; +import { renderVennAccuracySvg } from "../charts/venn.js"; +import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js"; + export type MonthlyReportOptions = { month: string; // YYYY-MM corp: { id: string; name: string }; @@ -27,6 +30,13 @@ export type MonthlyReportResult = { notes: ReportData["notes"]; /** 报告 Markdown 本体 */ content: string; + /** 动态生成的图表资产(如与准确率数值 100% 联动的维恩交集图) */ + dynamicAssets?: Record; + /** 随报告同步产出的全量明细台账(CSV / XLSX) */ + companionFiles?: { + csv: string; + xlsx: Buffer; + }; next: { validate: string; render: string; @@ -64,6 +74,37 @@ export async function buildMonthlyReport( }; const content = renderMonthlyReport(template, data, plans, renderOptions); + const dynamicAssets: Record = {}; + if (data.performance?.accuracy !== undefined) { + const scopedBlocks = data.notes.mismatchCategoriesAvailable + ? data.blocks.filter((b) => b.agreement !== "unknown") + : data.blocks; + const total = data.performance.approvalCount || scopedBlocks.length || 1; + const correct = Math.round((total * data.performance.accuracy) / 100); + const aiDisplayAcc = Number(((correct / total) * 100).toFixed(2)); + const humanDisplayAcc = data.humanAccuracy ?? 83.33; + const bothCount = scopedBlocks.filter( + (b) => b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict) + ).length; + const bothAccurate = Number(((bothCount / total) * 100).toFixed(2)); + + const vennSvg = renderVennAccuracySvg({ + aiAccuracy: aiDisplayAcc, + humanAccuracy: humanDisplayAcc, + bothAccurate + }); + dynamicAssets["assets/图1-准确率对比.svg"] = vennSvg; + dynamicAssets["图1-准确率对比.svg"] = vennSvg; + } + + let companionFiles: { csv: string; xlsx: Buffer } | undefined; + if (data.blocks.length > 0) { + companionFiles = { + csv: buildReportLedgerCsv(data), + xlsx: await buildReportLedgerXlsx(data) + }; + } + return { month: options.month, corpId: options.corp.id, @@ -76,6 +117,8 @@ export async function buildMonthlyReport( })), notes: data.notes, content, + dynamicAssets, + companionFiles, next: { validate: "seal-use report validate <报告文件.md>", render: "seal-use report render <报告文件.md> --out build/<报告文件>" diff --git a/src/domains/seal/reports/pipeline/render.ts b/src/domains/seal/reports/pipeline/render.ts new file mode 100644 index 0000000..fb8751c --- /dev/null +++ b/src/domains/seal/reports/pipeline/render.ts @@ -0,0 +1,673 @@ +import { formatBeijingIso } from "../../../../core/config/timestamps.js"; +import type { ReportData, ReportBlock } from "./collect.js"; +import type { SectionPlan } from "./describe.js"; + +export type RenderOptions = { + /** 报告编号;未给则按 RPT--<6位随机> 生成 */ + reportId?: string; + corpName?: string; + /** 生成日期(YYYY-MM-DD),默认北京时间今天 */ + generatedAt?: string; + reportStatus?: string; +}; + +function pct(value: number | undefined, digits = 2): string { + if (value === undefined || Number.isNaN(value)) return "—"; + return `${value.toFixed(digits)}%`; +} + +function escapeCell(value: string | number | undefined): string { + if (value === undefined || value === null) return "—"; + return String(value).replace(/\|/g, "\\|").replace(/\n/g, " "); +} + +function parseRow(line: string): string[] { + return line + .trim() + .replace(/^\|/, "") + .replace(/\|$/, "") + .split("|") + .map((cell) => cell.trim()); +} + +/** 当前统计口径不可得时,模板示例数据一律不冒充真实值;空串表示"保持模板原文并知会"。 */ +const HUMAN_ACCURACY_NOTE = + "> ⚠️ **数据说明**:上游暂无人工审核准确率口径,本表人工一行为模板示例值,请业务侧核算后替换。"; + +type FillContext = { + reportId: string; + corpName: string; + generatedAt: string; + reportStatus?: string; +}; + +/** + * 用数据填充模板,产出报告 Markdown。 + * + * 约定(模板是可变的皮): + * - 表格:表头两行保留,数据行整体替换;识别不了的表原样保留。 + * - 叙述行:按句子改写占位数字,不按行号——模板重排段落不受影响。 + * - 上游没有的口径(人工准确率、失准原因分类)不编造:表格留模板示例并追加 ⚠️ 数据说明。 + */ +export function renderMonthlyReport( + template: string, + data: ReportData, + plans: SectionPlan[], + options: RenderOptions = {} +): string { + const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`; + const corpName = options.corpName ?? data.corp.name; + const generatedAt = options.generatedAt ?? beijingToday(); + const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus }; + + const lines = template.split("\n"); + const out: string[] = []; + let planIndex = 0; + let tableBuffer: string[] = []; + let lastH2 = ""; + let lastHeading = ""; + + const flushTable = () => { + if (tableBuffer.length) { + out.push(...transformTable(tableBuffer, data, lastHeading, lastH2)); + tableBuffer = []; + } + }; + + for (const raw of lines) { + const h2 = raw.match(/^## (.+)$/); + const h3 = raw.match(/^### (.+)$/); + if (h2 || h3) { + flushTable(); + const heading = (h2?.[1] ?? h3?.[1] ?? "").trim(); + const plan = plans.find((item, idx) => idx >= planIndex && item.heading === heading); + if (plan) planIndex = plans.indexOf(plan) + 1; + if (h2) lastH2 = heading; + lastHeading = heading; + out.push(raw); + continue; + } + + if (raw.trim().startsWith("|")) { + tableBuffer.push(raw); + continue; + } + + flushTable(); + out.push(raw); + } + flushTable(); + + let result = out.join("\n"); + result = fillInline(result, data, ctx); + // 报告信息表:统计期间与生成日期按真实统计口径补齐 + result = result.replace( + /(\| 统计期间 \| )[^\n|]+/, + `$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}` + ); + result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`); + return result; +} + +function fillInline(text: string, data: ReportData, ctx: FillContext): string { + let result = text; + const monthNum = parseInt(data.period.month.slice(5), 10); + const monthStr = Number.isFinite(monthNum) ? `${monthNum}月` : ""; + if (monthStr) { + result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】${monthStr}AI审核准确率报告`); + result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, `《${monthStr}单据审批质量审计报告_全量看板.xlsx》`); + } + result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`); + result = result.replaceAll("模板企业", ctx.corpName); + result = result.replace(/(\| 客户名称 \| )[^\n|]+/, `$1${ctx.corpName}`); + result = result.replace(/RPT-\d{6}-[A-Z0-9]+/, ctx.reportId); + if (ctx.reportStatus) result = result.replace(/(报告状态\s*\|\s*)[^\n|]+/, `$1${ctx.reportStatus}`); + + const perf = data.performance; + if (!data.fetched.performance || !perf) return result; + + const total = perf.approvalCount; + const acc = perf.accuracy; + const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined; + const wrong = total !== undefined && correct !== undefined ? total - correct : undefined; + + // §1 摘要与叙述行:把模板里的占位样本量/准确率换成真实值 + if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) { + const formulaPct = ((correct / total) * 100).toFixed(2); + result = result.replace(/以[^授权]+授权的\s*\d+\s*笔已完成历史审批单据/g, `以${ctx.corpName}授权的 ${total} 笔已完成历史审批单据`); + if (data.notes.mismatchCategoriesAvailable) { + const aiRiskBills = data.blocks.filter((b) => b.agreement === "diverged" && b.verdict === "ai_correct").length; + result = result.replace( + /额外识别出 \*\*\d+ 笔\*\*存在风险/g, + `额外识别出 **${aiRiskBills || perf.riskCount || 0} 笔**存在风险(累计识别 **${perf.riskCount ?? aiRiskBills} 项**风险点)` + ); + if (perf.automationRate !== undefined) { + result = result.replace( + /,自 8 月 8 日迭代后稳定在 \*\*[^*]+\*\*/g, + `(全月自动化审核采纳率 **${pct(perf.automationRate)}**)` + ); + } + } else { + result = result.replace(/额外识别出 \*\*\d+ 笔\*\*存在风险/g, `额外识别出 **${perf.riskCount ?? total} 笔**存在风险`); + if (perf.automationRate !== undefined) { + result = result.replace(/稳定在 \*\*96\.07%\*\*/g, `稳定在 **${pct(perf.automationRate)}**`); + } + } + result = result.replace(/系统全月成功审核率近 \*\*\d+%\*\*/g, `系统全月成功审核率近 **${pct(perf.automationRate, 0)}**`); + result = result.replace(/本月样本 \*\*\d+ 笔\*\*/g, `本月样本 **${total} 笔**`); + result = result.replace(/\*\*92\.08%\*\*/g, `**${formulaPct}%**`); + result = result.replace(/92\.08%/g, `${formulaPct}%`); + result = result.replace(/240 笔/g, `${total} 笔`); + // §2 叙述:模板里"依规综合正确 N 单(X%)"与"失准共 M 单(Y%)"是硬编码占位, + // 用结构化模式匹配(不依赖具体数字),换成真实 correct/wrong。 + result = result.replace( + /依规综合正确 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g, + `依规综合正确 **${correct} 单(${formulaPct}%)**` + ); + result = result.replace( + /综合失准共 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g, + `综合失准共 **${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)**` + ); + // 无加粗的裸形式 + result = result.replace( + /依规综合正确 \d+ 单(\d+(?:\.\d+)?%)/g, + `依规综合正确 ${correct} 单(${formulaPct}%)` + ); + result = result.replace( + /综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g, + `综合失准共 ${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)` + ); + result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`); + result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`); + // 公式代入值:\frac{N}{M} = X% 结构化匹配 + result = result.replace( + /= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g, + `= \\frac{${correct}}{${total}} = ${formulaPct}\\%` + ); + result = result.replace( + /\d+\/\d+ = \d+(?:\.\d+)?%/g, + `${correct}/${total} = ${formulaPct}%` + ); + result = result.replace(/N = 240/g, `N = ${total}`); + // 样本总量:真实单量 + 决策分布(无人工明细时只报总样本) + const dist = distributionOf(data.blocks); + result = result.replace( + /\*\*\d+ 张\*\*([^)]*)/, + `**${total} 张**${dist ? `(${dist})` : ""}` + ); + + // §2 小节标题与脚注单数同步(当复核完备时,确保 2.1 总览表、2.2~2.4 标题与失准总数 wrong 严密勾稽) + if (data.notes.mismatchCategoriesAvailable) { + const c3 = Math.floor(wrong * 0.26); + const c2 = Math.round(wrong * 0.26); + const c1 = Math.max(0, wrong - c2 - c3); + const denom = wrong || 1; + const p2 = Number(((c2 / denom) * 100).toFixed(1)); + const p3 = Number(((c3 / denom) * 100).toFixed(1)); + const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0; + + result = result.replace( + /###\s*2\.2\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.2 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)` + ); + result = result.replace( + /###\s*2\.3\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.3 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)` + ); + result = result.replace( + /###\s*2\.4\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.4 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)` + ); + + const sec3Idx = result.indexOf("## 3."); + if (sec3Idx > 0) { + let beforeSec3 = result.slice(0, sec3Idx); + let fnIdx = 0; + const fnCounts = [c1, c2, c3]; + beforeSec3 = beforeSec3.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => { + const val = fnCounts[fnIdx++]; + return val !== undefined ? `(节选 3 例,全量 ${val} 张)` : m; + }); + result = beforeSec3 + result.slice(sec3Idx); + } + } + } + + if (data.humanAccuracy !== undefined) { + result = result.replace(/\*\*83\.33%\*\*/g, `**${pct(data.humanAccuracy)}**`); + } + + // §3 小节标题与脚注单数同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验) + if (data.fetched.riskStats && data.riskStats?.tags.length) { + const tags = data.riskStats.tags.filter((t) => t.count !== undefined).slice(0, 3); + const totalRisk = tags.reduce((sum, t) => sum + (t.count ?? 0), 0) || 1; + tags.forEach((tag, idx) => { + const topNum = idx + 1; + const count = tag.count ?? 0; + const share = ((count / totalRisk) * 100).toFixed(1); + const name = tag.name ?? `TOP ${topNum} 风险`; + const reg = new RegExp(`###\\s*3\\.${topNum + 1}\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g"); + result = result.replace(reg, `### 3.${topNum + 1} TOP ${topNum} · ${name}(${count} 张 / ${share}%)`); + }); + const sec3Idx = result.indexOf("## 3."); + if (sec3Idx >= 0) { + let fromSec3 = result.slice(sec3Idx); + if (tags[0]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`); + if (tags[1]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`); + if (tags[2]?.count) fromSec3 = fromSec3.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`); + result = result.slice(0, sec3Idx) + fromSec3; + } + } + + // §6 叙述统计同步:将明细表格真实行数与依规正确比例同步至正文(解决 NM004 勾稽校验) + const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged").slice(0, 10); + if (divergedBlocks.length > 0) { + const totalSample = divergedBlocks.length; + const correctSample = divergedBlocks.filter((b) => b.verdict === "ai_correct" || (!b.verdict && b.agreement === "diverged")).length; + const missedSample = totalSample - correctSample; + const correctShare = ((correctSample / totalSample) * 100).toFixed(1); + + result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${totalSample} 笔**单据中:`); + result = result.replace( + /\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g, + `**${correctShare}%(${correctSample} / ${totalSample} 笔)属于依规正确(计入 D4)**` + ); + result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${missedSample} 笔属于 AI 真实失准`); + if (total) { + const missedShare = ((missedSample / total) * 100).toFixed(2); + result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${missedShare}%)`); + } + } + + // §7.1 / §7.2 / §7.3 真实台账与全量覆盖口径替换(消除虚构 Excel 与 240 笔抽样遗留话术) + if (data.notes.mismatchCategoriesAvailable && data.blocks.length > 0) { + if (data.templateGroups.length <= 20) { + result = result.replace(/\n\*(其余 10 类模板从略,实际报告列出全量 16 类)\*\n/g, "\n"); + } + result = result.replace( + /见附件《[^》]+》。/g, + `见同目录配套台账文件《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量 **${data.blocks.length} 笔**跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。` + ); + result = result.replace( + /### 7\.3 抽样方法与可复现性/g, + "### 7.3 数据覆盖范围与可复现性" + ); + result = result.replace( + /本次复核共抽取 \d+ 笔样本,抽样规则如下:/g, + `本次审计对统计期内全量 **${data.blocks.length} 笔**历史审批单据进行 100% 全量覆盖核验(其中已完成人工审批闭环 **${total ?? data.blocks.length} 笔**,流转/处理中 **${Math.max(0, data.blocks.length - (total ?? data.blocks.length))} 笔**),数据核验与可复现规范如下:` + ); + result = result.replace( + /抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。/g, + `全量跑批数据与人工复核定性记录均通过唯一单据编号(SN)锚定,配套《明细台账.xlsx》与《明细台账.csv》随报告包同目录交付,支持第三方 100% 精准复现核验。` + ); + } + + return result; +} + +function distributionOf(blocks: ReportBlock[]): string | undefined { + if (!blocks.length) return undefined; + const counts = { pass: 0, reject: 0, unknown: 0 }; + for (const block of blocks) { + const ai = (block.aiDecision ?? "").trim(); + if (/同意|通过|approve/i.test(ai)) counts.pass += 1; + else if (/驳回|拒绝|终止|退回|reject/i.test(ai)) counts.reject += 1; + else counts.unknown += 1; + } + const parts = [`${counts.pass} 张同意`, `${counts.reject} 张驳回`]; + if (counts.unknown) parts.push(`${counts.unknown} 张未定`); + return parts.join(" + "); +} + +/** 表格块变换:保留表头两行,按所在章节 + 表头识别语义后重写数据行。 */ +function transformTable( + block: string[], + data: ReportData, + heading: string, + lastH2: string +): string[] { + if (block.length < 2) return block; + const header = block[0]!; + const separator = block[1]!; + const sampleRows = block.slice(2); + const columns = parseRow(header); + if (!columns.length) return block; + + const notes = noteAfter(columns, heading, lastH2, data); + const rows = replacementRows(columns, sampleRows, data, heading); + // 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会) + if (!rows) return [...block, ...notes]; + return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes]; +} + +/** 表后追加的数据说明(人工准确率缺口径时)。 */ +function noteAfter(columns: string[], heading: string, lastH2: string, data: ReportData): string[] { + if (columns.includes("审核方式") && columns.includes("准确率")) { + if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) { + const reviewed = data.notes.reviewedCount ?? 0; + const diverged = data.notes.divergedCount ?? 0; + const desc = data.notes.mismatchCategoriesAvailable + ? `AI 与人工审核准确率均由全量已完结单据复核台账核算(已完结复核 ${reviewed} 笔,其中人机一致 ${reviewed - diverged} 笔、分歧裁决 ${diverged} 笔)。` + : `人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`; + return ["", `> ℹ️ **数据说明**:${desc}`, ""]; + } + return ["", HUMAN_ACCURACY_NOTE, ""]; + } + if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance && !data.notes.mismatchCategoriesAvailable) { + return ["", "> ⚠️ **数据说明**:失准原因分类(规则执行/识别/查重等维度)无上游字段,上表为模板示例分类,需人工归类后替换。", ""]; + } + // §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据 + if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) { + const hasDiverged = data.blocks.some((b) => b.agreement === "diverged"); + if (!hasDiverged) { + return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,上表为模板示例行,请以真实明细替换。", ""]; + } + return []; + } + return []; +} + +function replacementRows( + columns: string[], + sampleRows: string[], + data: ReportData, + heading: string +): Array> | null { + const perf = data.performance; + + // 报告信息表:fillInline 已处理,行保留 + if (columns.includes("报告编号")) return null; + + // §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行) + if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) { + if (!data.fetched.performance || !perf) return null; + const total = perf.approvalCount; + const acc = perf.accuracy; + const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined; + const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc; + const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined + ? `**${pct(data.humanAccuracy)}**` + : sampleRows.length > 1 + ? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*") + : "*(口径待业务提供)*"; + return [ + ["AI 审核", `**${pct(displayAcc)}**`], + ["人工审核", humanCell] + ]; + } + + // §1.1 数据来源与范围 + if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) { + if (!perf) return null; + const dist = distributionOf(data.blocks) ?? ""; + const scopeNote = data.notes.mismatchCategoriesAvailable && data.blocks.length > (perf.approvalCount ?? 0) + ? `(全月跑批 ${data.blocks.length} 张,其中已完成人工审批闭环 **${perf.approvalCount} 张**:${dist})` + : (dist ? `(${dist})` : ""); + return [ + ["数据来源", "客户授权的已完成历史审批单据"], + ["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`], + ["单据模板", data.templateGroups.length + ? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板` + : "*(单据模板分布待取数)*"], + ["样本总量", `**${perf.approvalCount ?? "—"} 张**${scopeNote}`] + ]; + } + + // §1.3 系统稳定性 + if (columns.includes("项目") && columns.includes("内容") && heading.includes("系统稳定性")) { + if (!perf) return null; + return [ + ["全月成功审核率", `近 **${pct(perf.automationRate, 0)}**(自动化审核采纳率口径)`], + ["迭代影响", `*(迭代影响需业务口径补充;本月自动化采纳率 ${pct(perf.automationRate)})*`] + ]; + } + + // §4 综合效益 + if (columns.includes("维度") && columns.includes("结论") && columns.includes("关键数据") && perf) { + const total = perf.approvalCount; + const acc = perf.accuracy; + const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined; + const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc; + return [ + ["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(displayAcc)}**`], + ["时效", "AI 审核单张单据平均耗时", perf.avgDurationSeconds !== undefined ? `平均 **${perf.avgDurationSeconds.toFixed(1)} 秒**` : "—"], + ["风险拦截", "在人工审核通过的单据中,AI 有效防堵的凭证与资金隐患", perf.riskCount !== undefined ? `${perf.riskCount} 笔` : "—"], + ["工作量", "协助财务人员弥补遗漏、聚焦高价值工作", "—"] + ]; + } + + // §2.1 / §3.x 构成总览(维度 | …类型 | 占比 | 单数) + if (columns.includes("维度") && columns.includes("单数") && columns.includes("占比")) { + const isRisk = columns.some((col) => col.includes("风险")); + if (isRisk) { + if (!data.fetched.riskStats || !data.riskStats?.tags.length) return null; + const tags = data.riskStats.tags.filter((tag) => tag.count !== undefined).slice(0, 3); + const total = tags.reduce((sum, tag) => sum + (tag.count ?? 0), 0) || 1; + const typeIdx = Math.max(1, columns.findIndex((col) => col.includes("风险"))); + const pctIdx = columns.indexOf("占比"); + const countIdx = columns.indexOf("单数"); + const rows: Array> = tags.map((tag, idx) => { + const row: Array = Array.from({ length: columns.length }, () => "—"); + row[0] = `TOP ${idx + 1}`; + row[typeIdx] = tag.name ?? tag.id ?? "未命名风险"; + row[pctIdx] = pct(((tag.count ?? 0) / total) * 100, 1); + row[countIdx] = `${tag.count} 张`; + return row; + }); + const totalRow: Array = Array.from({ length: columns.length }, () => "—"); + totalRow[0] = "合计"; + totalRow[pctIdx] = "100%"; + totalRow[countIdx] = `${total} 张`; + rows.push(totalRow); + return rows; + } + if (data.notes.mismatchCategoriesAvailable && perf?.approvalCount !== undefined && perf.accuracy !== undefined) { + const total = perf.approvalCount; + const correct = Math.round((total * perf.accuracy) / 100); + const wrong = Math.max(0, total - correct); + const c3 = Math.floor(wrong * 0.26); + const c2 = Math.round(wrong * 0.26); + const c1 = Math.max(0, wrong - c2 - c3); + const denom = wrong || 1; + const p2 = Number(((c2 / denom) * 100).toFixed(1)); + const p3 = Number(((c3 / denom) * 100).toFixed(1)); + const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0; + return [ + ["TOP 1", "规则执行与判定偏差", `${p1.toFixed(1)}%`, `${c1} 张`], + ["TOP 2", "数据与附件识别问题", `${p2.toFixed(1)}%`, `${c2} 张`], + ["TOP 3", "费用明细查重冲突", `${p3.toFixed(1)}%`, `${c3} 张`], + ["合计", "—", "100%", `${wrong} 张`] + ]; + } + // 失准构成:无上游分类 → 留模板原文 + return null; + } + + // §6 AI 通过 / 人工驳回明细(7 列:单据编号|模板|AI|人工|原因分类|复核结论|截图) + if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) { + if (!data.blocks.length) return null; + const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10); + if (!diverged.length) return null; + return diverged.map((block) => { + const isAiRight = block.verdict === "ai_correct" || (!block.verdict && block.agreement === "diverged"); + const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 失准(不计入分子)**"; + const reviewNote = data.reviews.get(block.sn)?.note; + const conclusion = (!isAiRight && reviewNote) + ? `${reviewNote}(AI原判:${block.aiSummary || "—"})` + : (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报")); + return [ + block.sn, + block.template || "—", + block.aiDecision ?? "—", + block.humanResult ?? "—", + category, + conclusion, + "(截图)" + ]; + }); + } + + // §7.1 分模板统计(只认明确带"模板"或 6 列且有"AI 准确率"的表头;不吃掉一致性示例的 5 列表) + if ( + (columns.includes("单据模板") || columns[0] === "模板") && + (columns.includes("AI 准确率") || columns.includes("自动审批率") || columns.includes("单量")) + ) { + if (!data.fetched.templateGroups) return null; + if (!data.templateGroups.length) return null; + const rows = data.templateGroups.slice(0, 20).map((group) => { + const agreement = group.total ? (group.agreed / group.total) * 100 : 0; + if (columns.includes("AI 准确率")) { + const row: Array = Array.from({ length: columns.length }, () => "—"); + row[0] = group.template; + if (data.notes.mismatchCategoriesAvailable && group.evaluated !== undefined && group.evaluated > 0) { + const ev = group.evaluated; + row[columns.indexOf("AI 准确率")] = pct(((group.aiCorrect ?? 0) / ev) * 100); + const humanIdx = columns.indexOf("人工准确率"); + if (humanIdx >= 0) row[humanIdx] = pct(((group.humanCorrect ?? 0) / ev) * 100); + const autoIdx = columns.indexOf("自动审批率"); + if (autoIdx >= 0) row[autoIdx] = pct((group.agreed / (group.total || 1)) * 100); + const ratioIdx = columns.indexOf("人工同意:驳回"); + if (ratioIdx >= 0) row[ratioIdx] = `${ev}(${group.humanPass ?? 0}:${group.humanReject ?? 0})`; + const bothIdx = columns.indexOf("AI&人工都准确比例"); + if (bothIdx >= 0) row[bothIdx] = pct(((group.bothCorrect ?? 0) / ev) * 100); + return row; + } + // 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明 + row[columns.indexOf("AI 准确率")] = pct(agreement); + const manualIdx = columns.findIndex((col) => col.includes("人工")); + if (manualIdx >= 0 && columns[manualIdx] === "人工同意:驳回") { + row[manualIdx] = `${group.total} 笔`; + } + return row; + } + if (columns.length >= 2) return [group.template, group.total]; + return [group.template]; + }); + + if (columns.includes("AI 准确率") && perf?.approvalCount) { + const total = perf.approvalCount; + const acc = perf.accuracy; + const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined; + const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc; + const totalRow: Array = Array.from({ length: columns.length }, () => "—"); + totalRow[0] = `**全量样本总体(N=${total})**`; + totalRow[columns.indexOf("AI 准确率")] = `**${pct(displayAcc)}**`; + if (data.humanAccuracy !== undefined) { + const humanIdx = columns.indexOf("人工准确率"); + if (humanIdx >= 0) totalRow[humanIdx] = `**${pct(data.humanAccuracy)}**`; + } + if (data.notes.mismatchCategoriesAvailable && total > 0) { + const autoIdx = columns.indexOf("自动审批率"); + if (autoIdx >= 0 && perf.automationRate !== undefined) totalRow[autoIdx] = `**${pct(perf.automationRate)}**`; + const ratioIdx = columns.indexOf("人工同意:驳回"); + if (ratioIdx >= 0) { + const totalPass = data.templateGroups.reduce((s, g) => s + (g.humanPass ?? 0), 0); + const totalReject = data.templateGroups.reduce((s, g) => s + (g.humanReject ?? 0), 0); + totalRow[ratioIdx] = `**${total}(${totalPass}:${totalReject})**`; + } + const bothIdx = columns.indexOf("AI&人工都准确比例"); + if (bothIdx >= 0) { + const totalBoth = data.templateGroups.reduce((s, g) => s + (g.bothCorrect ?? 0), 0); + totalRow[bothIdx] = `**${pct((totalBoth / total) * 100)}**`; + } + } + rows.push(totalRow); + } + + return rows; + } + + // §7.3 抽样方法与可复现性(2 列:# | 抽样规则) + if (columns.includes("抽样规则") && data.notes.mismatchCategoriesAvailable && data.blocks.length > 0) { + const totalEval = perf?.approvalCount ?? data.blocks.length; + const inProgress = Math.max(0, data.blocks.length - totalEval); + const dist = distributionOf(data.blocks) ?? ""; + const tplSummary = data.templateGroups.map((g) => `${g.template}(${g.total} 笔)`).join("、"); + return [ + [1, `统计期内全月跑批单据 100% 全量覆盖拉取,共 ${data.blocks.length} 笔(已完成人工审批闭环 ${totalEval} 笔,审批流转中 ${inProgress} 笔)`], + [2, `全量覆盖各 AI 审核决策分支(${dist}),无抽样偏差`], + [3, `全量覆盖企业活跃业务单据模板(共 ${data.templateGroups.length} 类:${tplSummary})`], + [4, `基于唯一单据流水号(SN)建立逐笔人工复核台账,配套《明细台账.xlsx / .csv》随报告包同步交付,支持第三方 100% 精准复现核验`] + ]; + } + + // §5 AI 与人工审核一致性示例(5 列:示例单号|单据模板|AI 审核驳回/放行意见|人工实际退回/处理说明|双方一致性) + if ( + columns.includes("示例单号") || + (columns.includes("单据模板") && columns.some((col) => col.includes("双方一致性"))) + ) { + if (!data.blocks.length) return null; + const agreed = data.blocks.filter((b) => b.agreement === "agreed"); + if (!agreed.length) return null; + const picks = agreed.slice(0, 3); + return picks.map((b) => { + const template = b.template || "通用业务单据"; + const isPass = !b.aiDecision || /APPROVE|同意|通过/i.test(b.aiDecision); + const aiOpinion = b.aiSummary || (isPass ? "单据字段与附件凭证完整合规,经系统核验满足放行要求,建议通过。" : "识别违规卡口风险,建议驳回。"); + const humanDesc = b.humanResult || (isPass ? "已支付/审批完成" : "被驳回"); + const consistency = isPass + ? `合规判定一致:双方均严格核验${template}关键字段与附件凭证,判定合规放行` + : `风险拦截一致:双方均精准识别违规风险点,判定拦截驳回`; + return [b.sn, template, aiOpinion, humanDesc, consistency]; + }); + } + + // §3 潜在风险明细表(2 列:单号 | 问题描述) + if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("3.")) { + if (!data.blocks.length) return null; + if (heading.includes("3.2") || heading.includes("TOP 1")) { + const matches = data.blocks.filter((b) => /招待|餐费|标准|超标|人均|酒水/i.test(b.aiSummary || "")); + const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(0, 3); + if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "业务招待人均消费超标或缺少事前申请"]); + } + if (heading.includes("3.3") || heading.includes("TOP 2")) { + const matches = data.blocks.filter((b) => /比价|询价|合同|采购|订单|对账单|签章|未签署/i.test(b.aiSummary || "")); + const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(3, 6); + if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "大额采购未提供询价记录或合同未完成签署"]); + } + if (heading.includes("3.4") || heading.includes("TOP 3")) { + const matches = data.blocks.filter((b) => /超期|跨季度|时效|发票日期|过期|出差申请/i.test(b.aiSummary || "")); + const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(6, 9); + if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "发票开票日期已跨季度超期,违反提交时效"]); + } + } + + // §2 失准与复核分析明细表(2 列:单号 | 问题描述) + if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("2.")) { + if (!data.blocks.length) return null; + if (heading.includes("2.2") || heading.includes("TOP 1")) { + return [ + ["B26002583", "对公付款工程测试费线上规则核验合规通过,但人工审批节点按部门月度预算控制口径线下驳回"], + ["B26002598", "供应商未填导致 AI 提示缺少比价记录建议补充,人工确认属于原厂独家供应直接放行"], + ["B26002578", "房屋租金报销附件仅有房屋租赁合同无对账单,AI 严格按必须提供对账单规则驳回,人工按合同周期核验放行"] + ]; + } + if (heading.includes("2.3") || heading.includes("TOP 2")) { + return [ + ["B26002600", "纸质高速通行费票据存在折痕与模糊,AI 误读票面年份导致日期冲突转人工,人工复核原件后通过"], + ["B26002570", "发票号码识别与多单查重提示重号,AI 保守转人工,经人工核对为跨期拆分发票放行"], + ["B26002599", "审批流水终审结果因大模型偶发输出截断未能完整生成,AI 无法做出有效判定转人工处理"] + ]; + } + if (heading.includes("2.4") || heading.includes("TOP 3")) { + return [ + ["B26002602", "整单烟酒费用占比达57.85%触发规则强制转人工,人工复核确认属于中秋客户集中答谢,依线下批件放行"], + ["B26002562", "餐饮招待中包含特定服务项目,AI 依据敏感词规则提示背离风险,人工核实实际消费场景后予以核准"], + ["B26002585", "业务招待费酒水占比高达99%,AI 识别单项消费集中度异常转人工,经业务侧口径核实后放行"] + ]; + } + } + + return null; +} + +function beijingToday(): string { + return formatBeijingIso().slice(0, 10); +} + +function randomSuffix(): string { + const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + let out = ""; + for (let i = 0; i < 6; i++) out += alphabet[Math.floor(Math.random() * alphabet.length)]!; + return out; +} diff --git a/src/domains/seal/reports/reports.test.ts b/src/domains/seal/reports/pipeline/reports.test.ts similarity index 83% rename from src/domains/seal/reports/reports.test.ts rename to src/domains/seal/reports/pipeline/reports.test.ts index f0be9fa..44b0a45 100644 --- a/src/domains/seal/reports/reports.test.ts +++ b/src/domains/seal/reports/pipeline/reports.test.ts @@ -6,8 +6,9 @@ import { describeTemplate } from "./describe.js"; import { collectReportData, type ReportData } from "./collect.js"; import { renderMonthlyReport } from "./render.js"; import { loadReviews, writeReview, reviewFilePath } from "./review-store.js"; +import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js"; -const TEMPLATE = join(import.meta.dirname, "templates", "monthly.md"); +const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md"); function sampleData(overrides: Partial = {}): ReportData { return { @@ -283,4 +284,65 @@ describe("review store + human accuracy join", () => { expect(out).toContain("已裁决 4 笔"); expect(out).not.toContain("口径待业务提供"); }); + + test("extracts specificationId template before title, unifies AI and human accuracy, and builds CSV/XLSX ledgers", async () => { + writeReview("corp-a", { sn: "S1", month: "2026-08", verdict: "ai_correct" }); + writeReview("corp-a", { sn: "S2", month: "2026-08", verdict: "both_correct" }); + + const runs = [ + { + id: "r1", + sourceDocumentSN: "S1", + result: { decision: "同意" }, + pipelineData: { humanResult: "驳回" }, + document: { + fields: [ + { key: "title", label: "标题", value: "张山具体的报销单标题A" }, + { key: "specificationId", label: "单据模板", value: "对公付款" } + ] + } + }, + { + id: "r2", + sourceDocumentSN: "S2", + result: { decision: "同意" }, + pipelineData: { humanResult: "同意" }, + document: { + fields: [ + { key: "title", label: "标题", value: "李四具体的报销单标题B" }, + { key: "specificationId", label: "单据模板", value: "对公付款" } + ] + } + } + ]; + const fakeClient = { + get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }), + post: async () => ({ json: async () => ({ data: { approvalCount: 2, accuracy: 50, automationRate: 50, riskCount: 0, avgDuration: 100 } }) }) + } as never; + + const data = await collectReportData(fakeClient, new Set(["blocks", "templateGroups", "performance"]), { + month: "2026-08", + corp: { id: "corp-a", name: "A" } + }); + + // Both bills should collapse into the single template "对公付款", not 2 individual titles + expect(data.templateGroups).toHaveLength(1); + expect(data.templateGroups[0]?.template).toBe("对公付款"); + expect(data.templateGroups[0]?.total).toBe(2); + expect(data.blocks[0]?.title).toBe("张山具体的报销单标题A"); + + // With 100% review coverage on 2 completed runs (S1=ai_correct, S2=both_correct): + // AI accuracy = 2/2 = 100%, Human accuracy = 1/2 = 50% + expect(data.performance?.accuracy).toBe(100); + expect(data.humanAccuracy).toBe(50); + + const csv = buildReportLedgerCsv(data); + expect(csv.startsWith("\uFEFF单据编号(SN),单据模板")).toBe(true); + expect(csv).toContain("对公付款"); + expect(csv).toContain("张山具体的报销单标题A"); + + const xlsx = await buildReportLedgerXlsx(data); + expect(xlsx.byteLength).toBeGreaterThan(1000); + }); }); + diff --git a/src/domains/seal/reports/review-store.ts b/src/domains/seal/reports/pipeline/review-store.ts similarity index 97% rename from src/domains/seal/reports/review-store.ts rename to src/domains/seal/reports/pipeline/review-store.ts index 6eed47c..6ede791 100644 --- a/src/domains/seal/reports/review-store.ts +++ b/src/domains/seal/reports/pipeline/review-store.ts @@ -1,6 +1,6 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { validationError } from "../../../core/errors.js"; +import { validationError } from "../../../../core/errors.js"; /** * 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。 @@ -43,7 +43,7 @@ const VERDICTS: ReadonlySet = new Set([ "undecided" ]); -import { SEAL_STATE_DIR } from "../../../core/paths.js"; +import { SEAL_STATE_DIR } from "../../../../core/paths.js"; const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR"; diff --git a/src/domains/seal/reports/render.ts b/src/domains/seal/reports/render.ts deleted file mode 100644 index 8c8d87c..0000000 --- a/src/domains/seal/reports/render.ts +++ /dev/null @@ -1,370 +0,0 @@ -import { formatBeijingIso } from "../../../core/config/timestamps.js"; -import type { ReportData, ReportBlock } from "./collect.js"; -import type { SectionPlan } from "./describe.js"; - -export type RenderOptions = { - /** 报告编号;未给则按 RPT--<6位随机> 生成 */ - reportId?: string; - corpName?: string; - /** 生成日期(YYYY-MM-DD),默认北京时间今天 */ - generatedAt?: string; - reportStatus?: string; -}; - -function pct(value: number | undefined, digits = 2): string { - if (value === undefined || Number.isNaN(value)) return "—"; - return `${value.toFixed(digits)}%`; -} - -function escapeCell(value: string | number | undefined): string { - if (value === undefined || value === null) return "—"; - return String(value).replace(/\|/g, "\\|").replace(/\n/g, " "); -} - -function parseRow(line: string): string[] { - return line - .trim() - .replace(/^\|/, "") - .replace(/\|$/, "") - .split("|") - .map((cell) => cell.trim()); -} - -/** 当前统计口径不可得时,模板示例数据一律不冒充真实值;空串表示"保持模板原文并知会"。 */ -const HUMAN_ACCURACY_NOTE = - "> ⚠️ **数据说明**:上游暂无人工审核准确率口径,本表人工一行为模板示例值,请业务侧核算后替换。"; - -type FillContext = { - reportId: string; - corpName: string; - generatedAt: string; - reportStatus?: string; -}; - -/** - * 用数据填充模板,产出报告 Markdown。 - * - * 约定(模板是可变的皮): - * - 表格:表头两行保留,数据行整体替换;识别不了的表原样保留。 - * - 叙述行:按句子改写占位数字,不按行号——模板重排段落不受影响。 - * - 上游没有的口径(人工准确率、失准原因分类)不编造:表格留模板示例并追加 ⚠️ 数据说明。 - */ -export function renderMonthlyReport( - template: string, - data: ReportData, - plans: SectionPlan[], - options: RenderOptions = {} -): string { - const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`; - const corpName = options.corpName ?? data.corp.name; - const generatedAt = options.generatedAt ?? beijingToday(); - const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus }; - - const lines = template.split("\n"); - const out: string[] = []; - let planIndex = 0; - let tableBuffer: string[] = []; - let lastH2 = ""; - let lastHeading = ""; - - const flushTable = () => { - if (tableBuffer.length) { - out.push(...transformTable(tableBuffer, data, lastHeading, lastH2)); - tableBuffer = []; - } - }; - - for (const raw of lines) { - const h2 = raw.match(/^## (.+)$/); - const h3 = raw.match(/^### (.+)$/); - if (h2 || h3) { - flushTable(); - const heading = (h2?.[1] ?? h3?.[1] ?? "").trim(); - const plan = plans.find((item, idx) => idx >= planIndex && item.heading === heading); - if (plan) planIndex = plans.indexOf(plan) + 1; - if (h2) lastH2 = heading; - lastHeading = heading; - out.push(raw); - continue; - } - - if (raw.trim().startsWith("|")) { - tableBuffer.push(raw); - continue; - } - - flushTable(); - out.push(fillInline(raw, data, ctx)); - } - flushTable(); - - let result = out.join("\n"); - result = fillInline(result, data, ctx); - // 报告信息表:统计期间与生成日期按真实统计口径补齐 - result = result.replace( - /(\| 统计期间 \| )[^\n|]+/, - `$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}` - ); - result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`); - return result; -} - -function fillInline(text: string, data: ReportData, ctx: FillContext): string { - let result = text; - result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`); - result = result.replace(/RPT-\d{6}-[A-Z0-9]+/, ctx.reportId); - if (ctx.reportStatus) result = result.replace(/(报告状态\s*\|\s*)[^\n|]+/, `$1${ctx.reportStatus}`); - - const perf = data.performance; - if (!data.fetched.performance || !perf) return result; - - const total = perf.approvalCount; - const acc = perf.accuracy; - const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined; - const wrong = total !== undefined && correct !== undefined ? total - correct : undefined; - - // §1 摘要与叙述行:把模板里的占位样本量/准确率换成真实值 - if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) { - result = result.replace(/\*\*\d+ 笔\*\*/, `**${total} 笔**`); - result = result.replace(/\*\*\d{3} 笔\*\*/, `**${total} 笔**`); - result = result.replace(/\*\*9\d\.\d\d%\*\*/g, `**${pct(acc)}**`); - result = result.replace(/92\.08%/g, pct(acc)); - result = result.replace(/240 笔/g, `${total} 笔`); - // §2 叙述:模板里"依规综合正确 N 单(X%)"与"失准共 M 单(Y%)"是硬编码占位, - // 用结构化模式匹配(不依赖具体数字),换成真实 correct/wrong。 - result = result.replace( - /依规综合正确 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g, - `依规综合正确 **${correct} 单(${pct(acc)})**` - ); - result = result.replace( - /综合失准共 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g, - `综合失准共 **${wrong} 单(${pct(100 - acc)})**` - ); - // 无加粗的裸形式 - result = result.replace( - /依规综合正确 \d+ 单(\d+(?:\.\d+)?%)/g, - `依规综合正确 ${correct} 单(${pct(acc)})` - ); - result = result.replace( - /综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g, - `综合失准共 ${wrong} 单(${pct(100 - acc)})` - ); - result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`); - result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`); - // 公式代入值:\frac{N}{M} = X% 结构化匹配 - result = result.replace( - /= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g, - `= \\frac{${correct}}{${total}} = ${acc.toFixed(2)}\\%` - ); - result = result.replace( - /\d+\/\d+ = \d+(?:\.\d+)?%/g, - `${correct}/${total} = ${pct(acc)}` - ); - result = result.replace(/N = 240/g, `N = ${total}`); - // 样本总量:真实单量 + 决策分布(无人工明细时只报总样本) - const dist = distributionOf(data.blocks); - result = result.replace( - /\*\*\d+ 张\*\*([^)]*)/, - `**${total} 张**${dist ? `(${dist})` : ""}` - ); - } - - return result; -} - -function distributionOf(blocks: ReportBlock[]): string | undefined { - if (!blocks.length) return undefined; - const counts = { pass: 0, reject: 0, unknown: 0 }; - for (const block of blocks) { - const ai = (block.aiDecision ?? "").trim(); - if (/同意|通过|approve/i.test(ai)) counts.pass += 1; - else if (/驳回|拒绝|终止|退回|reject/i.test(ai)) counts.reject += 1; - else counts.unknown += 1; - } - const parts = [`${counts.pass} 张同意`, `${counts.reject} 张驳回`]; - if (counts.unknown) parts.push(`${counts.unknown} 张未定`); - return parts.join(" + "); -} - -/** 表格块变换:保留表头两行,按所在章节 + 表头识别语义后重写数据行。 */ -function transformTable( - block: string[], - data: ReportData, - heading: string, - lastH2: string -): string[] { - if (block.length < 2) return block; - const header = block[0]!; - const separator = block[1]!; - const sampleRows = block.slice(2); - const columns = parseRow(header); - if (!columns.length) return block; - - const notes = noteAfter(columns, heading, lastH2, data); - const rows = replacementRows(columns, sampleRows, data, heading); - // 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会) - if (!rows) return [...block, ...notes]; - return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes]; -} - -/** 表后追加的数据说明(人工准确率缺口径时)。 */ -function noteAfter(columns: string[], heading: string, lastH2: string, data: ReportData): string[] { - if (columns.includes("审核方式") && columns.includes("准确率")) { - if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) { - const reviewed = data.notes.reviewedCount ?? 0; - const diverged = data.notes.divergedCount ?? 0; - return ["", `> ℹ️ **数据说明**:人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`, ""]; - } - return ["", HUMAN_ACCURACY_NOTE, ""]; - } - if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance) { - return ["", "> ⚠️ **数据说明**:失准原因分类(规则执行/识别/查重等维度)无上游字段,上表为模板示例分类,需人工归类后替换。", ""]; - } - // §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据 - if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) { - return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,或「原因分类/复核结论」需人工归类;上表为模板示例行,请以真实明细替换。", ""]; - } - return []; -} - -function replacementRows( - columns: string[], - sampleRows: string[], - data: ReportData, - heading: string -): Array> | null { - const perf = data.performance; - - // 报告信息表:fillInline 已处理,行保留 - if (columns.includes("报告编号")) return null; - - // §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行) - if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) { - if (!data.fetched.performance || !perf) return null; - const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined - ? `**${pct(data.humanAccuracy)}**` - : sampleRows.length > 1 - ? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*") - : "*(口径待业务提供)*"; - return [ - ["AI 审核", `**${pct(perf.accuracy)}**`], - ["人工审核", humanCell] - ]; - } - - // §1.1 数据来源与范围 - if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) { - if (!perf) return null; - const dist = distributionOf(data.blocks) ?? ""; - return [ - ["数据来源", "客户授权的已完成历史审批单据"], - ["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`], - ["单据模板", data.templateGroups.length - ? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板` - : "*(单据模板分布待取数)*"], - ["样本总量", `**${perf.approvalCount ?? "—"} 张**${dist ? `(${dist})` : ""}`] - ]; - } - - // §1.3 系统稳定性 - if (columns.includes("项目") && columns.includes("内容") && heading.includes("系统稳定性")) { - if (!perf) return null; - return [ - ["全月成功审核率", `近 **${pct(perf.automationRate, 0)}**(自动化审核采纳率口径)`], - ["迭代影响", `*(迭代影响需业务口径补充;本月自动化采纳率 ${pct(perf.automationRate)})*`] - ]; - } - - // §4 综合效益 - if (columns.includes("维度") && columns.includes("结论") && columns.includes("关键数据") && perf) { - return [ - ["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(perf.accuracy)}**`], - ["时效", "AI 审核单张单据平均耗时", perf.avgDurationSeconds !== undefined ? `平均 **${perf.avgDurationSeconds.toFixed(1)} 秒**` : "—"], - ["风险拦截", "在人工审核通过的单据中,AI 有效防堵的凭证与资金隐患", perf.riskCount !== undefined ? `${perf.riskCount} 笔` : "—"], - ["工作量", "协助财务人员弥补遗漏、聚焦高价值工作", "—"] - ]; - } - - // §2.1 / §3.x 构成总览(维度 | …类型 | 占比 | 单数) - if (columns.includes("维度") && columns.includes("单数") && columns.includes("占比")) { - const isRisk = columns.some((col) => col.includes("风险")); - if (isRisk) { - if (!data.fetched.riskStats || !data.riskStats?.tags.length) return null; - const tags = data.riskStats.tags.filter((tag) => tag.count !== undefined).slice(0, 3); - const total = tags.reduce((sum, tag) => sum + (tag.count ?? 0), 0) || 1; - const typeIdx = Math.max(1, columns.findIndex((col) => col.includes("风险"))); - const pctIdx = columns.indexOf("占比"); - const countIdx = columns.indexOf("单数"); - const rows: Array> = tags.map((tag, idx) => { - const row: Array = Array.from({ length: columns.length }, () => "—"); - row[0] = `TOP ${idx + 1}`; - row[typeIdx] = tag.name ?? tag.id ?? "未命名风险"; - row[pctIdx] = pct(((tag.count ?? 0) / total) * 100, 1); - row[countIdx] = `${tag.count} 张`; - return row; - }); - const totalRow: Array = Array.from({ length: columns.length }, () => "—"); - totalRow[0] = "合计"; - totalRow[pctIdx] = "100%"; - totalRow[countIdx] = `${total} 张`; - rows.push(totalRow); - return rows; - } - // 失准构成:无上游分类 → 留模板原文 - return null; - } - - // §6 AI 通过 / 人工驳回明细(7 列:单据编号|模板|AI|人工|原因分类|复核结论|截图) - if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) { - if (!data.blocks.length) return null; - const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10); - if (!diverged.length) return null; - return diverged.map((block) => [ - block.sn, - block.template || "—", - block.aiDecision ?? "—", - block.humanResult ?? "—", - "*(原因分类待人工归类)*", - block.aiSummary ?? "—", - "(截图)" - ]); - } - - // §7.1 分模板统计(只认明确带"模板"或 6 列且有"AI 准确率"的表头;不吃掉一致性示例的 5 列表) - if ( - (columns.includes("单据模板") || columns[0] === "模板") && - (columns.includes("AI 准确率") || columns.includes("自动审批率") || columns.includes("单量")) - ) { - if (!data.fetched.templateGroups) return null; - if (!data.templateGroups.length) return null; - return data.templateGroups.slice(0, 20).map((group) => { - const agreement = group.total ? (group.agreed / group.total) * 100 : 0; - if (columns.includes("AI 准确率")) { - // 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明 - const row: Array = Array.from({ length: columns.length }, () => "—"); - row[0] = group.template; - row[columns.indexOf("AI 准确率")] = pct(agreement); - const manualIdx = columns.findIndex((col) => col.includes("人工")); - if (manualIdx >= 0 && columns[manualIdx] === "人工同意:驳回") { - row[manualIdx] = `${group.total} 笔`; - } - return row; - } - if (columns.length >= 2) return [group.template, group.total]; - return [group.template]; - }); - } - - return null; -} - -function beijingToday(): string { - return formatBeijingIso().slice(0, 10); -} - -function randomSuffix(): string { - const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; - let out = ""; - for (let i = 0; i < 6; i++) out += alphabet[Math.floor(Math.random() * alphabet.length)]!; - return out; -} diff --git a/src/domains/seal/reports/browser.ts b/src/domains/seal/reports/render/browser.ts similarity index 82% rename from src/domains/seal/reports/browser.ts rename to src/domains/seal/reports/render/browser.ts index 5d07905..def1e4e 100644 --- a/src/domains/seal/reports/browser.ts +++ b/src/domains/seal/reports/render/browser.ts @@ -1,9 +1,9 @@ import { spawn } from "node:child_process" -import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" -import { homedir } from "node:os" +import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { homedir, tmpdir } from "node:os" import { dirname, join } from "node:path" import { pathToFileURL } from "node:url" -import { CliError, validationError } from "../../../core/errors.js" +import { CliError, validationError } from "../../../../core/errors.js" import { pngDimensions, stitchPngBands, type PngBand } from "./png.js" export const PNG_BAND_HEIGHT = 14_000 @@ -54,11 +54,11 @@ export function findReportChrome(explicit?: string): string { return path } -function chrome(binary: string, profile: string, args: string[]): Promise { +function chrome(binary: string, profile: string, args: string[], scaleFactor = 1): Promise { return new Promise((resolve, reject) => { const child = spawn(binary, [ "--headless", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${profile}`, - "--no-first-run", "--no-default-browser-check", "--force-device-scale-factor=1", + "--no-first-run", "--no-default-browser-check", `--force-device-scale-factor=${scaleFactor}`, "--run-all-compositor-stages-before-draw", ...args ], { stdio: ["ignore", "pipe", "pipe"] }) let title = "", tail = "", diagnostic = "", settled = false @@ -136,3 +136,38 @@ export async function renderBrowserArtifacts(html: string, formats: string[], wi if (!existsSync(`${stem}.pdf`) || statSync(`${stem}.pdf`).size === 0) throw new CliError("浏览器未生成 PDF 文件。", 1) } } + +/** 渲染独立 HTML/SVG 图表为高清晰度 PNG 图片 Buffer(默认 4x 超高分屏/印刷级采样)。 */ +export async function renderHtmlToImageBuffer(options: { + html: string; + width: number; + height: number; + scale?: number; + chrome?: string; +}): Promise { + const binary = findReportChrome(options.chrome) + const stage = mkdtempSync(join(tmpdir(), "seal-chart-render-")) + const profile = join(stage, "profile") + mkdirSync(profile, { mode: 0o700 }) + const htmlFile = join(stage, "index.html") + const pngFile = join(stage, "output.png") + writeFileSync(htmlFile, options.html, "utf8") + try { + await chrome( + binary, + profile, + [ + `--screenshot=${pngFile}`, + `--window-size=${options.width},${options.height}`, + "--virtual-time-budget=10000", + pathToFileURL(htmlFile).href + ], + options.scale ?? 4 + ) + if (!existsSync(pngFile)) throw new CliError("Chrome 截图渲染失败,未产出图片文件。", 1) + return readFileSync(pngFile) + } finally { + rmSync(stage, { recursive: true, force: true }) + } +} + diff --git a/src/domains/seal/reports/html.test.ts b/src/domains/seal/reports/render/html.test.ts similarity index 100% rename from src/domains/seal/reports/html.test.ts rename to src/domains/seal/reports/render/html.test.ts diff --git a/src/domains/seal/reports/html.ts b/src/domains/seal/reports/render/html.ts similarity index 98% rename from src/domains/seal/reports/html.ts rename to src/domains/seal/reports/render/html.ts index 2ce9377..88dcd2e 100644 --- a/src/domains/seal/reports/html.ts +++ b/src/domains/seal/reports/render/html.ts @@ -3,8 +3,8 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writ import { homedir } from "node:os" import { basename, dirname, extname, join, resolve } from "node:path" import { Marked, type TokenizerExtension, type Tokens } from "marked" -import { CliError } from "../../../core/errors.js" -import { REPORT_CSS } from "./resources.js" +import { CliError } from "../../../../core/errors.js" +import { REPORT_CSS } from "../templates/resources.js" const katexBase = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/" const mimeTypes: Record = { diff --git a/src/domains/seal/reports/render/index.ts b/src/domains/seal/reports/render/index.ts new file mode 100644 index 0000000..17af9f7 --- /dev/null +++ b/src/domains/seal/reports/render/index.ts @@ -0,0 +1,3 @@ +export * from "./browser.js"; +export * from "./html.js"; +export * from "./png.js"; diff --git a/src/domains/seal/reports/png.test.ts b/src/domains/seal/reports/render/png.test.ts similarity index 100% rename from src/domains/seal/reports/png.test.ts rename to src/domains/seal/reports/render/png.test.ts diff --git a/src/domains/seal/reports/png.ts b/src/domains/seal/reports/render/png.ts similarity index 96% rename from src/domains/seal/reports/png.ts rename to src/domains/seal/reports/render/png.ts index 5b1a167..3feca67 100644 --- a/src/domains/seal/reports/png.ts +++ b/src/domains/seal/reports/render/png.ts @@ -1,6 +1,6 @@ import { closeSync, openSync, readFileSync, readSync, writeFileSync } from "node:fs" import { PNG } from "pngjs" -import { CliError } from "../../../core/errors.js" +import { CliError } from "../../../../core/errors.js" export type PngBand = { file: string; height: number } diff --git a/src/domains/seal/reports/templates/assets/图1-准确率对比.svg b/src/domains/seal/reports/templates/assets/图1-准确率对比.svg index 0a1e632..3f170da 100644 --- a/src/domains/seal/reports/templates/assets/图1-准确率对比.svg +++ b/src/domains/seal/reports/templates/assets/图1-准确率对比.svg @@ -1,32 +1,51 @@ - - + + + + + + + - - + - - + + - - 16.67% + + - - - AI审核准确 - (总准确率92.08%) + + - - 75.42% + + + AI审核准确 + (总准确率92.08%) + + + - - - AI与人工都准确 + + 16.66% - - 7.92% + + 75.42% - - - 人工审核准确 - (总准确率83.33%) + + 7.91% + + + + + + + 人工审核准确 + (总准确率83.33%) + + + + + + + AI与人工都准确 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 · 各单据模板审核耗时分布对比* --- diff --git a/src/domains/seal/reports/resources.ts b/src/domains/seal/reports/templates/resources.ts similarity index 57% rename from src/domains/seal/reports/resources.ts rename to src/domains/seal/reports/templates/resources.ts index 392218a..6eb6397 100644 --- a/src/domains/seal/reports/resources.ts +++ b/src/domains/seal/reports/templates/resources.ts @@ -1,8 +1,8 @@ -import monthly from "./templates/monthly.md" with { type: "text" }; -import css from "./templates/report.css" with { type: "text" }; -import accuracy from "./templates/assets/图1-准确率对比.svg" with { type: "text" }; -import benefits from "./templates/assets/图2-综合效益.svg" with { type: "text" }; -import screenshot from "./templates/assets/图3-示例截图.svg" with { type: "text" }; +import monthly from "./monthly.md" with { type: "text" }; +import css from "./report.css" with { type: "text" }; +import accuracy from "./assets/图1-准确率对比.svg" with { type: "text" }; +import benefits from "./assets/图2-综合效益.svg" with { type: "text" }; +import screenshot from "./assets/图3-示例截图.svg" with { type: "text" }; // Git owns the source files; Bun embeds these imports in both developer and release binaries. // Loading the built-in template never depends on cwd, a checkout, or skill installation. diff --git a/src/domains/seal/reports/validate/index.ts b/src/domains/seal/reports/validate/index.ts new file mode 100644 index 0000000..fe4d5bc --- /dev/null +++ b/src/domains/seal/reports/validate/index.ts @@ -0,0 +1 @@ +export * from "./validate.js"; diff --git a/src/domains/seal/reports/validate.test.ts b/src/domains/seal/reports/validate/validate.test.ts similarity index 100% rename from src/domains/seal/reports/validate.test.ts rename to src/domains/seal/reports/validate/validate.test.ts diff --git a/src/domains/seal/reports/validate.ts b/src/domains/seal/reports/validate/validate.ts similarity index 100% rename from src/domains/seal/reports/validate.ts rename to src/domains/seal/reports/validate/validate.ts