Add report ledger workflow, refine terminology and codify skill discipline

This commit is contained in:
gitea committed 2026-10-16 15:35:25 +08:00
1 parent 077ecb050c
commit c6bd113fff
21 files changed
+1393 -377

No files matched your search

+116 -9
View File
@@ -16,12 +16,29 @@ import {
loadReviews,
reviewFilePath,
writeReview,
type MonthlyReportResult
type MonthlyReportResult,
buildReportLedgerCsv,
buildReportLedgerXlsx,
loadReportDataFromLedger,
collectReportData,
type ReportData
} 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" | "export" | "template" | "chart", args: ParsedArgs) {
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
if (Boolean(args.options.ledger) || action === "review") {
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
const corp = {
corpId,
id: corpId,
name: corpId,
corpName: corpId,
source: { source: "seal", sealUrl: "" }
} as unknown as CorpConfig;
await handleReportCommand(action, {} as any, corp, args);
return;
}
if (action === "template") {
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
@@ -78,14 +95,83 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report generate` / `data` — AI 审核报告。 */
/** `seal-use report generate` / `ledger` / `data` — AI 审核报告。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "ledger") {
const ledgerPath = stringOption(args.options.ledger);
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
const format = (stringOption(args.options.format) ?? (out?.endsWith(".csv") ? "csv" : "xlsx")).toLowerCase();
let data: ReportData;
if (ledgerPath) {
data = await loadReportDataFromLedger(ledgerPath, { corp: { id: corp.id, name: corp.name } });
} else {
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if ((!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--max-runs <n>] [--out <file.xlsx|csv>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
data = await collectReportData(client, new Set(["blocks", "templateGroups", "performance"]), {
startDate,
endDate,
month,
corp: { id: corp.id, name: corp.name },
templates,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
});
}
const outFile = out ?? `台账-${corp.id}-${(data.period.label ?? data.period.start).replace(/[^0-9A-Za-z_-]/g, "_")}.${format === "csv" ? "csv" : "xlsx"}`;
const targetPath = resolve(outFile);
if (format === "csv") {
const csvContent = buildReportLedgerCsv(data);
writeFileSync(targetPath, csvContent, "utf8");
} else {
const xlsxBuffer = await buildReportLedgerXlsx(data);
writeFileSync(targetPath, xlsxBuffer);
}
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
printJson({
file: targetPath,
format: format === "csv" ? "csv" : "xlsx",
corpId: corp.id,
period: data.period,
totalBlocks: data.blocks.length,
templates: [...new Set(data.blocks.map((b) => b.template))],
divergedCount,
unreviewedDiverged,
next: {
reviewTip: "可在 Excel 中直接编辑'复核定性裁决'列(填写:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),也可直接剔除不需要的模板行",
generate: `seal-use report generate --ledger '${targetPath}' --corp ${corp.id} --out reports/报告.md`
}
}, outputOptions(args.options));
return;
}
if (action === "data") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
@@ -98,9 +184,9 @@ export async function handleReportCommand(
stringOption(args.options.until);
const month = stringOption(args.options.month);
if ((!startDate || !endDate) && !month) {
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report data --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--max-runs <n>] [--corp <corpId>]"
"Usage: seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--max-runs <n>] [--corp <corpId>]"
);
}
@@ -115,6 +201,7 @@ export async function handleReportCommand(
endDate,
month,
templates,
ledgerPath,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
}
);
@@ -123,6 +210,7 @@ export async function handleReportCommand(
}
if (action === "monthly" || action === "month" || action === "generate") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
@@ -135,9 +223,9 @@ export async function handleReportCommand(
stringOption(args.options.until);
const month = stringOption(args.options.month);
if ((!startDate || !endDate) && !month) {
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report generate --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
"Usage: seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
);
}
@@ -152,6 +240,7 @@ export async function handleReportCommand(
endDate,
month,
templates,
ledgerPath,
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),
@@ -178,7 +267,7 @@ export async function handleReportCommand(
}
if (action === "review") {
const sub = args.command[2]; // set | list
const sub = args.command[2]; // set | list | import
if (sub === "list") {
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
@@ -193,6 +282,24 @@ export async function handleReportCommand(
return;
}
if (sub === "import") {
const file = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.ledger);
if (!file) throw usageError("Usage: seal-use report review import <台账.xlsx|csv> --corp <corpId>");
const ledgerData = await loadReportDataFromLedger(file, { corp: { id: corp.id, name: corp.name } });
let imported = 0;
for (const rev of ledgerData.reviews.values()) {
writeReview(corp.id, rev);
imported++;
}
printJson({
corpId: corp.id,
file: resolve(file),
importedCount: imported,
totalBlocks: ledgerData.blocks.length
}, outputOptions(args.options));
return;
}
if (sub === "set") {
const recordId =
stringOption(args.options["record-id"]) ??
@@ -221,7 +328,7 @@ export async function handleReportCommand(
return;
}
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
}
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
+35 -7
View File
@@ -619,22 +619,40 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
title: "AI audit accuracy reports (acceptance, go-live, periodic)",
description: "Generate AI audit and acceptance reports, export standalone Excel/CSV ledgers, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "ledger",
summary: "Export standalone audit run ledger (.xlsx / .csv) with full AI & human opinions",
usage: ["seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--out <file.xlsx>] [--corp <corpId>]"],
options: [
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--ledger <file>", description: "Inspect or convert an existing ledger file" },
{ flag: "--out <file>", description: "Output path (.xlsx or .csv); defaults to 台账-<corpId>-<period>.xlsx" },
{ flag: "--format <xlsx|csv>", description: "Export format (default: xlsx, or inferred from --out)" },
{ flag: "--max-runs <n>", description: "Cap approval-run fetch, default 500" }
],
description: "Exports full audit ledger containing recordId, SN, template, AI decisions, full AI opinions & conditions, human results & comments, agreement, and review verdict columns. Agents can freely trim rows/templates and fill verdicts."
},
{
name: "data",
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
usage: ["seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--max-runs <n>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD" },
{ flag: "--ledger <file>", description: "Directly parse an edited Excel/CSV ledger file without remote requests" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
],
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
},
{
name: "template",
summary: "Dump or save the built-in monthly report Markdown template",
summary: "Dump or save the built-in report Markdown template",
usage: ["seal-use report template [--out <file.md>]"],
options: [
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
@@ -657,10 +675,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "generate",
aliases: ["monthly", "month"],
summary: "Fill the audit report template with performance, risk, and approval-run data",
usage: ["seal-use report generate --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
usage: ["seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
options: [
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--ledger <file>", description: "Driven directly by an edited Excel/CSV ledger as the sole source of truth; ignores deleted templates/runs and respects in-place verdicts" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist; filters blocks and ledger at source" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary" },
{ flag: "--out <file>", description: "Save Markdown plus local images and Excel/CSV ledgers beside the report; stdout stays JSON" },
@@ -669,7 +688,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
],
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). Generates both Markdown report and companion Excel/CSV ledger."
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings. Supports direct ledger-driven generation where user/Agent modifications to templates and rows are strictly respected."
},
{
name: "validate",
@@ -725,6 +744,15 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads the local JSONL store and returns all adjudications."
},
{
name: "review import",
summary: "Bulk import adjudications from an edited Excel/CSV ledger file",
usage: ["seal-use report review import <台账.xlsx|csv> --corp <corpId>"],
options: [
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads '复核定性裁决', '复核人', and '复核批注说明' columns from the ledger and bulk writes into the local review store."
}
]
},
+2 -2
View File
@@ -52,7 +52,7 @@ export const VALUE_FLAGS = new Set([
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
@@ -105,7 +105,7 @@ export const KNOWN_FLAGS = new Set([
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
+10 -1
View File
@@ -225,7 +225,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
if (
area === "report" &&
(action === "validate" ||
action === "render" ||
action === "export" ||
action === "template" ||
action === "chart" ||
action === "review" ||
Boolean(args.options.ledger))
) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
return;
}
+9
View File
@@ -31,6 +31,7 @@ export const reportCapabilities = [
.optional()
.describe("自定义模板 Markdown 路径;缺省用随 CLI 内嵌的仓内 monthly.md,不依赖当前目录"),
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
ledgerPath: z.string().optional().describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
maxRuns: z
.number()
.int()
@@ -50,6 +51,7 @@ export const reportCapabilities = [
endDate?: string;
month?: string;
templates?: string[];
ledgerPath?: string;
templatePath?: string;
reportId?: string;
maxRuns?: number;
@@ -62,6 +64,7 @@ export const reportCapabilities = [
endDate: params.endDate,
month: params.month,
templates: params.templates,
ledgerPath: params.ledgerPath,
corp: { id: context.corp.id, name: context.corp.name },
templatePath: params.templatePath,
reportId: params.reportId,
@@ -91,6 +94,10 @@ export const reportCapabilities = [
.array(z.string())
.optional()
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
ledgerPath: z
.string()
.optional()
.describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
maxRuns: z
.number()
.int()
@@ -106,6 +113,7 @@ export const reportCapabilities = [
endDate?: string;
month?: string;
templates?: string[];
ledgerPath?: string;
maxRuns?: number;
},
context: CapabilityContext
@@ -115,6 +123,7 @@ export const reportCapabilities = [
endDate: params.endDate,
month: params.month,
templates: params.templates,
ledgerPath: params.ledgerPath,
corp: { id: context.corp.id, name: context.corp.name },
maxRuns: params.maxRuns
})
+3 -2
View File
@@ -1,6 +1,6 @@
# Seal 报告生成与渲染域 (`src/domains/seal/reports`)
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核月度准确率报告的**数据提取、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核报告(验收、上线、周期审计)的**数据提取、台账导出导入、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
---
@@ -18,7 +18,7 @@ src/domains/seal/reports/
│ ├── describe.ts # 解析 Markdown 标题并反推各章节数据需求
│ ├── collect.ts # 通过 Seal API 抓取单据指标,合并人工复核记录
│ ├── render.ts # 模板占位填充与章节内容排版
│ ├── monthly.ts # 月度报告顶层调度器 (buildMonthlyReport)
│ ├── monthly.ts # 报告顶层调度器 (buildMonthlyReport / 支持 --ledger 离线台账)
│ ├── review-store.ts # 人工复核判定本地存储(JSONL 租户分片)
│ └── index.ts # 流水线出口
├── render/ # 渲染与排版引擎底层
@@ -31,6 +31,7 @@ src/domains/seal/reports/
│ └── index.ts # 校验门禁出口
├── export/ # 文件系统整包导出与资产收拢
│ ├── files.ts # 报告整包打包器 (exportReportPackage) 及文件保存
│ ├── ledger.ts # 明细台账双端依据导出 (Excel/CSV) 与自由裁量加载
│ └── index.ts # 导出器出口
├── templates/ # 模板与静态资源
│ ├── monthly.md # 标准月度报告 Markdown 模板
@@ -211,5 +211,44 @@ describe("local report CLI", () => {
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true);
expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true);
}, 35000);
test("CLI report ledger and --ledger options work seamlessly", async () => {
const dir = workspace();
const csvContent = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-1,SN-1,差旅报销,出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批,分歧,AI判断正确 / 人工判断错误,专家,依据合规,12',
'rec-2,SN-2,差旅报销,采购,李四,行政部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,专家,无误,8'
].join("\n");
const csvFile = join(dir, "my-ledger.csv");
writeFileSync(csvFile, csvContent);
// 1. seal-use report ledger --ledger <file> --out <file.xlsx>
const xlsxOut = join(dir, "converted.xlsx");
const ledgerRes = await runCli(["report", "ledger", "--ledger", csvFile, "--out", xlsxOut, "--corp", "test-corp"]);
expect(ledgerRes.exitCode).toBe(0);
expect(existsSync(xlsxOut)).toBe(true);
// 2. seal-use report data --ledger <file> --corp test-corp
const dataRes = await runCli(["report", "data", "--ledger", csvFile, "--corp", "test-corp"]);
expect(dataRes.exitCode).toBe(0);
const parsedData = JSON.parse(dataRes.stdout);
expect(parsedData.templateGroups).toHaveLength(1);
expect(parsedData.templateGroups[0].template).toBe("差旅报销");
expect(parsedData.metrics.aiAccuracy).toBe(100);
// 3. seal-use report review import <file> --corp test-corp
const importRes = await runCli(["report", "review", "import", csvFile, "--corp", "test-corp"]);
expect(importRes.exitCode).toBe(0);
const parsedImport = JSON.parse(importRes.stdout);
expect(parsedImport.importedCount).toBe(2);
// 4. seal-use report generate --ledger <file> --out <report.md> --corp test-corp
const reportOut = join(dir, "generated-report.md");
const genRes = await runCli(["report", "generate", "--ledger", csvFile, "--out", reportOut, "--corp", "test-corp"]);
expect(genRes.exitCode).toBe(0);
expect(existsSync(reportOut)).toBe(true);
const md = readFileSync(reportOut, "utf8");
expect(md).toContain("差旅报销");
});
});
+1
View File
@@ -1 +1,2 @@
export * from "./files.js";
export * from "./ledger.js";
+371 -39
View File
@@ -1,8 +1,35 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import ExcelJS from "exceljs";
import type { ReportBlock, ReportData } from "../pipeline/collect.js";
import { validationError } from "../../../../core/errors.js";
import {
polarityOf,
populateReviewsAndMetrics,
type ReportBlock,
type ReportData
} from "../pipeline/collect.js";
import { ReviewsMap, type ReviewRecord } from "../pipeline/review-store.js";
function csvEscape(val: string | number | undefined): string {
export const REPORT_LEDGER_HEADERS = [
"审核ID(recordId)",
"单据编号(SN)",
"单据模板",
"单据标题/事由",
"提交人",
"费用承担部门",
"跑批时间",
"AI审批决策",
"AI审核完整意见与违规详情",
"人工审批结论",
"人工审批批注/驳回说明",
"人机一致性",
"复核定性裁决",
"复核人",
"复核批注说明",
"审批耗时(秒)"
] as const;
function csvEscape(val: string | number | undefined | null): string {
if (val === undefined || val === null) return "";
const str = String(val).replace(/\r?\n/g, " ").trim();
if (/[",\n]/.test(str)) {
@@ -11,44 +38,111 @@ function csvEscape(val: string | number | undefined): string {
return str;
}
function formatAgreement(agreement: ReportBlock["agreement"]): string {
export function formatAgreement(agreement: ReportBlock["agreement"]): string {
if (agreement === "agreed") return "一致";
if (agreement === "diverged") return "分歧";
return "未完结/流转中";
}
function formatVerdict(block: ReportBlock): string {
/**
* 将 AI 审核摘要与命中的具体规则风险详情合成为完整的审核意见文本
*/
export function formatAiOpinion(block: { aiSummary?: string; conditions?: string[] }): string {
const parts: string[] = [];
if (block.aiSummary && block.aiSummary.trim()) {
parts.push(block.aiSummary.trim());
}
if (block.conditions && block.conditions.length > 0) {
const condStr = block.conditions.map((c, i) => `${i + 1}. ${c}`).join("; ");
if (!parts.some((p) => p.includes(condStr))) {
parts.push(`【触发违规/风险项】${condStr}`);
}
}
return parts.join("\n") || "—";
}
/**
* 规范化复核裁决定性措辞:
* 严密区分「单据违规判定(通过/驳回)」与「审核行为复核(判断正确/判定误判)」,杜绝含混的“失准”造成歧义。
*/
export 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") return "AI 依规正确 / 人工失准 (D4)";
if (v === "human_correct") return "人工合理 / AI 失准";
if (v === "both_wrong") return "双方均失准";
if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方判断均正确";
if (v === "ai_correct") return "AI 判断正确 / 人工判断错误";
if (v === "human_correct") return "人工判断正确 / AI 判定误判";
if (v === "both_wrong") return "双方判定均误判";
if (v === "undecided") return "存疑待定";
return "待复核";
}
/**
* 解析人或 Agent 在 Excel/CSV 中填入的复核裁决定性文本,映射为标准 verdict
*/
export function parseVerdictText(text: string | number | undefined | null): ReviewRecord["verdict"] | undefined {
if (text === undefined || text === null) return undefined;
const str = String(text).trim();
if (!str || str === "—" || str === "-" || str === "待复核" || str === "待人工审批完结") return undefined;
const lower = str.toLowerCase();
// 1. ai_correct (AI判断正确 / 人工判断错误)
if (
lower.includes("ai_correct") ||
/ai.*(正确|依规|判对|看对)/i.test(str) ||
/人工.*(错误|误判|失准|漏审|看错|漏判)/i.test(str) ||
lower.includes("d4")
) {
if (/人工.*(正确|合理)/i.test(str) && /ai.*(错误|误判|失准)/i.test(str)) {
return "human_correct";
}
return "ai_correct";
}
// 2. human_correct (人工判断正确 / AI判定误判)
if (
lower.includes("human_correct") ||
/人工.*(正确|合理|判对|看对)/i.test(str) ||
/ai.*(误判|错误|失准|误报|漏报|漏审)/i.test(str)
) {
return "human_correct";
}
// 3. both_correct (双方判断均正确)
if (
lower.includes("both_correct") ||
/双方.*(正确|合理|无误)/i.test(str) ||
/一致.*正确/i.test(str) ||
lower.includes("d1") ||
lower.includes("d2")
) {
return "both_correct";
}
// 4. both_wrong (双方判定均误判)
if (
lower.includes("both_wrong") ||
/双方.*(误判|错误|失准)/i.test(str) ||
/都.*(错|误判)/i.test(str)
) {
return "both_wrong";
}
// 5. undecided (存疑待定)
if (
lower.includes("undecided") ||
/存疑|待定|暂不确定|无法判定/i.test(str)
) {
return "undecided";
}
return undefined;
}
/**
* 构建带 UTF-8 BOM 的跑批与人工复核明细台账 CSV
*/
export function buildReportLedgerCsv(data: ReportData): string {
const headers = [
"审核ID(recordId)",
"单据编号(SN)",
"单据模板",
"单据标题/事由",
"提交人",
"费用承担部门",
"跑批时间",
"AI审批决策",
"人工审批结论",
"人机一致性",
"复核定性结论",
"复核人",
"复核批注说明",
"审批耗时(秒)",
"AI审核意见摘要"
];
const headers = [...REPORT_LEDGER_HEADERS];
const rows = data.blocks.map((block) => {
const review = data.reviews instanceof ReviewsMap
@@ -63,13 +157,14 @@ export function buildReportLedgerCsv(data: ReportData): string {
block.department || "—",
block.createdAt || "—",
block.aiDecision || "—",
formatAiOpinion(block),
block.humanResult || "—",
block.humanComment || "—",
formatAgreement(block.agreement),
formatVerdict(block),
review?.reviewedBy || "—",
review?.note || "—",
block.durationSeconds ?? "",
block.aiSummary || "—"
review?.reviewedBy || block.reviewedBy || "—",
review?.note || block.reviewNote || "—",
block.durationSeconds ?? ""
].map(csvEscape).join(",");
});
@@ -90,20 +185,21 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
detailSheet.columns = [
{ header: "审核ID(recordId)", key: "recordId", width: 28 },
{ header: "单据编号(SN)", key: "sn", width: 16 },
{ header: "单据编号(SN)", key: "sn", width: 18 },
{ 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: "AI审批决策", key: "aiDecision", width: 14 },
{ header: "AI审核完整意见与违规详情", key: "aiOpinion", width: 55 },
{ header: "人工审批结论", key: "humanResult", width: 15 },
{ header: "人工审批批注/驳回说明", key: "humanComment", width: 38 },
{ header: "人机一致性", key: "agreement", width: 14 },
{ header: "复核定性结论", key: "verdict", width: 24 },
{ header: "复核定性裁决", key: "verdict", width: 26 },
{ header: "复核人", key: "reviewedBy", width: 14 },
{ header: "复核批注说明", key: "note", width: 38 },
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 },
{ header: "AI审核意见摘要", key: "aiSummary", width: 55 }
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 }
];
const headerRow = detailSheet.getRow(1);
@@ -125,13 +221,14 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
department: block.department || "—",
createdAt: block.createdAt || "—",
aiDecision: block.aiDecision || "—",
aiOpinion: formatAiOpinion(block),
humanResult: block.humanResult || "—",
humanComment: block.humanComment || "—",
agreement: formatAgreement(block.agreement),
verdict: formatVerdict(block),
reviewedBy: review?.reviewedBy || "—",
note: review?.note || "—",
durationSeconds: block.durationSeconds ?? "",
aiSummary: block.aiSummary || "—"
reviewedBy: review?.reviewedBy || block.reviewedBy || "—",
note: review?.note || block.reviewNote || "—",
durationSeconds: block.durationSeconds ?? ""
});
row.alignment = { vertical: "top", wrapText: true };
}
@@ -185,6 +282,241 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
return Buffer.from(arrayBuffer);
}
/**
* 解析 CSV 行(支持引号转义与换行)
*/
function parseCsvRows(content: string): string[][] {
const rows: string[][] = [];
let currentRow: string[] = [];
let currentCell = "";
let inQuotes = false;
const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
for (let i = 0; i < text.length; i++) {
const char = text[i];
const next = text[i + 1];
if (inQuotes) {
if (char === '"') {
if (next === '"') {
currentCell += '"';
i++;
} else {
inQuotes = false;
}
} else {
currentCell += char;
}
} else {
if (char === '"') {
inQuotes = true;
} else if (char === ",") {
currentRow.push(currentCell.trim());
currentCell = "";
} else if (char === "\n" || (char === "\r" && next === "\n")) {
if (char === "\r") i++;
currentRow.push(currentCell.trim());
if (currentRow.some((c) => c !== "")) {
rows.push(currentRow);
}
currentRow = [];
currentCell = "";
} else if (char !== "\r") {
currentCell += char;
}
}
}
if (currentCell || currentRow.length > 0) {
currentRow.push(currentCell.trim());
if (currentRow.some((c) => c !== "")) {
rows.push(currentRow);
}
}
return rows;
}
/**
* 从本地已编辑/已裁剪的 Excel (.xlsx) 或 CSV 台账文件逆向解析载入 ReportData。
* 核心设计边界:
* 1. 严格以本地台账为唯一事实源,绝不越界回查云端接口;
* 2. Agent 从台账中剔除的模板和单据,完全不参与后续报告和指标统计;
* 3. 自动识别台账中填入的「复核定性裁决」,作为权威判定计算人机一致率与准确率;
* 4. 门禁校验仅校验当前台账内部剩余行的数据完备性。
*/
export async function loadReportDataFromLedger(
filePath: string,
options?: { corp?: { id: string; name: string } }
): Promise<ReportData> {
const resolvedPath = resolve(filePath);
if (!existsSync(resolvedPath)) {
throw validationError(`台账文件不存在: ${resolvedPath}`);
}
let rawRows: string[][] = [];
if (resolvedPath.endsWith(".xlsx")) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(resolvedPath);
const sheet = workbook.worksheets.find((w) => w.name.includes("明细")) ?? workbook.worksheets[0];
if (!sheet) {
throw validationError(`Excel 文件中未找到有效工作表: ${resolvedPath}`);
}
sheet.eachRow((row) => {
const values: string[] = [];
row.eachCell({ includeEmpty: true }, (cell) => {
let text = "";
if (cell.value !== null && cell.value !== undefined) {
if (typeof cell.value === "object" && "text" in cell.value) {
text = String(cell.value.text);
} else if (typeof cell.value === "object" && "result" in cell.value) {
text = String(cell.value.result);
} else {
text = String(cell.value);
}
}
values.push(text.trim());
});
rawRows.push(values);
});
} else {
const content = readFileSync(resolvedPath, "utf8");
rawRows = parseCsvRows(content);
}
if (rawRows.length < 2) {
throw validationError(`台账文件中没有有效数据行: ${resolvedPath}`);
}
const headerRow = rawRows[0]!;
const colMap: Record<string, number> = {};
headerRow.forEach((h, idx) => {
const clean = String(h).trim().toLowerCase();
if (clean.includes("审核id") || clean.includes("recordid")) colMap.recordId = idx;
else if (clean.includes("单据编号") || clean.includes("sn")) colMap.sn = idx;
else if (clean.includes("模板") || clean.includes("template")) colMap.template = idx;
else if (clean.includes("事由") || clean.includes("标题") || clean.includes("title")) colMap.title = idx;
else if (clean.includes("提交人") || clean.includes("submitter")) colMap.submitter = idx;
else if (clean.includes("部门") || clean.includes("department")) colMap.department = idx;
else if (clean.includes("时间") || clean.includes("createdat")) colMap.createdAt = idx;
else if (clean.includes("ai审批决策") || clean.includes("aidecision") || clean.includes("ai决策")) colMap.aiDecision = idx;
else if (clean.includes("ai审核") || clean.includes("ai意见") || clean.includes("aisummary") || clean.includes("违规详情")) colMap.aiSummary = idx;
else if (clean.includes("人工审批结论") || clean.includes("人工结论") || clean.includes("humanresult")) colMap.humanResult = idx;
else if (clean.includes("人工审批批注") || clean.includes("驳回说明") || clean.includes("驳回原因") || clean.includes("humancomment")) colMap.humanComment = idx;
else if (clean.includes("人机一致性") || clean.includes("一致性") || clean.includes("agreement")) colMap.agreement = idx;
else if (clean.includes("复核定性") || clean.includes("裁决") || clean.includes("verdict")) colMap.verdict = idx;
else if (clean.includes("复核人") || clean.includes("reviewedby")) colMap.reviewedBy = idx;
else if (clean.includes("复核批注") || clean.includes("批注说明") || clean.includes("reviewnote") || clean.includes("note")) colMap.reviewNote = idx;
else if (clean.includes("耗时") || clean.includes("duration")) colMap.durationSeconds = idx;
});
const blocks: ReportBlock[] = [];
const reviews = new ReviewsMap();
const createdDates: string[] = [];
for (let i = 1; i < rawRows.length; i++) {
const row = rawRows[i]!;
const sn = (colMap.sn !== undefined ? row[colMap.sn] : undefined) || `ROW-${i}`;
const recordId = colMap.recordId !== undefined && row[colMap.recordId] !== "—" ? row[colMap.recordId] : undefined;
const template = (colMap.template !== undefined ? row[colMap.template] : undefined) || "未标注模板";
const title = colMap.title !== undefined ? row[colMap.title] : undefined;
const submitter = colMap.submitter !== undefined ? row[colMap.submitter] : undefined;
const department = colMap.department !== undefined ? row[colMap.department] : undefined;
const createdAt = colMap.createdAt !== undefined ? row[colMap.createdAt] : undefined;
if (createdAt && createdAt !== "—") createdDates.push(createdAt.slice(0, 10));
const aiDecision = colMap.aiDecision !== undefined ? row[colMap.aiDecision] : undefined;
const aiSummary = colMap.aiSummary !== undefined ? row[colMap.aiSummary] : undefined;
const humanResult = colMap.humanResult !== undefined ? row[colMap.humanResult] : undefined;
const humanComment = colMap.humanComment !== undefined ? row[colMap.humanComment] : undefined;
let agreement: ReportBlock["agreement"] = "unknown";
const agreementText = colMap.agreement !== undefined ? row[colMap.agreement] ?? "" : "";
if (agreementText.includes("一致") || agreementText.toLowerCase() === "agreed") {
agreement = "agreed";
} else if (agreementText.includes("分歧") || agreementText.toLowerCase() === "diverged") {
agreement = "diverged";
} else if (agreementText.includes("未完结") || agreementText.includes("流转中")) {
agreement = "unknown";
} else {
const aiPol = polarityOf(aiDecision);
const humPol = polarityOf(humanResult);
if (aiPol === "unknown" || humPol === "unknown") agreement = "unknown";
else if (aiPol === humPol) agreement = "agreed";
else agreement = "diverged";
}
const rawVerdict = colMap.verdict !== undefined ? row[colMap.verdict] : undefined;
const verdict = parseVerdictText(rawVerdict);
const reviewedBy = colMap.reviewedBy !== undefined && row[colMap.reviewedBy] !== "—" ? row[colMap.reviewedBy] : undefined;
const reviewNote = colMap.reviewNote !== undefined && row[colMap.reviewNote] !== "—" ? row[colMap.reviewNote] : undefined;
if (verdict || reviewedBy || reviewNote) {
reviews.set({
recordId,
sn,
verdict: verdict ?? (agreement === "agreed" ? "both_correct" : "undecided"),
note: reviewNote,
reviewedBy,
recordedAt: new Date().toISOString()
});
}
const durVal = colMap.durationSeconds !== undefined ? Number(row[colMap.durationSeconds]) : undefined;
blocks.push({
recordId,
sn,
template,
title,
submitter,
department,
createdAt,
durationSeconds: Number.isFinite(durVal) ? durVal : undefined,
aiDecision,
humanResult,
agreement,
aiSummary,
humanComment,
verdict,
reviewedBy,
reviewNote
});
}
createdDates.sort();
const startIso = createdDates[0] ?? new Date().toISOString().slice(0, 10);
const endIso = createdDates[createdDates.length - 1] ?? startIso;
const periodLabel = startIso === endIso ? startIso : `${startIso} ~ ${endIso}`;
const metrics = populateReviewsAndMetrics(blocks, reviews);
return {
period: {
start: startIso,
end: endIso,
label: periodLabel,
month: startIso.slice(0, 7) === endIso.slice(0, 7) ? startIso.slice(0, 7) : undefined
},
corp: {
id: options?.corp?.id ?? "local-ledger",
name: options?.corp?.name ?? "本地台账企业"
},
fetched: {
blocks: true,
templateGroups: true,
performance: metrics.performance !== undefined,
riskStats: false,
riskDetails: false
},
blocks,
templateGroups: metrics.templateGroups,
reviews,
humanAccuracy: metrics.humanAccuracy,
notes: metrics.notes,
performance: metrics.performance
};
}
/**
* 当针对独立 Markdown 文件直接执行 report export 且无预生成台账时,从 Markdown 表格提取构建台账
*/
+170 -110
View File
@@ -9,7 +9,7 @@ import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
type Polarity = "pass" | "reject" | "unknown";
function polarityOf(value: string | undefined): Polarity {
export function polarityOf(value: string | undefined): Polarity {
if (!value) return "unknown";
const text = value.trim();
if (/同意|通过|approve|pass|已支付|审批完成/i.test(text)) return "pass";
@@ -310,109 +310,149 @@ export async function collectReportData(
data.notes.failureRateAvailable = data.performance !== undefined;
data.notes.mismatchCategoriesAvailable = false;
// 4. 人工裁决回填:支持 recordId 精确匹配与 sn 业务自然键匹配
if (data.reviews.size > 0) {
let reviewed = 0;
let diverged = 0;
let aiRight = 0;
let humanRight = 0;
let completedCount = 0;
let completedReviewed = 0;
for (const block of data.blocks) {
if (block.agreement !== "unknown") completedCount += 1;
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: data.reviews.get(block.sn);
if (review) {
block.verdict = review.verdict;
block.reviewNote = review.note;
block.reviewedBy = review.reviewedBy;
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
if (block.agreement !== "unknown") {
completedReviewed += 1;
}
}
if (block.agreement !== "unknown") {
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
aiRight += 1;
humanRight += 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
aiRight += 1;
} else if (v === "human_correct") {
humanRight += 1;
}
}
}
if (reviewed > 0) {
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
data.notes.reviewedCount = completedCount > 0 ? completedCount : reviewed;
data.notes.divergedCount = divergedCount;
if (completedCount > 0) {
data.humanAccuracy = Number(((humanRight / completedCount) * 100).toFixed(2));
data.notes.humanAccuracyAvailable = true;
if (unreviewedDiverged === 0 && data.performance) {
data.performance.approvalCount = completedCount;
data.performance.accuracy = Number(((aiRight / completedCount) * 100).toFixed(2));
data.notes.mismatchCategoriesAvailable = true;
}
}
}
}
// 5. 分模板统计(在 review 挂载后聚合,携带分模板的 AI/人工准确率)
if (demands.has("templateGroups") && data.blocks.length > 0) {
const byTemplate = new Map<string, ReportTemplateGroup>();
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;
}
// 4. 人工裁决回填与分模板指标聚合(支持 recordId 精确匹配与 sn 业务自然键匹配)
const metrics = populateReviewsAndMetrics(data.blocks, data.reviews, data.performance, data.notes);
data.templateGroups = metrics.templateGroups;
data.humanAccuracy = metrics.humanAccuracy;
data.notes = metrics.notes;
data.performance = metrics.performance;
fetched.templateGroups = demands.has("templateGroups") && data.templateGroups.length > 0;
return data;
}
/**
* 核心指标计算引擎:基于单据明细 blocks 与复核裁决集合 reviews,纯计算聚合各模板与全局指标。
* 供 collectReportData(云端拉取)与 loadReportDataFromLedger(本地 Excel/CSV 驱动)共享 100% 一致口径。
*/
export function populateReviewsAndMetrics(
blocks: ReportBlock[],
reviews: ReviewsMap | Map<string, ReviewRecord>,
initialPerformance?: ReportData["performance"],
initialNotes?: Partial<ReportData["notes"]>
): {
templateGroups: ReportTemplateGroup[];
humanAccuracy?: number;
notes: ReportData["notes"];
performance?: ReportData["performance"];
} {
const notes: ReportData["notes"] = {
humanAccuracyAvailable: false,
failureRateAvailable: initialPerformance !== undefined,
mismatchCategoriesAvailable: false,
...initialNotes
};
let performance = initialPerformance;
let reviewed = 0;
let diverged = 0;
let aiRight = 0;
let humanRight = 0;
let completedCount = 0;
for (const block of blocks) {
if (block.agreement !== "unknown") completedCount += 1;
const review = reviews instanceof ReviewsMap
? reviews.get({ recordId: block.recordId, sn: block.sn })
: reviews.get(block.sn);
if (review) {
block.verdict = review.verdict;
block.reviewNote = review.note;
block.reviewedBy = review.reviewedBy;
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
} else if (block.verdict) {
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
}
if (block.agreement !== "unknown") {
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
aiRight += 1;
humanRight += 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
aiRight += 1;
} else if (v === "human_correct") {
humanRight += 1;
}
}
}
let humanAccuracy: number | undefined;
if (reviewed > 0) {
const divergedCount = blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
notes.reviewedCount = completedCount > 0 ? completedCount : reviewed;
notes.divergedCount = divergedCount;
if (completedCount > 0) {
humanAccuracy = Number(((humanRight / completedCount) * 100).toFixed(2));
notes.humanAccuracyAvailable = true;
if (!performance && unreviewedDiverged === 0) {
performance = {
approvalCount: completedCount,
accuracy: Number(((aiRight / completedCount) * 100).toFixed(2)),
sankey: { nodes: [], links: [] }
};
}
if (unreviewedDiverged === 0 && performance) {
performance.approvalCount = completedCount;
performance.accuracy = Number(((aiRight / completedCount) * 100).toFixed(2));
notes.mismatchCategoriesAvailable = true;
}
}
}
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,
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);
}
const templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
return {
templateGroups,
humanAccuracy,
notes,
performance
};
}
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
function summarizeLocal(record: ApprovalRun): {
id: string;
@@ -431,20 +471,25 @@ function summarizeLocal(record: ApprovalRun): {
} {
const result = (record.result ?? {}) as Record<string, unknown>;
const document = (record.document ?? {}) as Record<string, unknown>;
const manual = record.manualApprovalRecord as Record<string, unknown> | undefined;
const manual =
(record.manualApprovalRecord as Record<string, unknown> | undefined) ??
(result.manualApprovalRecord as Record<string, unknown> | undefined) ??
(document.manualApprovalRecord as Record<string, unknown> | undefined);
const manualApproval = result.manualApproval as Record<string, unknown> | undefined;
const pipelineData = record.pipelineData as Record<string, unknown> | undefined;
const aiDecision =
firstString(result.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
firstString(manualApproval?.decision) ??
firstString(manualApproval?.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<string, unknown> | undefined)?.humanResult) ??
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
firstString(manualApproval?.humanResult) ??
firstString(pipelineData?.humanResult);
const fields = (document.fields as Array<{ key?: string; label?: string; value?: unknown }> | undefined) ?? [];
const tField = fields.find(
@@ -469,6 +514,24 @@ function summarizeLocal(record: ApprovalRun): {
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;
const humanComment =
firstString(manual?.rejectComment) ??
firstString(manual?.comment) ??
firstString(manual?.comments) ??
firstString(manual?.opinion) ??
firstString(manual?.approvalComment) ??
firstString(manualApproval?.comment) ??
firstString(manualApproval?.rejectComment) ??
firstString(manualApproval?.opinion) ??
firstString(result.humanComment) ??
firstString(pipelineData?.rejectComment) ??
firstString(pipelineData?.comment);
const aiSummary =
firstString(result.summary) ??
firstString(result.reason) ??
firstString(result.explanation);
return {
id: record.id,
sn: record.sourceDocumentSN,
@@ -480,11 +543,8 @@ function summarizeLocal(record: ApprovalRun): {
durationSeconds,
aiDecision,
humanResult,
aiSummary: firstString(result.summary),
humanComment:
firstString(manual?.rejectComment) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
firstString(result.humanComment),
aiSummary,
humanComment,
conditions: extractTriggeredConditions(result)
};
}
+12 -8
View File
@@ -1,5 +1,6 @@
import type { KyInstance } from "ky";
import { collectReportData } from "./collect.js";
import { loadReportDataFromLedger } from "../export/ledger.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
export type ReportDataOptions = {
@@ -8,6 +9,7 @@ export type ReportDataOptions = {
month?: string;
corp: { id: string; name: string };
templates?: string[];
ledgerPath?: string;
maxRuns?: number;
};
@@ -121,14 +123,16 @@ export async function getMonthlyReportData(
"templateGroups"
]);
const data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
const data = options.ledgerPath
? await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp })
: await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
const total = data.performance?.approvalCount || data.blocks.length || 0;
const rawAiAcc = data.performance?.accuracy;
+22 -12
View File
@@ -9,7 +9,7 @@ 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";
import { buildReportLedgerCsv, buildReportLedgerXlsx, loadReportDataFromLedger } from "../export/ledger.js";
export type ReportOptions = {
startDate?: string;
@@ -18,6 +18,8 @@ export type ReportOptions = {
corp: { id: string; name: string };
/** 单据模板白名单列表(可选,未指定则拉取全量模板) */
templates?: string[];
/** 外部直接传入已编辑的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源,不再查询云端 */
ledgerPath?: string;
/** 模板路径;缺省用仓内内置 monthly.md,随二进制内嵌 */
templatePath?: string;
reportId?: string;
@@ -69,15 +71,20 @@ export async function buildMonthlyReport(
const template = options.templatePath ? readFileSync(templatePath, "utf8") : BUILTIN_MONTHLY_TEMPLATE;
const plans = describeTemplate(template);
const demands = new Set(plans.flatMap((plan) => plan.demands));
const data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
let data: ReportData;
if (options.ledgerPath) {
data = await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp });
} else {
const demands = new Set(plans.flatMap((plan) => plan.demands));
data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
}
const unreviewedDiverged = data.blocks.filter(
(b) => b.agreement === "diverged" && !b.verdict
@@ -88,13 +95,16 @@ export async function buildMonthlyReport(
const periodArg = options.startDate && options.endDate
? `--start-date ${options.startDate} --end-date ${options.endDate}`
: options.month ? `--month ${options.month}` : "";
const tip = options.ledgerPath
? `请在台账文件(${options.ledgerPath})中为这些单据填写“复核定性裁决”列(如:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),或直接剔除不需要的单据/模板行。`
: `请先执行 'seal-use report ledger ${periodArg} --corp ${options.corp.id}' 导出台账并在 Excel 中裁决,或通过 'seal-use report review set' 录入裁决结论。`;
throw new CliError(
`前置业务门禁拦截:检测到 ${unreviewedDiverged.length} 笔人机分歧单据尚未完成复核裁决(如 ${snList}${more})。\n` +
`为保证报告结论的真实性与合规性,出具正式报告前必须完成人机分歧裁决。\n` +
`请先执行 'seal-use report data ${periodArg} --corp ${options.corp.id}' 审查分歧单据,并使用 'seal-use report review set' 录入裁决结论。\n` +
`${tip}\n` +
`(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`,
1,
`seal-use report data ${periodArg} --corp ${options.corp.id}`
options.ledgerPath ? undefined : `seal-use report data ${periodArg} --corp ${options.corp.id}`
);
}
+4 -3
View File
@@ -1,6 +1,7 @@
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
import type { ReportData, ReportBlock } from "./collect.js";
import type { SectionPlan } from "./describe.js";
import { ReviewsMap } from "./review-store.js";
export type RenderOptions = {
/** 报告编号;未给则按 RPT-<YYYYMM>-<6位随机> 生成 */
@@ -552,11 +553,11 @@ function replacementRows(
if (!diverged.length) return null;
return diverged.map((block) => {
const isAiRight = block.verdict === "ai_correct" || block.verdict === "both_correct" || (!block.verdict && block.agreement === "diverged");
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 失准(不计入分子)**";
const reviewNote = data.reviews.get(block.sn)?.note;
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 判定误判(不计入分子)**";
const reviewNote = block.reviewNote ?? (data.reviews instanceof ReviewsMap ? data.reviews.get({ recordId: block.recordId, sn: block.sn }) : (data.reviews as Map<string, any>).get(block.sn))?.note;
const conclusion = (!isAiRight && reviewNote)
? `${reviewNote}(AI原判:${block.aiSummary || "—"})`
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报"));
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报/误判"));
return [
block.sn,
block.template || "—",
@@ -6,7 +6,14 @@ 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";
import {
buildReportLedgerCsv,
buildReportLedgerXlsx,
loadReportDataFromLedger,
parseVerdictText,
formatVerdict,
formatAiOpinion
} from "../export/ledger.js";
import { getMonthlyReportData } from "./data.js";
import { buildMonthlyReport } from "./monthly.js";
@@ -588,6 +595,180 @@ describe("getMonthlyReportData", () => {
expect(group.aiAccuracy).toBe(100);
expect(group.humanAccuracy).toBe(50);
});
test("wording distinction: formatVerdict and parseVerdictText clearly separate document validity from audit correctness", () => {
expect(
formatVerdict({
sn: "1",
template: "T",
agreement: "diverged",
aiDecision: "驳回",
humanResult: "同意",
aiSummary: "超标",
humanComment: undefined,
verdict: "ai_correct"
})
).toBe("AI 判断正确 / 人工判断错误");
expect(
formatVerdict({
sn: "2",
template: "T",
agreement: "diverged",
aiDecision: "驳回",
humanResult: "同意",
aiSummary: "误报",
humanComment: undefined,
verdict: "human_correct"
})
).toBe("人工判断正确 / AI 判定误判");
expect(
formatVerdict({
sn: "3",
template: "T",
agreement: "agreed",
aiDecision: "同意",
humanResult: "同意",
aiSummary: "合规",
humanComment: undefined,
verdict: "both_correct"
})
).toBe("双方判断均正确");
expect(
formatVerdict({
sn: "4",
template: "T",
agreement: "agreed",
aiDecision: "同意",
humanResult: "同意",
aiSummary: "漏检",
humanComment: undefined,
verdict: "both_wrong"
})
).toBe("双方判定均误判");
expect(parseVerdictText("AI正确")).toBe("ai_correct");
expect(parseVerdictText("AI判断正确 / 人工判断错误")).toBe("ai_correct");
expect(parseVerdictText("人工错误")).toBe("ai_correct");
expect(parseVerdictText("人工合理")).toBe("human_correct");
expect(parseVerdictText("人工判断正确 / AI 判定误判")).toBe("human_correct");
expect(parseVerdictText("AI误判")).toBe("human_correct");
expect(parseVerdictText("双方判断均正确")).toBe("both_correct");
expect(parseVerdictText("双方判定均误判")).toBe("both_wrong");
expect(parseVerdictText("存疑待定")).toBe("undecided");
});
test("formatAiOpinion combines summary and triggered conditions into full audit rationale", () => {
const text = formatAiOpinion({
aiSummary: "发票金额超标",
conditions: ["发票金额超出城市报销标准(350元)", "缺少同行人名单"]
});
expect(text).toContain("发票金额超标");
expect(text).toContain("【触发违规/风险项】1. 发票金额超出城市报销标准(350元); 2. 缺少同行人名单");
});
test("ledger round-trip: buildReportLedgerXlsx exports full comments and loadReportDataFromLedger respects Agent edits", async () => {
const tmp = mkdtempSync(join(tmpdir(), "seal-ledger-test-"));
try {
const data = sampleData({
blocks: [
{
recordId: "rec-001",
sn: "SN-001",
template: "差旅报销",
title: "北京出差差旅",
submitter: "张三",
department: "技术部",
createdAt: "2026-08-15 10:00:00",
aiDecision: "驳回",
humanResult: "同意",
agreement: "diverged",
aiSummary: "住宿超标",
conditions: ["超标50元"],
humanComment: "领导特批放行",
verdict: undefined
},
{
recordId: "rec-002",
sn: "SN-002",
template: "采购付款",
title: "办公用品采购",
submitter: "李四",
department: "行政部",
createdAt: "2026-08-18 14:00:00",
aiDecision: "同意",
humanResult: "同意",
agreement: "agreed",
aiSummary: "凭证齐全",
humanComment: "核验无误",
verdict: undefined
}
]
});
// 1. 导出 Excel 台账
const buffer = await buildReportLedgerXlsx(data);
const xlsxFile = join(tmp, "台账.xlsx");
await Bun.write(xlsxFile, buffer);
// 2. 逆向加载台账
const loaded = await loadReportDataFromLedger(xlsxFile);
expect(loaded.blocks).toHaveLength(2);
expect(loaded.blocks[0]!.sn).toBe("SN-001");
expect(loaded.blocks[0]!.humanComment).toBe("领导特批放行");
expect(loaded.blocks[0]!.aiSummary).toContain("超标50元");
// 3. 模拟 Agent 自由编辑台账:直接在 CSV/Excel 中完成裁决,并剔除掉采购付款模板(仅留差旅报销)
const editedCsv = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批放行,分歧,AI判断正确 / 人工判断错误,王总监,特批应走线下签批流程不应线上直接放行,12'
].join("\n");
const csvFile = join(tmp, "台账-edited.csv");
await Bun.write(csvFile, editedCsv);
const loadedEdited = await loadReportDataFromLedger(csvFile);
// 严格尊重 Agent 裁剪:只剩下 1 笔差旅报销,完全没有采购付款
expect(loadedEdited.blocks).toHaveLength(1);
expect(loadedEdited.templateGroups).toHaveLength(1);
expect(loadedEdited.templateGroups[0]!.template).toBe("差旅报销");
// 权威识别已填写的裁决
expect(loadedEdited.blocks[0]!.verdict).toBe("ai_correct");
expect(loadedEdited.blocks[0]!.reviewedBy).toBe("王总监");
expect(loadedEdited.humanAccuracy).toBe(0); // 人工判断错误
expect(loadedEdited.performance?.accuracy).toBe(100); // AI判断正确
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
test("buildMonthlyReport driven directly by --ledger skips remote fetch and validates in-place", async () => {
const tmp = mkdtempSync(join(tmpdir(), "seal-report-ledger-test-"));
try {
// 构造已由 Agent 完成复核的台账
const csv = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,无批注,分歧,AI判断正确 / 人工判断错误,评审专家,AI依据城市差旅标准拦截正确,12',
'rec-002,SN-002,差旅报销,上海出差,李四,市场部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,评审专家,无误,8'
].join("\n");
const csvFile = join(tmp, "台账.csv");
await Bun.write(csvFile, csv);
const fakeClient = {} as never;
const report = await buildMonthlyReport(fakeClient, {
ledgerPath: csvFile,
corp: { id: "corp-ledger", name: "台账驱动测试企业" }
});
expect(report.content).toBeTruthy();
expect(report.notes.humanAccuracyAvailable).toBe(true);
expect(report.dynamicAssets?.["assets/图1-准确率对比.svg"]).toBeTruthy();
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
@@ -50,11 +50,15 @@ export class ReviewsMap {
readonly bySn = new Map<string, ReviewRecord>();
readonly records: ReviewRecord[] = [];
set(key: string, record: ReviewRecord): this {
set(record: ReviewRecord): this;
set(key: string, record: ReviewRecord): this;
set(keyOrRecord: string | ReviewRecord, maybeRecord?: ReviewRecord): this {
const record = typeof keyOrRecord === "string" ? maybeRecord! : keyOrRecord;
const key = typeof keyOrRecord === "string" ? keyOrRecord : record.recordId ?? record.sn ?? "";
this.records.push(record);
if (record.recordId) this.byRecordId.set(record.recordId, record);
if (record.sn) this.bySn.set(record.sn, record);
if (!record.recordId && !record.sn) {
if (!record.recordId && !record.sn && key) {
this.bySn.set(key, record);
}
return this;
+10 -2
View File
@@ -1,6 +1,6 @@
# Report templates
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
企业 AI 审核报告(验收、上线、周期审计)的模板与配套资产(供 `seal-use report generate` / `report monthly` 消费)。
| 文件 | 用途 |
| --- | --- |
@@ -14,11 +14,19 @@
默认模板和配图由本仓库 Git 管理(位于 `src/domains/seal/reports/templates/`),构建时直接内嵌进二进制;无需外置模板目录或已安装的 Skill。模板修改通过 PR 合入,再随构建/发版分发。`--template` 仅用于显式覆盖。
```bash
seal-use report monthly --month 2026-08 --corp <corpId> --out 报告.md
# 模式 A (首选·Excel 台账自由裁量驱动):
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 台账.xlsx
seal-use report generate --ledger 台账.xlsx --corp <corpId> --out 报告.md
# 模式 B (直接时间周期/月度提数驱动):
seal-use report generate --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 报告.md
# 校验与多端渲染:
seal-use report validate 报告.md
seal-use report render 报告.md --out build/报告
```
`monthly --out` 保存 Markdown 和同目录的 `<报告名>.assets/` 配图目录,返回文件路径、数据缺口与后续命令;不指定 `--out` 时继续返回 `content`。自定义模板的本地配图也一并复制。已有文件默认拒绝覆盖,显式 `--overwrite` 才允许替换。通用 `--output-file` 仍只保存 JSON,与 `--out` 不同。
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
@@ -161,7 +161,7 @@ export function validateReportDocument(file: string): ReportValidation {
if (detail) {
if (detail.header.some((col) => col.includes("单号") || col.includes("单据编号"))) {
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
const missed = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("失准")).length
const missed = detail.rows.filter((row) => row.cells.length > 4 && (row.cells[4]!.includes("失准") || row.cells[4]!.includes("误判"))).length
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)