Add one-shot monthly audit report command (report monthly)

Eats in the ai-audit-report-template as a module. The template is the mutable
skin: describeTemplate() infers per-section data demands from ##/### headings
(keyword rules), so editing/renaming/reordering sections does not require
touching collect or render code.

- src/domains/seal/reports/: describe (heading to demand), collect (performance/
  risk blocks/template groups, fetched only for declared demands), render (fills
  tables by section+column signature, rewrites narrative by structure not line
  number), monthly (orchestrator returning content + per-section completeness +
  notes).
- report-templates/: the template body, assets, example, and downstream
  validate.py/render.py (not bundled; next.validate/render in the result point
  at them).
- Capability sealReportMonthlyGet (read-only, allow-listed) + CLI
  "seal-use report monthly --month <YYYY-MM>" + help + KNOWN_FLAGS month +
  read-only report:monthly.
- SKILL.md: routing row + a section stating the two hard rules: the template is
  swappable, and metrics with no upstream source keep template sample values
  with a warning note instead of fabricated numbers.

Template-path resolution branches on isCompiledBinary() (dev: module-relative to
repo root; compiled: cwd), matching how rules lint --file resolves paths, since
templates are not embedded.

Verified: bun test 633 pass (6 new reports tests), tsc clean, oxlint 0 warnings.
Live smoke: 2026-08 report for a real corp fills real accuracy/counts/distribution
and marks human-accuracy + mismatch-classification + section-6 sample rows with
gap notes.
This commit is contained in:
gitea committed 2026-09-30 17:55:37 +08:00
1 parent a37cac2679
commit 2ee15bb0d6
21 files changed
+2281 -1

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "monthly" || action === "month") {
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
}
await runCapability(
"sealReportMonthlyGet",
client,
corp,
{
month,
templatePath: stringOption(args.options.template),
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
}
+20
View File
@@ -600,6 +600,26 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
commands: [
{
name: "monthly",
aliases: ["month"],
summary: "Fill the monthly report template with performance, risk, and approval-run data",
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
],
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
}
]
},
{
area: "simulation",
title: "Simulation testing engine",
+2
View File
@@ -54,6 +54,7 @@ export const VALUE_FLAGS = new Set([
"json", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"month",
"n", "name", "note", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
@@ -100,6 +101,7 @@ export const KNOWN_FLAGS = new Set([
"key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"month",
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
"note", "o", "offset", "out", "out-dir", "outDir",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
+1
View File
@@ -78,6 +78,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
analytics: ["insight", "risks", "performance", "export"],
report: ["monthly"],
source: ["config"],
skill: ["dump", "status"],
doctor: ["", "guide", "paths", "tenant", "auth"],
+6
View File
@@ -53,6 +53,7 @@ export const KNOWN_AREAS = new Set([
"rules",
"approval-runs",
"analytics",
"report",
"simulation",
"deploy",
"preference",
@@ -386,6 +387,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report") {
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
+4 -1
View File
@@ -8,6 +8,7 @@ import { approvalRunsCapabilities } from "./approval-runs.js";
import { simulationCapabilities } from "./simulation.js";
import { deployCapabilities } from "./deploy.js";
import { preferenceCapabilities } from "./preference.js";
import { reportCapabilities } from "./reports.js";
export * from "./helpers.js";
export * from "./validate.js";
@@ -22,7 +23,8 @@ export const sealCapabilities = [
...approvalRunsCapabilities,
...simulationCapabilities,
...deployCapabilities,
...preferenceCapabilities
...preferenceCapabilities,
...reportCapabilities
];
export type SealCapability = (typeof sealCapabilities)[number];
@@ -99,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealPermissionsConfigsList",
"sealPreferenceGet",
"sealPreferenceThinkingDepthPoliciesList",
"sealReportMonthlyGet",
"sealSessionGet",
"sealSimulationBatchGet",
"sealSimulationBatchRecordsGet",
+42
View File
@@ -0,0 +1,42 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { buildMonthlyReport } from "../reports/monthly.js";
import type { CapabilityContext } from "./helpers.js";
export const reportCapabilities = [
{
name: "sealReportMonthlyGet",
description:
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
parameters: z.object({
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
templatePath: z
.string()
.optional()
.describe("自定义模板 Markdown 路径;缺省用 report-templates/monthly.md"),
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
maxRuns: z
.number()
.int()
.positive()
.max(500)
.optional()
.describe("拉取审批运行明细分块的上限,默认 500")
}),
handler: async (
client: KyInstance,
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number },
context: CapabilityContext
) =>
buildMonthlyReport(client, {
month: params.month,
corp: { id: context.corp.id, name: context.corp.name },
templatePath: params.templatePath,
reportId: params.reportId,
maxRuns: params.maxRuns
})
}
];
+266
View File
@@ -0,0 +1,266 @@
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 type { ReportDemand } from "./describe.js";
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
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 (/驳回|拒绝|终止|退回|reject|deny/i.test(text)) return "reject";
return "unknown";
}
export type ReportBlock = {
sn: string;
template: string;
aiDecision: string | undefined;
humanResult: string | undefined;
agreement: "agreed" | "diverged" | "unknown";
aiSummary: string | undefined;
humanComment: string | undefined;
};
export type ReportTemplateGroup = {
template: string;
total: number;
agreed: number;
diverged: number;
};
export type ReportData = {
/** 报告信息表要用的上下文 */
period: { start: string; end: string; month: string };
corp: { id: string; name: string };
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
fetched: Record<ReportDemand, boolean>;
performance?: {
approvalCount?: number;
accuracy?: number;
accuracyTrend?: number;
automationRate?: number;
riskCount?: number;
/** 平均耗时(秒);上游给秒就传秒 */
avgDurationSeconds?: number;
sankey: { nodes: Array<{ id: string }>; links: Array<{ source: string; target: string; value: number }> };
};
riskStats?: {
tags: Array<{ id?: string; name?: string; count?: number }>;
};
blocks: ReportBlock[];
templateGroups: ReportTemplateGroup[];
/** 章节数据完备性标记,渲染时逐节如实写入 */
notes: {
humanAccuracyAvailable: false; // 上游无"人工审核准确率"指标;v1 恒为 false,接口出现后再接
failureRateAvailable: boolean;
mismatchCategoriesAvailable: boolean;
};
};
export type CollectOptions = {
month: string; // YYYY-MM
corp: { id: string; name: string };
/** 用于拉明细分块的上限,防御性封顶 */
maxRuns?: number;
};
function monthRange(month: string): { startDate: string; endDate: 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) };
}
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
export async function collectReportData(
client: KyInstance,
demands: Set<ReportDemand>,
options: CollectOptions
): Promise<ReportData> {
const range = monthRange(options.month);
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
const fetched: Record<ReportDemand, boolean> = {
performance: false,
riskStats: false,
riskDetails: false,
blocks: false,
templateGroups: false
};
const data: ReportData = {
period: {
start: formatBeijingIso(Number(range.startDate)),
end: formatBeijingIso(Number(range.endDate)),
month: options.month
},
corp: options.corp,
fetched,
blocks: [],
templateGroups: [],
notes: {
humanAccuracyAvailable: false,
failureRateAvailable: false,
mismatchCategoriesAvailable: false
}
};
// 1. 效能指标(§1 / §4)
if (demands.has("performance")) {
try {
const perf = await api.getInsightPerformance(client, {
startDate: range.startDate,
endDate: range.endDate
});
const metrics = (perf.metrics ?? {}) as Record<string, { value?: number; trend?: number } | undefined>;
data.performance = {
approvalCount: metrics.approvalCount?.value,
accuracy: metrics.accuracy?.value,
accuracyTrend: metrics.accuracy?.trend,
automationRate: metrics.automationRate?.value,
riskCount: metrics.riskCount?.value,
avgDurationSeconds: metrics.avgDuration?.value,
sankey: perf.sankeyData ?? { nodes: [], links: [] }
};
fetched.performance = true;
} catch {
// 指标接口不可达:章节保持模板原文并在填充时标注数据未取到
}
}
// 2. 风险标签统计(§3 / §4 风险拦截)
if (demands.has("riskStats") || demands.has("riskDetails")) {
try {
const stats = await api.getInsightStats(client, {
startDate: range.startDate,
endDate: range.endDate,
limit: 50
});
const rawList = ((stats as { tags?: unknown }).tags ?? (stats as { list?: unknown }).list ?? []) as Array<Record<string, unknown>>;
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
}))
};
fetched.riskStats = true;
fetched.riskDetails = data.riskStats.tags.length > 0;
} catch {
// 风险统计不可达
}
}
// 3. 决策分块(§2 / §5 / §6)与分模板统计(§7.1)
if (demands.has("blocks") || demands.has("templateGroups")) {
const runs: ApprovalRun[] = [];
let offset = 0;
try {
while (runs.length < maxRuns) {
const page = await api.listApprovalRuns(client, {
offset,
limit: 100,
startDate: range.startDate,
endDate: range.endDate
});
const records = page.records ?? [];
if (!records.length) break;
runs.push(...records);
offset += records.length;
if (records.length < 100) break;
}
const blocks: ReportBlock[] = runs.map((record) => {
const summary = summarizeLocal(record);
const aiPolarity = polarityOf(summary.aiDecision);
const humanPolarity = polarityOf(summary.humanResult);
const agreement =
aiPolarity === "unknown" || humanPolarity === "unknown"
? "unknown"
: aiPolarity === humanPolarity
? "agreed"
: "diverged";
return {
sn: summary.sn ?? summary.id,
template: summary.template,
aiDecision: summary.aiDecision,
humanResult: summary.humanResult,
agreement,
aiSummary: summary.aiSummary,
humanComment: summary.humanComment
};
});
data.blocks = blocks;
fetched.blocks = true;
if (demands.has("templateGroups")) {
const byTemplate = new Map<string, ReportTemplateGroup>();
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; // 失准原因分类无上游字段,需人工归类
return data;
}
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
function summarizeLocal(record: ApprovalRun): {
id: string;
sn?: string;
template: string;
aiDecision?: string;
humanResult?: string;
aiSummary?: string;
humanComment?: string;
} {
const result = (record.result ?? {}) as Record<string, unknown>;
const document = (record.document ?? {}) as Record<string, unknown>;
const aiDecision =
firstString(result.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
const humanResult =
firstString(result.humanResult) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
const template =
firstString(document.templateName) ??
firstString(document.title) ??
firstString(document.name) ??
"";
return {
id: record.id,
sn: record.sourceDocumentSN,
template,
aiDecision,
humanResult,
aiSummary: firstString(result.summary),
humanComment: firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
firstString(result.humanComment)
};
}
function firstString(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
+107
View File
@@ -0,0 +1,107 @@
/**
* 模板 → 数据需求 分析器。
*
* 报告模板是可变的皮:章节标题允许增删、改名、重排。
* 这里不硬编码任何章节,而是扫描模板的 `##`/`###` 标题,用关键词规则反推每个章节
* 需要哪些数据(demand)。渲染器逐节按 demand 取数——模板改了,只需调整或新增规则,
* 编排器(collect/render)不用动。
*/
export type ReportDemand =
/** 审核效能指标(准确率、自动化率、平均耗时、审批量) */
| "performance"
/** 风险标签统计(§3 风险构成) */
| "riskStats"
/** 风险标签下的单据明细(§3 TOP 小节) */
| "riskDetails"
/** AI 与人工的决策分块(§2 失准、§5 一致性、§6 通过/驳回明细) */
| "blocks"
/** 分模板(单据模板)维度的分组统计(§7.1) */
| "templateGroups";
export type SectionPlan = {
/** 章节的 ## 标题原文 */
heading: string;
/** 是否为二级章节(## 为 true,### 为 false) */
level: 2 | 3;
/** 该章节声明的需求;为空表示保持模板原文(纯叙述章节) */
demands: ReportDemand[];
/** 章节序号(## 级别从 1 递增;### 归属最近的 ##) */
chapter: number;
};
/**
* 标题关键词 → 数据需求。规则即契约:命中一个关键词就声明一个需求,多命中取并集。
* 顺序无关;`avoid` 关键词优先(防止"人工审核准确率"这类词把一致性章节误判成效能章节)。
*/
const TITLE_RULES: Array<{ pattern: RegExp; demand: ReportDemand; avoid?: RegExp }> = [
{ pattern: /AI 失准|失准分析|误判|失准构成/, demand: "blocks" },
{ pattern: /风险|潜在/, demand: "riskStats" },
{ pattern: /TOP \d|构成总览|小节|明细/, demand: "riskDetails" },
{ pattern: /准确率|时效|耗时|效能|稳定性|审核测试结果|样本/, demand: "performance", avoid: /一致性示例/ },
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回/, demand: "blocks" },
{ pattern: /分模板|单据模板.*率/, demand: "templateGroups" },
{ pattern: /风险拦截/, demand: "riskStats" }
];
/** 汇总一个 `##` 章节内所有标题(含自身)命中的需求。 */
function demandsFor(titles: string[]): ReportDemand[] {
const demands = new Set<ReportDemand>();
for (const title of titles) {
for (const rule of TITLE_RULES) {
if (rule.avoid && rule.avoid.test(title)) continue;
if (rule.pattern.test(title)) demands.add(rule.demand);
}
}
return [...demands];
}
/**
* 扫描模板文本,产出逐节执行计划。
* 同时返回模板正文里出现过的 `data:` 元数据行(如 `数据来源`、`统计期间` 行)供填充使用。
*/
export function describeTemplate(template: string): SectionPlan[] {
const lines = template.split("\n");
const plans: SectionPlan[] = [];
let chapter = 0;
/** 当前 ## 章节内累积的标题(## 标题 + 其下 ### 标题),到下一个 ## 时结算 */
let pendingTitles: string[] = [];
let pendingHeading = "";
let pendingLevel: 2 | 3 = 2;
let pendingChapter = 0;
const flush = () => {
if (!pendingHeading) return;
plans.push({
heading: pendingHeading,
level: pendingLevel,
demands: demandsFor(pendingTitles),
chapter: pendingChapter
});
};
for (const line of lines) {
const h2 = line.match(/^## (.+)$/);
const h3 = line.match(/^### (.+)$/);
if (h2) {
flush();
chapter += 1;
pendingHeading = h2[1]!.trim();
pendingLevel = 2;
pendingChapter = chapter;
pendingTitles = [pendingHeading];
} else if (h3) {
if (pendingHeading) pendingTitles.push(h3[1]!.trim());
else {
// `###` 出现在任何 `##` 之前:作为独立段落登记,序号并入后续章节
pendingHeading = h3[1]!.trim();
pendingLevel = 3;
pendingChapter = chapter;
pendingTitles = [pendingHeading];
}
}
}
flush();
return plans;
}
+91
View File
@@ -0,0 +1,91 @@
import type { KyInstance } from "ky";
import { existsSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { isCompiledBinary } from "../../../core/runtime.js";
import { describeTemplate } from "./describe.js";
import { collectReportData, type ReportData } from "./collect.js";
import { renderMonthlyReport, type RenderOptions } from "./render.js";
export type MonthlyReportOptions = {
month: string; // YYYY-MM
corp: { id: string; name: string };
/** 模板路径;缺省用仓内 report-templates/monthly.md */
templatePath?: string;
reportId?: string;
maxRuns?: number;
};
export type MonthlyReportResult = {
month: string;
corpId: string;
reportId: string;
templatePath: string;
/** 模板各章节声明的数据需求与取数结果,供 agent 判断哪些章节可直接用、哪些需人工补 */
sections: Array<{ heading: string; demands: string[]; fetched: string[] }>;
notes: ReportData["notes"];
/** 报告 Markdown 本体 */
content: string;
next: {
validate: string;
render: string;
};
};
function defaultTemplatePath(): string {
if (isCompiledBinary()) {
// 模板不进包;编译产物用 cwd(与 rules lint --file 的相对路径解析一致)
return join(process.cwd(), "report-templates", "monthly.md");
}
// dev: src/domains/seal/reports → 仓库根
return join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
}
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
export async function buildMonthlyReport(
client: KyInstance,
options: MonthlyReportOptions
): Promise<MonthlyReportResult> {
const templatePath = options.templatePath
? resolve(options.templatePath)
: defaultTemplatePath();
if (!existsSync(templatePath)) {
throw new Error(
`未找到报告模板: ${templatePath}\n` +
`可用 --template <file> 指定路径,或在 report-templates/ 目录下运行。`
);
}
const template = readFileSync(templatePath, "utf8");
const plans = describeTemplate(template);
const demands = new Set(plans.flatMap((plan) => plan.demands));
const data = await collectReportData(client, demands, {
month: options.month,
corp: options.corp,
maxRuns: options.maxRuns
});
const renderOptions: RenderOptions = {
reportId: options.reportId,
corpName: options.corp.name
};
const content = renderMonthlyReport(template, data, plans, renderOptions);
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-XXXXXX`;
return {
month: options.month,
corpId: options.corp.id,
reportId,
templatePath,
sections: plans.map((plan) => ({
heading: plan.heading,
demands: plan.demands,
fetched: plan.demands.filter((demand) => data.fetched[demand])
})),
notes: data.notes,
content,
next: {
validate: `python3 tools/validate.py <报告文件.md>(校验器与渲染器见 ai-audit-report-template 仓库)`,
render: `python3 tools/render.py <报告文件.md> -o build/<报告文件>(产出 HTML / PNG / A4 PDF 三件套)`
}
};
}
+360
View File
@@ -0,0 +1,360 @@
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { ReportData, ReportBlock } from "./collect.js";
import type { SectionPlan } from "./describe.js";
export type RenderOptions = {
/** 报告编号;未给则按 RPT-<YYYYMM>-<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("准确率")) {
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<Array<string | number>> | 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;
return [
["AI 审核", `**${pct(perf.accuracy)}**`],
["人工审核", sampleRows.length > 1 ? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*") : "*(口径待业务提供)*"]
];
}
// §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<Array<string | number>> = tags.map((tag, idx) => {
const row: Array<string | number> = 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<string | number> = 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<string | number> = 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;
}
+165
View File
@@ -0,0 +1,165 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describeTemplate } from "./describe.js";
import { renderMonthlyReport } from "./render.js";
import type { ReportData } from "./collect.js";
const TEMPLATE = join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
function sampleData(overrides: Partial<ReportData> = {}): ReportData {
return {
period: { start: "2026-08-01T00:00:00+08:00", end: "2026-08-31T23:59:59+08:00", month: "2026-08" },
corp: { id: "corp-a", name: "赢家时尚" },
fetched: { performance: true, riskStats: true, riskDetails: true, blocks: true, templateGroups: true },
performance: {
approvalCount: 240,
accuracy: 92.08,
automationRate: 41.67,
riskCount: 40,
avgDurationSeconds: 445.4,
sankey: { nodes: [], links: [] }
},
riskStats: {
tags: [
{ id: "B.1.1", name: "缺失要求凭证", count: 23 },
{ id: "B.2.3", name: "大额预付与采购口径偏差", count: 9 },
{ id: "B.3.1", name: "票据合规与专票强制违规", count: 8 },
{ id: "B.4.1", name: "长尾风险", count: 30 }
]
},
blocks: [
{ sn: "FP260001", template: "费用报销", aiDecision: "同意", humanResult: "驳回", agreement: "diverged", aiSummary: "合规放行", humanComment: "超标" },
{ sn: "FP260002", template: "费用报销", aiDecision: "同意", humanResult: "同意", agreement: "agreed", aiSummary: "合规放行", humanComment: undefined }
],
templateGroups: [
{ template: "费用报销", total: 100, agreed: 92, diverged: 8 },
{ template: "差旅报销", total: 140, agreed: 130, diverged: 10 }
],
notes: { humanAccuracyAvailable: false, failureRateAvailable: true, mismatchCategoriesAvailable: false },
...overrides
};
}
describe("describeTemplate", () => {
test("infers data demands from section headings without hard-coding chapters", () => {
const template = [
"# x",
"## 1. 审核测试结果",
"### 1.2 核心准确率结论",
"## 2. AI 失准分析",
"## 3. AI 发现的潜在风险",
"### 3.1 风险构成总览",
"## 4. 综合效益",
"## 5. AI 与人工审核一致性示例",
"## 6. AI 通过 / 人工驳回单据明细",
"### 7.1 分模板准确率与自动审批率"
].join("\n");
const plans = describeTemplate(template);
const byHeading = new Map(plans.map((plan) => [plan.heading, plan.demands]));
// 每个 ## 章节一条 plan;### 子标题的需求并入所属章节
expect(byHeading.get("1. 审核测试结果")).toContain("performance");
expect(byHeading.get("2. AI 失准分析")).toContain("blocks");
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskStats");
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskDetails"); // 由 ### 3.1 并入
expect(byHeading.get("5. AI 与人工审核一致性示例")).toContain("blocks");
expect(byHeading.get("6. AI 通过 / 人工驳回单据明细")).toContain("blocks");
// "人工审核准确率" 不应把一致性章节误判为效能章节
expect(byHeading.get("5. AI 与人工审核一致性示例")).not.toContain("performance");
// 子标题不单独成 plan
expect(byHeading.has("3.1 风险构成总览")).toBe(false);
});
test("renaming a chapter keeps working when keywords still match", () => {
// 模板可变:章节改名后只要关键词仍命中就能取到需求
const template = "## 1. 月度测试结果\n## 2. 误判分析\n## 3. 风险扫描";
const plans = describeTemplate(template);
expect(plans).toHaveLength(3);
expect(plans[0]!.demands).toEqual([]); // "月度测试结果" 不含既有规则关键词
expect(plans[1]!.demands).toContain("blocks"); // "误判" 命中规则
expect(plans[2]!.demands).toContain("riskStats");
});
});
describe("renderMonthlyReport", () => {
test("fills identity, period, and performance facts from real data", () => {
const template = readFileSync(TEMPLATE, "utf8");
const plans = describeTemplate(template);
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-TEST01" });
expect(out).toContain("【赢家时尚】8月AI审核准确率报告");
expect(out).toContain("RPT-202608-TEST01");
expect(out).toContain("2026-08-01 ~ 2026-08-31");
// §1.2 AI 准确率用真实值
expect(out).toContain("**92.08%**");
// §1.1 样本总量 = 真实审批量 + blocks 的决策分布(fixture: 2 同意 0 驳回)
expect(out).toContain("**240 张**(2 张同意 + 0 张驳回)");
// §4 关键数据
expect(out).toContain("平均 **445.4 秒**");
expect(out).toContain("40 笔");
// §7.1 分模板:模板名 + 一致率占位
expect(out).toContain("差旅报销");
expect(out).toContain("92.86%"); // 130/140 一致率
expect(out).toContain("费用报销");
});
test("keeps template sample values and adds a warning note when a metric has no upstream source", () => {
const template = readFileSync(TEMPLATE, "utf8");
const plans = describeTemplate(template);
const out = renderMonthlyReport(template, sampleData(), plans);
// 人工审核准确率:无上游口径 → 模板示例值保留 + ⚠️ 数据说明
expect(out).toContain("人工审核准确率");
expect(out).toContain("数据说明");
expect(out).toContain("人工准确率");
// 失准原因分类:无上游字段 → 不编造
expect(out).toContain("失准原因分类");
// 不应把示例值(83.33%)冒充为真实抓取结果的同时又丢失说明
expect(out).toContain("**83.33%**");
});
test("replaces the sample mismatch narrative with real counts", () => {
const template = readFileSync(TEMPLATE, "utf8");
const plans = describeTemplate(template);
const out = renderMonthlyReport(template, sampleData(), plans);
// 221/240 与 19 单 是模板示例;真实数据 240 * 92.08% = 221, 失准 19 → 数字仍成立,
// 关键是失准构成总览不冒充分类(已由 noteAfter 标注),且叙述句不残留 92.08% 之外的错误样本量
expect(out).toContain("221 单(92.08%)");
expect(out).toContain("19 单(7.92%)");
});
test("custom template path drives the same pipeline (skin is swappable)", () => {
const template = [
"# 【X】月报",
"",
"| 报告信息 | 内容 |",
"| --- | --- |",
"| 报告编号 | RPT-202608-PLACE |",
"| 客户名称 | 占位 |",
"| 统计期间 | 占位 |",
"| 生成日期 | 占位 |",
"",
"## 1. 审核测试结果",
"",
"本月样本 **0 笔**。",
"",
"| 审核方式 | 准确率 |",
"| --- | --- |",
"| AI 审核 | **0%** |",
"| 人工审核 | **0%** |"
].join("\n");
const plans = describeTemplate(template);
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-CUSTOM" });
expect(out).toContain("RPT-202608-CUSTOM");
expect(out).toContain("**92.08%**");
expect(out).toContain("**240 笔**");
// 表头保留
expect(out).toContain("| 审核方式 | 准确率 |");
// ⚠️ 说明在表后追加
expect(out).toContain("⚠️ **数据说明**");
});
});