287 lines
13 KiB
TypeScript
287 lines
13 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
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";
|
||
|
||
const TEMPLATE = join(import.meta.dirname, "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 }
|
||
],
|
||
reviews: new Map(),
|
||
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("⚠️ **数据说明**");
|
||
});
|
||
});
|
||
|
||
|
||
describe("review store + human accuracy join", () => {
|
||
const originalEnv = process.env.SEAL_USE_REVIEWS_DIR;
|
||
let testDir: string;
|
||
|
||
beforeEach(() => {
|
||
testDir = mkdtempSync(join(tmpdir(), "seal-reviews-test-"));
|
||
process.env.SEAL_USE_REVIEWS_DIR = testDir;
|
||
});
|
||
|
||
afterEach(() => {
|
||
if (originalEnv === undefined) delete process.env.SEAL_USE_REVIEWS_DIR;
|
||
else process.env.SEAL_USE_REVIEWS_DIR = originalEnv;
|
||
rmSync(testDir, { recursive: true, force: true });
|
||
});
|
||
|
||
test("writeReview appends and loadReviews merges by SN (last write wins)", () => {
|
||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "human_correct" });
|
||
writeReview("corp-a", { sn: "FP2", month: "2026-08", verdict: "ai_correct" });
|
||
// 同一 SN 改判:后写覆盖先写
|
||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "both_correct" });
|
||
|
||
const reviews = loadReviews("corp-a", "2026-08");
|
||
expect(reviews.size).toBe(2);
|
||
expect(reviews.get("FP1")?.verdict).toBe("both_correct");
|
||
expect(reviews.get("FP2")?.verdict).toBe("ai_correct");
|
||
|
||
// 文件按租户+月份分片,追加式 JSONL
|
||
expect(reviewFilePath("corp-a", "2026-08")).toContain("corp-a-2026-08.jsonl");
|
||
const content = readFileSync(reviewFilePath("corp-a", "2026-08"), "utf8").trim().split("\n");
|
||
expect(content).toHaveLength(3); // 3 次写入(含改判)
|
||
});
|
||
|
||
test("loadReviews isolates tenants and months, skips corrupt lines", () => {
|
||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" });
|
||
writeReview("corp-b", { sn: "B1", month: "2026-08", verdict: "human_correct" });
|
||
writeReview("corp-a", { sn: "A2", month: "2026-09", verdict: "ai_correct" });
|
||
// 写入一行损坏数据
|
||
const fs = require("node:fs") as typeof import("node:fs");
|
||
fs.appendFileSync(reviewFilePath("corp-a", "2026-08"), "{corrupt json}\n", "utf8");
|
||
|
||
expect(loadReviews("corp-a", "2026-08").size).toBe(1);
|
||
expect(loadReviews("corp-b", "2026-08").size).toBe(1);
|
||
expect(loadReviews("corp-a", "2026-09").size).toBe(1);
|
||
expect(loadReviews("corp-a", "2026-07").size).toBe(0);
|
||
});
|
||
|
||
test("rejects invalid month and verdict with exit 13 validation error", () => {
|
||
expect(() => writeReview("corp-a", { sn: "X", month: "bad", verdict: "ai_correct" })).toThrow();
|
||
expect(() => writeReview("corp-a", { sn: "X", month: "2026-08", verdict: "wrong" })).toThrow();
|
||
expect(() => writeReview("corp-a", { sn: " ", month: "2026-08", verdict: "ai_correct" })).toThrow();
|
||
});
|
||
|
||
test("collectReportData joins reviews onto fetched blocks and computes human accuracy", async () => {
|
||
// 写入裁决:3 个 SN,其中 1 个分歧单被判人工对
|
||
writeReview("corp-a", { sn: "D1", month: "2026-08", verdict: "human_correct" }); // 分歧,人工对
|
||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" }); // 一致,AI 对
|
||
writeReview("corp-a", { sn: "A2", month: "2026-08", verdict: "both_correct" }); // 一致,双方对
|
||
|
||
// 伪客户端:只返回 3 条审批运行(SN 对应裁决),不发真网络
|
||
const runs = [
|
||
{ id: "r1", sourceDocumentSN: "D1", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } },
|
||
{ id: "r2", sourceDocumentSN: "A1", result: { decision: "驳回" }, pipelineData: { humanResult: "驳回" } },
|
||
{ id: "r3", sourceDocumentSN: "A2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" } }
|
||
];
|
||
const fakeClient = {
|
||
get: async () => ({ json: async () => ({ data: { records: runs, total: 3 } }) })
|
||
} as never;
|
||
|
||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||
month: "2026-08",
|
||
corp: { id: "corp-a", name: "A" }
|
||
});
|
||
|
||
expect(data.reviews.size).toBe(3);
|
||
expect(data.blocks).toHaveLength(3);
|
||
// 每个 block 挂上裁决
|
||
expect(data.blocks.map((b) => b.verdict)).toEqual(["human_correct", "ai_correct", "both_correct"]);
|
||
// 裁决数 = 3,人工对 = human_correct(D1) + both_correct(A2) = 2 → 2/3 = 66.67%
|
||
expect(data.notes.reviewedCount).toBe(3);
|
||
expect(data.notes.humanAccuracyAvailable).toBe(true);
|
||
expect(data.humanAccuracy).toBeCloseTo(66.67, 1);
|
||
// D1 是分歧单(AI 同意 / 人工驳回)
|
||
expect(data.notes.divergedCount).toBeGreaterThanOrEqual(1);
|
||
});
|
||
|
||
test("no reviews → human accuracy unavailable (honest gap, not fabricated)", async () => {
|
||
const fakeClient = {
|
||
get: async () => ({ json: async () => ({ data: { records: [{ id: "r1", sourceDocumentSN: "X1" }], total: 1 } }) })
|
||
} as never;
|
||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||
month: "2026-08",
|
||
corp: { id: "corp-no-reviews", name: "B" }
|
||
});
|
||
expect(data.reviews.size).toBe(0);
|
||
expect(data.notes.humanAccuracyAvailable).toBe(false);
|
||
expect(data.humanAccuracy).toBeUndefined();
|
||
});
|
||
|
||
test("render uses human accuracy when available and shows review coverage note", () => {
|
||
const template = readFileSync(TEMPLATE, "utf8");
|
||
const plans = describeTemplate(template);
|
||
const reviews = new Map();
|
||
reviews.set("FP260001", { sn: "FP260001", month: "2026-08", verdict: "human_correct", recordedAt: "" });
|
||
const data = sampleData({
|
||
reviews,
|
||
humanAccuracy: 75,
|
||
notes: { humanAccuracyAvailable: true, failureRateAvailable: true, mismatchCategoriesAvailable: false, reviewedCount: 4, divergedCount: 2 }
|
||
});
|
||
const out = renderMonthlyReport(template, data, plans);
|
||
|
||
// §1.2 人工审核行用真实 75%,且不再弹"口径待业务提供"
|
||
expect(out).toContain("**75.00%**");
|
||
expect(out).toContain("已裁决 4 笔");
|
||
expect(out).not.toContain("口径待业务提供");
|
||
});
|
||
});
|