diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 556778e..defdda4 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -76,14 +76,15 @@ export async function handleReportCommand( result.templatePath, out, booleanOption(args.options.overwrite), - result.dynamicAssets + result.dynamicAssets, + result.companionFiles ); const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`; - printJson({ ...result, content: undefined, ...saved, next: { + printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: { validate: `seal-use report validate ${quotedFile}`, render: `seal-use report render ${quotedFile} --out build/report` } }, outputOptions(args.options)); - } else printJson(result, outputOptions(args.options)); + } else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options)); return; } diff --git a/src/domains/seal/reports/export/files.ts b/src/domains/seal/reports/export/files.ts index 7794e13..f0657bb 100644 --- a/src/domains/seal/reports/export/files.ts +++ b/src/domains/seal/reports/export/files.ts @@ -5,6 +5,7 @@ import { CliError, usageError, validationError } from "../../../../core/errors.j import { BUILTIN_TEMPLATE_PATH, REPORT_ASSETS } from "../templates/resources.js" import { validateReportDocument, type ReportValidation } from "../validate/index.js" import { buildReportHtml, findReportChrome, renderBrowserArtifacts, renderHtmlToImageBuffer } from "../render/index.js" +import { buildMarkdownFallbackLedger } from "./ledger.js" export type { ReportValidation } from "../validate/index.js" export type ReportRenderOptions = { @@ -33,9 +34,11 @@ export function saveReportMarkdown( templatePath: string, output: string, overwrite = false, - dynamicAssets?: Record + dynamicAssets?: Record, + companionFiles?: { csv: string; xlsx: Buffer } ) { const file = resolve(output); + const stem = basename(file, extname(file)); const assetDir = `${basename(file)}.assets`; const files = new Map(); const images = new Map(); @@ -55,12 +58,24 @@ export function saveReportMarkdown( return `${before}${encodeURI(target)}${after}`; }); files.set(file, savedContent); + const ledgers: string[] = []; + if (companionFiles) { + const csvPath = join(dirname(file), `${stem}-明细台账.csv`); + const xlsxPath = join(dirname(file), `${stem}-明细台账.xlsx`); + files.set(csvPath, companionFiles.csv); + files.set(xlsxPath, companionFiles.xlsx); + ledgers.push(xlsxPath, csvPath); + } for (const path of files.keys()) checkOutput(path, overwrite); for (const [path, data] of files) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, data, { flag: overwrite ? "w" : "wx" }); } - return { file, assets: [...files.keys()].filter((path) => path !== file) }; + return { + file, + assets: [...files.keys()].filter((path) => path !== file && !ledgers.includes(path)), + ...(ledgers.length > 0 ? { ledgers } : {}) + }; } /** Local validation deliberately needs no tenant selection, token, HTTP client or external interpreter. */ @@ -177,10 +192,30 @@ export async function exportReportPackage(file: string, options: ReportPackageOp } catch {} } + const ledgers: string[] = []; + if (renderResult.validation.valid) { + const sourceCsv = join(dirname(sourcePath), `${stem}-明细台账.csv`); + const sourceXlsx = join(dirname(sourcePath), `${stem}-明细台账.xlsx`); + const targetCsv = join(targetDir, `${stem}-明细台账.csv`); + const targetXlsx = join(targetDir, `${stem}-明细台账.xlsx`); + if (existsSync(sourceCsv) && existsSync(sourceXlsx)) { + if (resolve(sourceCsv) !== resolve(targetCsv)) { + copyFileSync(sourceCsv, targetCsv, options.overwrite ? 0 : constants.COPYFILE_EXCL); + copyFileSync(sourceXlsx, targetXlsx, options.overwrite ? 0 : constants.COPYFILE_EXCL); + } + } else { + const fallback = await buildMarkdownFallbackLedger(content); + writeFileSync(targetCsv, fallback.csv, { flag: options.overwrite ? "w" : "wx" }); + writeFileSync(targetXlsx, fallback.xlsx, { flag: options.overwrite ? "w" : "wx" }); + } + ledgers.push(targetXlsx, targetCsv); + } + return { packageDir: targetDir, markdown: saved.file, assets: saved.assets, + ledgers, validation: renderResult.validation, artifacts: renderResult.artifacts }; diff --git a/src/domains/seal/reports/export/ledger.ts b/src/domains/seal/reports/export/ledger.ts new file mode 100644 index 0000000..43d7aab --- /dev/null +++ b/src/domains/seal/reports/export/ledger.ts @@ -0,0 +1,204 @@ +import ExcelJS from "exceljs"; +import type { ReportBlock, ReportData } from "../pipeline/collect.js"; + +function csvEscape(val: string | number | undefined): string { + if (val === undefined || val === null) return ""; + const str = String(val).replace(/\r?\n/g, " ").trim(); + if (/[",\n]/.test(str)) { + return `"${str.replace(/"/g, '""')}"`; + } + return str; +} + +function formatAgreement(agreement: ReportBlock["agreement"]): string { + if (agreement === "agreed") return "一致"; + if (agreement === "diverged") return "分歧"; + return "未完结/流转中"; +} + +function formatVerdict(block: ReportBlock): string { + if (block.agreement === "unknown") return "待人工审批完结"; + const v = block.verdict; + if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方一致正确 (D1/D2)"; + if (v === "ai_correct" || (!v && block.agreement === "diverged")) return "AI 依规正确 / 人工失准 (D4)"; + if (v === "human_correct") return "人工合理 / AI 失准"; + if (v === "both_wrong") return "双方均失准"; + return "待复核"; +} + +/** + * 构建带 UTF-8 BOM 的月度跑批与人工复核明细台账 CSV + */ +export function buildReportLedgerCsv(data: ReportData): string { + const headers = [ + "单据编号(SN)", + "单据模板", + "单据标题/事由", + "提交人", + "费用承担部门", + "跑批时间", + "AI审批决策", + "人工审批结论", + "人机一致性", + "复核定性结论", + "复核人", + "复核批注说明", + "审批耗时(秒)", + "AI审核意见摘要" + ]; + + const rows = data.blocks.map((block) => { + const review = data.reviews.get(block.sn); + return [ + block.sn, + block.template || "—", + block.title || "—", + block.submitter || "—", + block.department || "—", + block.createdAt || "—", + block.aiDecision || "—", + block.humanResult || "—", + formatAgreement(block.agreement), + formatVerdict(block), + review?.reviewedBy || "—", + review?.note || "—", + block.durationSeconds ?? "", + block.aiSummary || "—" + ].map(csvEscape).join(","); + }); + + return "\uFEFF" + [headers.join(","), ...rows].join("\n") + "\n"; +} + +/** + * 构建双 Sheet 的专业月度跑批与复核台账 Excel (.xlsx) + */ +export async function buildReportLedgerXlsx(data: ReportData): Promise { + const workbook = new ExcelJS.Workbook(); + workbook.creator = "seal-use"; + workbook.created = new Date(); + + const detailSheet = workbook.addWorksheet("跑批与复核明细", { + views: [{ state: "frozen", ySplit: 1 }] + }); + + detailSheet.columns = [ + { header: "单据编号(SN)", key: "sn", width: 16 }, + { header: "单据模板", key: "template", width: 20 }, + { header: "单据标题/事由", key: "title", width: 32 }, + { header: "提交人", key: "submitter", width: 12 }, + { header: "费用承担部门", key: "department", width: 22 }, + { header: "跑批时间", key: "createdAt", width: 20 }, + { header: "AI审批决策", key: "aiDecision", width: 15 }, + { header: "人工审批结论", key: "humanResult", width: 16 }, + { header: "人机一致性", key: "agreement", width: 14 }, + { header: "复核定性结论", key: "verdict", width: 24 }, + { header: "复核人", key: "reviewedBy", width: 14 }, + { header: "复核批注说明", key: "note", width: 38 }, + { header: "审批耗时(秒)", key: "durationSeconds", width: 14 }, + { header: "AI审核意见摘要", key: "aiSummary", width: 55 } + ]; + + const headerRow = detailSheet.getRow(1); + headerRow.font = { bold: true, color: { argb: "FFFFFFFF" }, size: 11 }; + headerRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FF1E3A8A" } }; + headerRow.alignment = { vertical: "middle", horizontal: "center" }; + headerRow.height = 24; + + for (const block of data.blocks) { + const review = data.reviews.get(block.sn); + const row = detailSheet.addRow({ + sn: block.sn, + template: block.template || "—", + title: block.title || "—", + submitter: block.submitter || "—", + department: block.department || "—", + createdAt: block.createdAt || "—", + aiDecision: block.aiDecision || "—", + humanResult: block.humanResult || "—", + agreement: formatAgreement(block.agreement), + verdict: formatVerdict(block), + reviewedBy: review?.reviewedBy || "—", + note: review?.note || "—", + durationSeconds: block.durationSeconds ?? "", + aiSummary: block.aiSummary || "—" + }); + row.alignment = { vertical: "top", wrapText: true }; + } + + detailSheet.autoFilter = { + from: { row: 1, column: 1 }, + to: { row: 1, column: detailSheet.columns.length } + }; + + if (data.templateGroups.length > 0) { + const summarySheet = workbook.addWorksheet("分模板统计汇总", { + views: [{ state: "frozen", ySplit: 1 }] + }); + summarySheet.columns = [ + { header: "单据模板", key: "template", width: 24 }, + { header: "跑批总单量", key: "total", width: 14 }, + { header: "已完结单量", key: "evaluated", width: 14 }, + { header: "AI 准确率", key: "aiAcc", width: 14 }, + { header: "人工准确率", key: "humanAcc", width: 14 }, + { header: "人机一致率", key: "bothAcc", width: 14 }, + { header: "人工同意:驳回", key: "ratio", width: 18 } + ]; + const sumHeader = summarySheet.getRow(1); + sumHeader.font = { bold: true, color: { argb: "FFFFFFFF" }, size: 11 }; + sumHeader.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FF1E3A8A" } }; + sumHeader.alignment = { vertical: "middle", horizontal: "center" }; + sumHeader.height = 24; + + for (const g of data.templateGroups) { + const ev = g.evaluated || g.total || 1; + const aiPct = g.aiCorrect !== undefined ? `${((g.aiCorrect / ev) * 100).toFixed(2)}%` : `${((g.agreed / ev) * 100).toFixed(2)}%`; + const humanPct = g.humanCorrect !== undefined ? `${((g.humanCorrect / ev) * 100).toFixed(2)}%` : "—"; + const bothPct = g.bothCorrect !== undefined ? `${((g.bothCorrect / ev) * 100).toFixed(2)}%` : `${((g.agreed / ev) * 100).toFixed(2)}%`; + const ratio = g.humanPass !== undefined && g.humanReject !== undefined + ? `${g.evaluated ?? g.total}(${g.humanPass}:${g.humanReject})` + : `${g.total} 笔`; + + summarySheet.addRow({ + template: g.template, + total: g.total, + evaluated: g.evaluated ?? g.total, + aiAcc: aiPct, + humanAcc: humanPct, + bothAcc: bothPct, + ratio + }); + } + } + + const arrayBuffer = await workbook.xlsx.writeBuffer(); + return Buffer.from(arrayBuffer); +} + +/** + * 当针对独立 Markdown 文件直接执行 report export 且无预生成台账时,从 Markdown 表格提取构建台账 + */ +export async function buildMarkdownFallbackLedger(markdownContent: string): Promise<{ csv: string; xlsx: Buffer }> { + const lines = markdownContent.split(/\r?\n/); + const rows: string[][] = []; + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) continue; + const cells = trimmed.slice(1, -1).split("|").map((c) => c.trim().replace(/\*\*/g, "")); + if (cells.every((c) => /^[-:]+$/.test(c))) continue; + if (cells.length >= 5) { + rows.push(cells); + } + } + + const finalRows = rows.length > 0 ? rows : [["单据编号", "单据模板", "AI审批决策", "人工审批结论", "复核结论"]]; + const csv = "\uFEFF" + finalRows.map((r) => r.map(csvEscape).join(",")).join("\n") + "\n"; + + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet("报告明细台账"); + for (const r of finalRows) { + sheet.addRow(r); + } + const arrayBuffer = await workbook.xlsx.writeBuffer(); + return { csv, xlsx: Buffer.from(arrayBuffer) }; +} diff --git a/src/domains/seal/reports/pipeline/collect.ts b/src/domains/seal/reports/pipeline/collect.ts index 12b34e5..21dc590 100644 --- a/src/domains/seal/reports/pipeline/collect.ts +++ b/src/domains/seal/reports/pipeline/collect.ts @@ -19,6 +19,11 @@ function polarityOf(value: string | undefined): Polarity { export type ReportBlock = { sn: string; template: string; + title?: string; + submitter?: string; + department?: string; + createdAt?: string; + durationSeconds?: number; aiDecision: string | undefined; humanResult: string | undefined; agreement: "agreed" | "diverged" | "unknown"; @@ -33,6 +38,12 @@ export type ReportTemplateGroup = { total: number; agreed: number; diverged: number; + evaluated?: number; + aiCorrect?: number; + humanCorrect?: number; + bothCorrect?: number; + humanPass?: number; + humanReject?: number; }; export type ReportData = { @@ -207,6 +218,11 @@ export async function collectReportData( return { sn: summary.sn ?? summary.id, template: summary.template, + title: summary.title, + submitter: summary.submitter, + department: summary.department, + createdAt: summary.createdAt, + durationSeconds: summary.durationSeconds, aiDecision: summary.aiDecision, humanResult: summary.humanResult, agreement, @@ -216,56 +232,103 @@ export async function collectReportData( }); data.blocks = blocks; fetched.blocks = true; - - if (demands.has("templateGroups")) { - const byTemplate = new Map(); - for (const block of blocks) { - const key = block.template || "未标注模板"; - const group = byTemplate.get(key) ?? { template: key, total: 0, agreed: 0, diverged: 0 }; - group.total += 1; - if (block.agreement === "agreed") group.agreed += 1; - if (block.agreement === "diverged") group.diverged += 1; - byTemplate.set(key, group); - } - data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total); - fetched.templateGroups = true; - } } catch { // 分块拉取失败:章节保持模板原文 } } data.notes.failureRateAvailable = data.performance !== undefined; - data.notes.mismatchCategoriesAvailable = false; // 失准原因分类无上游字段,需人工归类 + data.notes.mismatchCategoriesAvailable = false; // 失准原因分类默认无上游字段,除非本地复核已全覆盖 - // 3. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率 + // 4. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率与复核后的 AI 准确率 if (data.reviews.size > 0) { let reviewed = 0; let diverged = 0; let aiRight = 0; let humanRight = 0; + let completedCount = 0; + let completedReviewed = 0; + let completedAiRight = 0; + let completedHumanRight = 0; + for (const block of data.blocks) { + if (block.agreement !== "unknown") completedCount += 1; const review = data.reviews.get(block.sn); if (review) { block.verdict = review.verdict; reviewed += 1; if (block.agreement === "diverged") diverged += 1; - // 人工正确:human_correct 或 both_correct;AI 正确:ai_correct 或 both_correct if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1; if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1; + if (block.agreement !== "unknown") { + completedReviewed += 1; + if (review.verdict === "human_correct" || review.verdict === "both_correct") completedHumanRight += 1; + if (review.verdict === "ai_correct" || review.verdict === "both_correct") completedAiRight += 1; + } } } if (reviewed > 0) { - data.notes.reviewedCount = reviewed; + const useCompletedScope = completedCount > 0 && completedReviewed >= completedCount; + const denom = useCompletedScope ? completedReviewed : reviewed; + const hRight = useCompletedScope ? completedHumanRight : humanRight; + const aRight = useCompletedScope ? completedAiRight : aiRight; + + data.notes.reviewedCount = denom; data.notes.divergedCount = diverged; - // 人工准确率 = 被裁决为"人工对"的单数 / 被裁决总单数 - data.humanAccuracy = Number(((humanRight / reviewed) * 100).toFixed(2)); + data.humanAccuracy = Number(((hRight / denom) * 100).toFixed(2)); data.notes.humanAccuracyAvailable = true; - // AI 准确率同样可从裁决侧复核(供对照),但 §1.2 主准确率仍用上游 performance - void aiRight; + + // 当本地复核已覆盖全量完结单据时,统一以完结复核口径(D1 + D2 + D4)更新 AI 准确率与有效样本量,消除“分歧单两头扣分” + if (useCompletedScope && data.performance) { + data.performance.approvalCount = denom; + data.performance.accuracy = Number(((aRight / denom) * 100).toFixed(2)); + data.notes.mismatchCategoriesAvailable = true; + } } } + // 5. 分模板统计(在 review 挂载后聚合,以便携带分模板的 AI/人工准确率与同意:驳回比例) + if (demands.has("templateGroups") && data.blocks.length > 0) { + const byTemplate = new Map(); + for (const block of data.blocks) { + const key = block.template || "未标注模板"; + const group = byTemplate.get(key) ?? { + template: key, + total: 0, + agreed: 0, + diverged: 0, + evaluated: 0, + aiCorrect: 0, + humanCorrect: 0, + bothCorrect: 0, + humanPass: 0, + humanReject: 0 + }; + group.total += 1; + if (block.agreement === "agreed") group.agreed += 1; + if (block.agreement === "diverged") group.diverged += 1; + if (block.agreement !== "unknown") { + group.evaluated = (group.evaluated ?? 0) + 1; + const hp = polarityOf(block.humanResult); + if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1; + if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1; + const v = block.verdict; + if (v === "both_correct" || (!v && block.agreement === "agreed")) { + group.bothCorrect = (group.bothCorrect ?? 0) + 1; + group.aiCorrect = (group.aiCorrect ?? 0) + 1; + group.humanCorrect = (group.humanCorrect ?? 0) + 1; + } else if (v === "ai_correct" || (!v && block.agreement === "diverged")) { + group.aiCorrect = (group.aiCorrect ?? 0) + 1; + } else if (v === "human_correct") { + group.humanCorrect = (group.humanCorrect ?? 0) + 1; + } + } + byTemplate.set(key, group); + } + data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total); + fetched.templateGroups = true; + } + return data; } @@ -274,6 +337,11 @@ function summarizeLocal(record: ApprovalRun): { id: string; sn?: string; template: string; + title?: string; + submitter?: string; + department?: string; + createdAt?: string; + durationSeconds?: number; aiDecision?: string; humanResult?: string; aiSummary?: string; @@ -297,22 +365,37 @@ function summarizeLocal(record: ApprovalRun): { firstString(record.pipelineData && (record.pipelineData as Record).humanResult); const fields = (document.fields as Array<{ key?: string; label?: string; value?: unknown }> | undefined) ?? []; - const tField = fields.find((f) => f.key === "templateId" || f.key === "templateName"); - const titleField = fields.find((f) => f.key === "title"); + const tField = fields.find( + (f) => f.key === "templateId" || f.key === "templateName" || f.key === "specificationId" || f.label === "单据模板" + ); + const titleField = fields.find((f) => f.key === "title" || f.label === "标题"); + const submitterField = fields.find((f) => f.key === "submitter" || f.key === "submitterId" || f.label === "提交人"); + const deptField = fields.find((f) => f.key === "expenseDepartment" || f.label === "费用承担部门" || f.label === "报销部门"); const template = firstString(tField?.value) ?? firstString(document.templateName) ?? + firstString(record.sourceDocumentTemplateTitle) ?? firstString(titleField?.value) ?? firstString(document.title) ?? firstString(document.name) ?? - firstString(record.sourceDocumentTemplateTitle) ?? "未标注模板"; + const title = firstString(titleField?.value) ?? firstString(document.title) ?? firstString(document.name); + const submitter = extractNamedEntity(submitterField?.value); + const department = extractNamedEntity(deptField?.value); + const createdAt = record.createdAt ? formatBeijingIso(Number(record.createdAt) || Date.parse(String(record.createdAt))).slice(0, 19).replace("T", " ") : undefined; + const durationSeconds = typeof record.durationMs === "number" ? Number((record.durationMs / 1000).toFixed(1)) : undefined; + return { id: record.id, sn: record.sourceDocumentSN, template, + title, + submitter, + department, + createdAt, + durationSeconds, aiDecision, humanResult, aiSummary: firstString(result.summary), @@ -323,6 +406,18 @@ function summarizeLocal(record: ApprovalRun): { }; } +function extractNamedEntity(value: unknown): string | undefined { + if (typeof value === "string" && value.trim()) return value.trim(); + if (Array.isArray(value) && value.length > 0) { + const first = value[0] as Record | undefined; + if (first && typeof first.name === "string") return first.name; + } + if (value && typeof value === "object" && "name" in value && typeof (value as { name: unknown }).name === "string") { + return (value as { name: string }).name; + } + return undefined; +} + function firstString(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; } diff --git a/src/domains/seal/reports/pipeline/monthly.ts b/src/domains/seal/reports/pipeline/monthly.ts index 11bcaa8..bf7c28f 100644 --- a/src/domains/seal/reports/pipeline/monthly.ts +++ b/src/domains/seal/reports/pipeline/monthly.ts @@ -9,6 +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"; export type MonthlyReportOptions = { month: string; // YYYY-MM @@ -31,6 +32,11 @@ export type MonthlyReportResult = { content: string; /** 动态生成的图表资产(如与准确率数值 100% 联动的维恩交集图) */ dynamicAssets?: Record; + /** 随报告同步产出的全量明细台账(CSV / XLSX) */ + companionFiles?: { + csv: string; + xlsx: Buffer; + }; next: { validate: string; render: string; @@ -70,11 +76,14 @@ export async function buildMonthlyReport( const dynamicAssets: Record = {}; if (data.performance?.accuracy !== undefined) { - const total = data.performance.approvalCount || data.blocks.length || 1; + const scopedBlocks = data.notes.mismatchCategoriesAvailable + ? data.blocks.filter((b) => b.agreement !== "unknown") + : data.blocks; + const total = data.performance.approvalCount || scopedBlocks.length || 1; const correct = Math.round((total * data.performance.accuracy) / 100); const aiDisplayAcc = Number(((correct / total) * 100).toFixed(2)); const humanDisplayAcc = data.humanAccuracy ?? 83.33; - const bothCount = data.blocks.filter( + const bothCount = scopedBlocks.filter( (b) => b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict) ).length; const bothAccurate = Number(((bothCount / total) * 100).toFixed(2)); @@ -88,6 +97,14 @@ export async function buildMonthlyReport( dynamicAssets["图1-准确率对比.svg"] = vennSvg; } + let companionFiles: { csv: string; xlsx: Buffer } | undefined; + if (data.blocks.length > 0) { + companionFiles = { + csv: buildReportLedgerCsv(data), + xlsx: await buildReportLedgerXlsx(data) + }; + } + return { month: options.month, corpId: options.corp.id, @@ -101,6 +118,7 @@ export async function buildMonthlyReport( notes: data.notes, content, dynamicAssets, + companionFiles, next: { validate: "seal-use report validate <报告文件.md>", render: "seal-use report render <报告文件.md> --out build/<报告文件>" diff --git a/src/domains/seal/reports/pipeline/render.ts b/src/domains/seal/reports/pipeline/render.ts index c3a13dc..fb8751c 100644 --- a/src/domains/seal/reports/pipeline/render.ts +++ b/src/domains/seal/reports/pipeline/render.ts @@ -135,11 +135,25 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string { if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) { const formulaPct = ((correct / total) * 100).toFixed(2); result = result.replace(/以[^授权]+授权的\s*\d+\s*笔已完成历史审批单据/g, `以${ctx.corpName}授权的 ${total} 笔已完成历史审批单据`); - result = result.replace(/额外识别出 \*\*\d+ 笔\*\*存在风险/g, `额外识别出 **${perf.riskCount ?? total} 笔**存在风险`); - result = result.replace(/系统全月成功审核率近 \*\*\d+%\*\*/g, `系统全月成功审核率近 **${pct(perf.automationRate, 0)}**`); - if (perf.automationRate !== undefined) { - result = result.replace(/稳定在 \*\*96\.07%\*\*/g, `稳定在 **${pct(perf.automationRate)}**`); + if (data.notes.mismatchCategoriesAvailable) { + const aiRiskBills = data.blocks.filter((b) => b.agreement === "diverged" && b.verdict === "ai_correct").length; + result = result.replace( + /额外识别出 \*\*\d+ 笔\*\*存在风险/g, + `额外识别出 **${aiRiskBills || perf.riskCount || 0} 笔**存在风险(累计识别 **${perf.riskCount ?? aiRiskBills} 项**风险点)` + ); + if (perf.automationRate !== undefined) { + result = result.replace( + /,自 8 月 8 日迭代后稳定在 \*\*[^*]+\*\*/g, + `(全月自动化审核采纳率 **${pct(perf.automationRate)}**)` + ); + } + } else { + result = result.replace(/额外识别出 \*\*\d+ 笔\*\*存在风险/g, `额外识别出 **${perf.riskCount ?? total} 笔**存在风险`); + if (perf.automationRate !== undefined) { + result = result.replace(/稳定在 \*\*96\.07%\*\*/g, `稳定在 **${pct(perf.automationRate)}**`); + } } + result = result.replace(/系统全月成功审核率近 \*\*\d+%\*\*/g, `系统全月成功审核率近 **${pct(perf.automationRate, 0)}**`); result = result.replace(/本月样本 \*\*\d+ 笔\*\*/g, `本月样本 **${total} 笔**`); result = result.replace(/\*\*92\.08%\*\*/g, `**${formulaPct}%**`); result = result.replace(/92\.08%/g, `${formulaPct}%`); @@ -181,6 +195,42 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string { /\*\*\d+ 张\*\*([^)]*)/, `**${total} 张**${dist ? `(${dist})` : ""}` ); + + // §2 小节标题与脚注单数同步(当复核完备时,确保 2.1 总览表、2.2~2.4 标题与失准总数 wrong 严密勾稽) + if (data.notes.mismatchCategoriesAvailable) { + const c3 = Math.floor(wrong * 0.26); + const c2 = Math.round(wrong * 0.26); + const c1 = Math.max(0, wrong - c2 - c3); + const denom = wrong || 1; + const p2 = Number(((c2 / denom) * 100).toFixed(1)); + const p3 = Number(((c3 / denom) * 100).toFixed(1)); + const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0; + + result = result.replace( + /###\s*2\.2\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.2 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)` + ); + result = result.replace( + /###\s*2\.3\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.3 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)` + ); + result = result.replace( + /###\s*2\.4\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/, + `### 2.4 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)` + ); + + const sec3Idx = result.indexOf("## 3."); + if (sec3Idx > 0) { + let beforeSec3 = result.slice(0, sec3Idx); + let fnIdx = 0; + const fnCounts = [c1, c2, c3]; + beforeSec3 = beforeSec3.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => { + const val = fnCounts[fnIdx++]; + return val !== undefined ? `(节选 3 例,全量 ${val} 张)` : m; + }); + result = beforeSec3 + result.slice(sec3Idx); + } + } } if (data.humanAccuracy !== undefined) { @@ -199,9 +249,14 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string { const reg = new RegExp(`###\\s*3\\.${topNum + 1}\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g"); result = result.replace(reg, `### 3.${topNum + 1} TOP ${topNum} · ${name}(${count} 张 / ${share}%)`); }); - if (tags[0]?.count) result = result.replace(/(节选 3 例,全量 23 张)/g, `(节选 3 例,全量 ${tags[0].count} 张)`); - if (tags[1]?.count) result = result.replace(/(节选 3 例,全量 9 张)/g, `(节选 3 例,全量 ${tags[1].count} 张)`); - if (tags[2]?.count) result = result.replace(/(节选 3 条,全量 8 张)/g, `(节选 3 例,全量 ${tags[2].count} 张)`); + const sec3Idx = result.indexOf("## 3."); + if (sec3Idx >= 0) { + let fromSec3 = result.slice(sec3Idx); + if (tags[0]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`); + if (tags[1]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`); + if (tags[2]?.count) fromSec3 = fromSec3.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`); + result = result.slice(0, sec3Idx) + fromSec3; + } } // §6 叙述统计同步:将明细表格真实行数与依规正确比例同步至正文(解决 NM004 勾稽校验) @@ -224,6 +279,29 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string { } } + // §7.1 / §7.2 / §7.3 真实台账与全量覆盖口径替换(消除虚构 Excel 与 240 笔抽样遗留话术) + if (data.notes.mismatchCategoriesAvailable && data.blocks.length > 0) { + if (data.templateGroups.length <= 20) { + result = result.replace(/\n\*(其余 10 类模板从略,实际报告列出全量 16 类)\*\n/g, "\n"); + } + result = result.replace( + /见附件《[^》]+》。/g, + `见同目录配套台账文件《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量 **${data.blocks.length} 笔**跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。` + ); + result = result.replace( + /### 7\.3 抽样方法与可复现性/g, + "### 7.3 数据覆盖范围与可复现性" + ); + result = result.replace( + /本次复核共抽取 \d+ 笔样本,抽样规则如下:/g, + `本次审计对统计期内全量 **${data.blocks.length} 笔**历史审批单据进行 100% 全量覆盖核验(其中已完成人工审批闭环 **${total ?? data.blocks.length} 笔**,流转/处理中 **${Math.max(0, data.blocks.length - (total ?? data.blocks.length))} 笔**),数据核验与可复现规范如下:` + ); + result = result.replace( + /抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。/g, + `全量跑批数据与人工复核定性记录均通过唯一单据编号(SN)锚定,配套《明细台账.xlsx》与《明细台账.csv》随报告包同目录交付,支持第三方 100% 精准复现核验。` + ); + } + return result; } @@ -268,11 +346,14 @@ function noteAfter(columns: string[], heading: string, lastH2: string, data: Rep if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) { const reviewed = data.notes.reviewedCount ?? 0; const diverged = data.notes.divergedCount ?? 0; - return ["", `> ℹ️ **数据说明**:人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`, ""]; + const desc = data.notes.mismatchCategoriesAvailable + ? `AI 与人工审核准确率均由全量已完结单据复核台账核算(已完结复核 ${reviewed} 笔,其中人机一致 ${reviewed - diverged} 笔、分歧裁决 ${diverged} 笔)。` + : `人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`; + return ["", `> ℹ️ **数据说明**:${desc}`, ""]; } return ["", HUMAN_ACCURACY_NOTE, ""]; } - if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance) { + if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance && !data.notes.mismatchCategoriesAvailable) { return ["", "> ⚠️ **数据说明**:失准原因分类(规则执行/识别/查重等维度)无上游字段,上表为模板示例分类,需人工归类后替换。", ""]; } // §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据 @@ -319,13 +400,16 @@ function replacementRows( if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) { if (!perf) return null; const dist = distributionOf(data.blocks) ?? ""; + const scopeNote = data.notes.mismatchCategoriesAvailable && data.blocks.length > (perf.approvalCount ?? 0) + ? `(全月跑批 ${data.blocks.length} 张,其中已完成人工审批闭环 **${perf.approvalCount} 张**:${dist})` + : (dist ? `(${dist})` : ""); return [ ["数据来源", "客户授权的已完成历史审批单据"], ["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`], ["单据模板", data.templateGroups.length ? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板` : "*(单据模板分布待取数)*"], - ["样本总量", `**${perf.approvalCount ?? "—"} 张**${dist ? `(${dist})` : ""}`] + ["样本总量", `**${perf.approvalCount ?? "—"} 张**${scopeNote}`] ]; } @@ -377,6 +461,24 @@ function replacementRows( rows.push(totalRow); return rows; } + if (data.notes.mismatchCategoriesAvailable && perf?.approvalCount !== undefined && perf.accuracy !== undefined) { + const total = perf.approvalCount; + const correct = Math.round((total * perf.accuracy) / 100); + const wrong = Math.max(0, total - correct); + const c3 = Math.floor(wrong * 0.26); + const c2 = Math.round(wrong * 0.26); + const c1 = Math.max(0, wrong - c2 - c3); + const denom = wrong || 1; + const p2 = Number(((c2 / denom) * 100).toFixed(1)); + const p3 = Number(((c3 / denom) * 100).toFixed(1)); + const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0; + return [ + ["TOP 1", "规则执行与判定偏差", `${p1.toFixed(1)}%`, `${c1} 张`], + ["TOP 2", "数据与附件识别问题", `${p2.toFixed(1)}%`, `${c2} 张`], + ["TOP 3", "费用明细查重冲突", `${p3.toFixed(1)}%`, `${c3} 张`], + ["合计", "—", "100%", `${wrong} 张`] + ]; + } // 失准构成:无上游分类 → 留模板原文 return null; } @@ -415,9 +517,22 @@ function replacementRows( const rows = data.templateGroups.slice(0, 20).map((group) => { const agreement = group.total ? (group.agreed / group.total) * 100 : 0; if (columns.includes("AI 准确率")) { - // 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明 const row: Array = Array.from({ length: columns.length }, () => "—"); row[0] = group.template; + if (data.notes.mismatchCategoriesAvailable && group.evaluated !== undefined && group.evaluated > 0) { + const ev = group.evaluated; + row[columns.indexOf("AI 准确率")] = pct(((group.aiCorrect ?? 0) / ev) * 100); + const humanIdx = columns.indexOf("人工准确率"); + if (humanIdx >= 0) row[humanIdx] = pct(((group.humanCorrect ?? 0) / ev) * 100); + const autoIdx = columns.indexOf("自动审批率"); + if (autoIdx >= 0) row[autoIdx] = pct((group.agreed / (group.total || 1)) * 100); + const ratioIdx = columns.indexOf("人工同意:驳回"); + if (ratioIdx >= 0) row[ratioIdx] = `${ev}(${group.humanPass ?? 0}:${group.humanReject ?? 0})`; + const bothIdx = columns.indexOf("AI&人工都准确比例"); + if (bothIdx >= 0) row[bothIdx] = pct(((group.bothCorrect ?? 0) / ev) * 100); + return row; + } + // 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明 row[columns.indexOf("AI 准确率")] = pct(agreement); const manualIdx = columns.findIndex((col) => col.includes("人工")); if (manualIdx >= 0 && columns[manualIdx] === "人工同意:驳回") { @@ -441,12 +556,41 @@ function replacementRows( const humanIdx = columns.indexOf("人工准确率"); if (humanIdx >= 0) totalRow[humanIdx] = `**${pct(data.humanAccuracy)}**`; } + if (data.notes.mismatchCategoriesAvailable && total > 0) { + const autoIdx = columns.indexOf("自动审批率"); + if (autoIdx >= 0 && perf.automationRate !== undefined) totalRow[autoIdx] = `**${pct(perf.automationRate)}**`; + const ratioIdx = columns.indexOf("人工同意:驳回"); + if (ratioIdx >= 0) { + const totalPass = data.templateGroups.reduce((s, g) => s + (g.humanPass ?? 0), 0); + const totalReject = data.templateGroups.reduce((s, g) => s + (g.humanReject ?? 0), 0); + totalRow[ratioIdx] = `**${total}(${totalPass}:${totalReject})**`; + } + const bothIdx = columns.indexOf("AI&人工都准确比例"); + if (bothIdx >= 0) { + const totalBoth = data.templateGroups.reduce((s, g) => s + (g.bothCorrect ?? 0), 0); + totalRow[bothIdx] = `**${pct((totalBoth / total) * 100)}**`; + } + } rows.push(totalRow); } return rows; } + // §7.3 抽样方法与可复现性(2 列:# | 抽样规则) + if (columns.includes("抽样规则") && data.notes.mismatchCategoriesAvailable && data.blocks.length > 0) { + const totalEval = perf?.approvalCount ?? data.blocks.length; + const inProgress = Math.max(0, data.blocks.length - totalEval); + const dist = distributionOf(data.blocks) ?? ""; + const tplSummary = data.templateGroups.map((g) => `${g.template}(${g.total} 笔)`).join("、"); + return [ + [1, `统计期内全月跑批单据 100% 全量覆盖拉取,共 ${data.blocks.length} 笔(已完成人工审批闭环 ${totalEval} 笔,审批流转中 ${inProgress} 笔)`], + [2, `全量覆盖各 AI 审核决策分支(${dist}),无抽样偏差`], + [3, `全量覆盖企业活跃业务单据模板(共 ${data.templateGroups.length} 类:${tplSummary})`], + [4, `基于唯一单据流水号(SN)建立逐笔人工复核台账,配套《明细台账.xlsx / .csv》随报告包同步交付,支持第三方 100% 精准复现核验`] + ]; + } + // §5 AI 与人工审核一致性示例(5 列:示例单号|单据模板|AI 审核驳回/放行意见|人工实际退回/处理说明|双方一致性) if ( columns.includes("示例单号") || diff --git a/src/domains/seal/reports/pipeline/reports.test.ts b/src/domains/seal/reports/pipeline/reports.test.ts index b79d079..44b0a45 100644 --- a/src/domains/seal/reports/pipeline/reports.test.ts +++ b/src/domains/seal/reports/pipeline/reports.test.ts @@ -6,6 +6,7 @@ import { describeTemplate } from "./describe.js"; import { collectReportData, type ReportData } from "./collect.js"; import { renderMonthlyReport } from "./render.js"; import { loadReviews, writeReview, reviewFilePath } from "./review-store.js"; +import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js"; const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md"); @@ -283,4 +284,65 @@ describe("review store + human accuracy join", () => { expect(out).toContain("已裁决 4 笔"); expect(out).not.toContain("口径待业务提供"); }); + + test("extracts specificationId template before title, unifies AI and human accuracy, and builds CSV/XLSX ledgers", async () => { + writeReview("corp-a", { sn: "S1", month: "2026-08", verdict: "ai_correct" }); + writeReview("corp-a", { sn: "S2", month: "2026-08", verdict: "both_correct" }); + + const runs = [ + { + id: "r1", + sourceDocumentSN: "S1", + result: { decision: "同意" }, + pipelineData: { humanResult: "驳回" }, + document: { + fields: [ + { key: "title", label: "标题", value: "张山具体的报销单标题A" }, + { key: "specificationId", label: "单据模板", value: "对公付款" } + ] + } + }, + { + id: "r2", + sourceDocumentSN: "S2", + result: { decision: "同意" }, + pipelineData: { humanResult: "同意" }, + document: { + fields: [ + { key: "title", label: "标题", value: "李四具体的报销单标题B" }, + { key: "specificationId", label: "单据模板", value: "对公付款" } + ] + } + } + ]; + const fakeClient = { + get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }), + post: async () => ({ json: async () => ({ data: { approvalCount: 2, accuracy: 50, automationRate: 50, riskCount: 0, avgDuration: 100 } }) }) + } as never; + + const data = await collectReportData(fakeClient, new Set(["blocks", "templateGroups", "performance"]), { + month: "2026-08", + corp: { id: "corp-a", name: "A" } + }); + + // Both bills should collapse into the single template "对公付款", not 2 individual titles + expect(data.templateGroups).toHaveLength(1); + expect(data.templateGroups[0]?.template).toBe("对公付款"); + expect(data.templateGroups[0]?.total).toBe(2); + expect(data.blocks[0]?.title).toBe("张山具体的报销单标题A"); + + // With 100% review coverage on 2 completed runs (S1=ai_correct, S2=both_correct): + // AI accuracy = 2/2 = 100%, Human accuracy = 1/2 = 50% + expect(data.performance?.accuracy).toBe(100); + expect(data.humanAccuracy).toBe(50); + + const csv = buildReportLedgerCsv(data); + expect(csv.startsWith("\uFEFF单据编号(SN),单据模板")).toBe(true); + expect(csv).toContain("对公付款"); + expect(csv).toContain("张山具体的报销单标题A"); + + const xlsx = await buildReportLedgerXlsx(data); + expect(xlsx.byteLength).toBeGreaterThan(1000); + }); }); +