Refine report pipeline data collection and rendering consistency

This commit is contained in:
gitea committed 2026-10-12 23:18:28 +08:00
1 parent 87b691bd4e
commit 9ef38cda0f
2 files changed
+139 -36

No files matched your search

+29 -12
View File
@@ -11,7 +11,7 @@ type Polarity = "pass" | "reject" | "unknown";
function polarityOf(value: string | undefined): Polarity {
if (!value) return "unknown";
const text = value.trim();
if (/同意|通过|approve|pass/i.test(text)) return "pass";
if (/同意|通过|approve|pass|已支付|审批完成/i.test(text)) return "pass";
if (/驳回|拒绝|终止|退回|reject|deny/i.test(text)) return "reject";
return "unknown";
}
@@ -81,12 +81,16 @@ export type CollectOptions = {
loadReviews?: boolean;
};
function monthRange(month: string): { startDate: string; endDate: string } {
function monthRange(month: string): { startDate: string; endDate: string; startIsoDate: string; endIsoDate: string } {
const [y, m] = month.split("-").map(Number);
if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`);
const start = Date.UTC(y, m - 1, 1);
const end = Date.UTC(y, m, 1) - 1;
return { startDate: String(start), endDate: String(end) };
const lastDay = new Date(y, m, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
const startIsoDate = `${y}-${pad(m)}-01`;
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
return { startDate: String(start), endDate: String(end), startIsoDate, endIsoDate };
}
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
@@ -152,16 +156,16 @@ export async function collectReportData(
if (demands.has("riskStats") || demands.has("riskDetails")) {
try {
const stats = await api.getInsightStats(client, {
startDate: range.startDate,
endDate: range.endDate,
startDate: range.startIsoDate,
endDate: range.endIsoDate,
limit: 50
});
const rawList = ((stats as { tags?: unknown }).tags ?? (stats as { list?: unknown }).list ?? []) as Array<Record<string, unknown>>;
const tagStats = stats.tagStats ?? [];
data.riskStats = {
tags: rawList.slice(0, 20).map((tag) => ({
id: typeof tag.id === "string" ? tag.id : undefined,
name: typeof tag.name === "string" ? tag.name : typeof tag.title === "string" ? tag.title : undefined,
count: typeof tag.count === "number" ? tag.count : typeof tag.value === "number" ? tag.value : undefined
tags: tagStats.slice(0, 20).map((tag) => ({
id: tag.tagId,
name: tag.tagName,
count: tag.count
}))
};
fetched.riskStats = true;
@@ -277,22 +281,33 @@ 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 aiDecision =
firstString(result.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
const manualStatusObj = manual?.status as { label?: string; type?: string } | undefined;
const humanResult =
firstString(manualStatusObj?.label) ??
firstString(manualStatusObj?.type) ??
firstString(result.humanResult) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).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 template =
firstString(tField?.value) ??
firstString(document.templateName) ??
firstString(titleField?.value) ??
firstString(document.title) ??
firstString(document.name) ??
"";
firstString(record.sourceDocumentTemplateTitle) ??
"未标注模板";
return {
id: record.id,
@@ -301,7 +316,9 @@ function summarizeLocal(record: ApprovalRun): {
aiDecision,
humanResult,
aiSummary: firstString(result.summary),
humanComment: firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
humanComment:
firstString(manual?.rejectComment) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
firstString(result.humanComment)
};
}
+110 -24
View File
@@ -94,7 +94,7 @@ export function renderMonthlyReport(
}
flushTable();
out.push(fillInline(raw, data, ctx));
out.push(raw);
}
flushTable();
@@ -111,7 +111,15 @@ export function renderMonthlyReport(
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
let result = text;
const monthNum = parseInt(data.period.month.slice(5), 10);
const monthStr = Number.isFinite(monthNum) ? `${monthNum}月` : "";
if (monthStr) {
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】${monthStr}AI审核准确率报告`);
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, `《${monthStr}单据审批质量审计报告_全量看板.xlsx》`);
}
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
result = result.replaceAll("模板企业", ctx.corpName);
result = result.replace(/(\| 客户名称 \| )[^\n|]+/, `$1${ctx.corpName}`);
result = result.replace(/RPT-\d{6}-[A-Z0-9]+/, ctx.reportId);
if (ctx.reportStatus) result = result.replace(/(报告状态\s*\|\s*)[^\n|]+/, `$1${ctx.reportStatus}`);
@@ -125,40 +133,46 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
// §1 摘要与叙述行:把模板里的占位样本量/准确率换成真实值
if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) {
result = result.replace(/\*\*\d+ 笔\*\*/, `**${total} 笔**`);
result = result.replace(/\*\*\d{3} 笔\*\*/, `**${total} 笔**`);
result = result.replace(/\*\*9\d\.\d\d%\*\*/g, `**${pct(acc)}**`);
result = result.replace(/92\.08%/g, pct(acc));
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)}**`);
}
result = result.replace(/本月样本 \*\*\d+ 笔\*\*/g, `本月样本 **${total} 笔**`);
result = result.replace(/\*\*92\.08%\*\*/g, `**${formulaPct}%**`);
result = result.replace(/92\.08%/g, `${formulaPct}%`);
result = result.replace(/240 笔/g, `${total} 笔`);
// §2 叙述:模板里"依规综合正确 N 单(X%)"与"失准共 M 单(Y%)"是硬编码占位,
// 用结构化模式匹配(不依赖具体数字),换成真实 correct/wrong。
result = result.replace(
/依规综合正确 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
`依规综合正确 **${correct} 单(${pct(acc)})**`
`依规综合正确 **${correct} 单(${formulaPct}%)**`
);
result = result.replace(
/综合失准共 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
`综合失准共 **${wrong} 单(${pct(100 - acc)})**`
`综合失准共 **${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)**`
);
// 无加粗的裸形式
result = result.replace(
/依规综合正确 \d+ 单(\d+(?:\.\d+)?%)/g,
`依规综合正确 ${correct} 单(${pct(acc)})`
`依规综合正确 ${correct} 单(${formulaPct}%)`
);
result = result.replace(
/综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g,
`综合失准共 ${wrong} 单(${pct(100 - acc)})`
`综合失准共 ${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)`
);
result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`);
result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`);
// 公式代入值:\frac{N}{M} = X% 结构化匹配
result = result.replace(
/= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g,
`= \\frac{${correct}}{${total}} = ${acc.toFixed(2)}\\%`
`= \\frac{${correct}}{${total}} = ${formulaPct}\\%`
);
result = result.replace(
/\d+\/\d+ = \d+(?:\.\d+)?%/g,
`${correct}/${total} = ${pct(acc)}`
`${correct}/${total} = ${formulaPct}%`
);
result = result.replace(/N = 240/g, `N = ${total}`);
// 样本总量:真实单量 + 决策分布(无人工明细时只报总样本)
@@ -169,6 +183,44 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
);
}
if (data.humanAccuracy !== undefined) {
result = result.replace(/\*\*83\.33%\*\*/g, `**${pct(data.humanAccuracy)}**`);
}
// §3 小节标题同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验)
if (data.fetched.riskStats && data.riskStats?.tags.length) {
const tags = data.riskStats.tags.filter((t) => t.count !== undefined).slice(0, 3);
const totalRisk = tags.reduce((sum, t) => sum + (t.count ?? 0), 0) || 1;
tags.forEach((tag, idx) => {
const topNum = idx + 1;
const count = tag.count ?? 0;
const share = ((count / totalRisk) * 100).toFixed(1);
const name = tag.name ?? `TOP ${topNum} 风险`;
const reg = new RegExp(`###\\s*3\\.${topNum + 1}\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g");
result = result.replace(reg, `### 3.${topNum + 1} TOP ${topNum} · ${name}(${count} 张 / ${share}%)`);
});
}
// §6 叙述统计同步:将明细表格真实行数与依规正确比例同步至正文(解决 NM004 勾稽校验)
const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged").slice(0, 10);
if (divergedBlocks.length > 0) {
const totalSample = divergedBlocks.length;
const correctSample = divergedBlocks.filter((b) => b.verdict === "ai_correct" || (!b.verdict && b.agreement === "diverged")).length;
const missedSample = totalSample - correctSample;
const correctShare = ((correctSample / totalSample) * 100).toFixed(1);
result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${totalSample} 笔**单据中:`);
result = result.replace(
/\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g,
`**${correctShare}%(${correctSample} / ${totalSample} 笔)属于依规正确(计入 D4)**`
);
result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${missedSample} 笔属于 AI 真实失准`);
if (total) {
const missedShare = ((missedSample / total) * 100).toFixed(2);
result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${missedShare}%)`);
}
}
return result;
}
@@ -222,7 +274,11 @@ function noteAfter(columns: string[], heading: string, lastH2: string, data: Rep
}
// §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,或「原因分类/复核结论」需人工归类;上表为模板示例行,请以真实明细替换。", ""];
const hasDiverged = data.blocks.some((b) => b.agreement === "diverged");
if (!hasDiverged) {
return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,上表为模板示例行,请以真实明细替换。", ""];
}
return [];
}
return [];
}
@@ -241,13 +297,17 @@ function replacementRows(
// §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行)
if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) {
if (!data.fetched.performance || !perf) return null;
const total = perf.approvalCount;
const acc = perf.accuracy;
const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined;
const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc;
const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined
? `**${pct(data.humanAccuracy)}**`
: sampleRows.length > 1
? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*")
: "*(口径待业务提供)*";
return [
["AI 审核", `**${pct(perf.accuracy)}**`],
["AI 审核", `**${pct(displayAcc)}**`],
["人工审核", humanCell]
];
}
@@ -277,8 +337,12 @@ function replacementRows(
// §4 综合效益
if (columns.includes("维度") && columns.includes("结论") && columns.includes("关键数据") && perf) {
const total = perf.approvalCount;
const acc = perf.accuracy;
const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined;
const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc;
return [
["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(perf.accuracy)}**`],
["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(displayAcc)}**`],
["时效", "AI 审核单张单据平均耗时", perf.avgDurationSeconds !== undefined ? `平均 **${perf.avgDurationSeconds.toFixed(1)} 秒**` : "—"],
["风险拦截", "在人工审核通过的单据中,AI 有效防堵的凭证与资金隐患", perf.riskCount !== undefined ? `${perf.riskCount} 笔` : "—"],
["工作量", "协助财务人员弥补遗漏、聚焦高价值工作", "—"]
@@ -319,15 +383,20 @@ function replacementRows(
if (!data.blocks.length) return null;
const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10);
if (!diverged.length) return null;
return diverged.map((block) => [
block.sn,
block.template || "—",
block.aiDecision ?? "—",
block.humanResult ?? "—",
"*(原因分类待人工归类)*",
block.aiSummary ?? "—",
"(截图)"
]);
return diverged.map((block) => {
const isAiRight = block.verdict === "ai_correct" || (!block.verdict && block.agreement === "diverged");
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 失准(不计入分子)**";
const conclusion = block.aiSummary || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报");
return [
block.sn,
block.template || "—",
block.aiDecision ?? "—",
block.humanResult ?? "—",
category,
conclusion,
"(截图)"
];
});
}
// §7.1 分模板统计(只认明确带"模板"或 6 列且有"AI 准确率"的表头;不吃掉一致性示例的 5 列表)
@@ -337,7 +406,7 @@ function replacementRows(
) {
if (!data.fetched.templateGroups) return null;
if (!data.templateGroups.length) return null;
return data.templateGroups.slice(0, 20).map((group) => {
const rows = data.templateGroups.slice(0, 20).map((group) => {
const agreement = group.total ? (group.agreed / group.total) * 100 : 0;
if (columns.includes("AI 准确率")) {
// 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明
@@ -353,6 +422,23 @@ function replacementRows(
if (columns.length >= 2) return [group.template, group.total];
return [group.template];
});
if (columns.includes("AI 准确率") && perf?.approvalCount) {
const total = perf.approvalCount;
const acc = perf.accuracy;
const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined;
const displayAcc = total && correct ? Number(((correct / total) * 100).toFixed(2)) : acc;
const totalRow: Array<string | number> = Array.from({ length: columns.length }, () => "—");
totalRow[0] = `**全量样本总体(N=${total})**`;
totalRow[columns.indexOf("AI 准确率")] = `**${pct(displayAcc)}**`;
if (data.humanAccuracy !== undefined) {
const humanIdx = columns.indexOf("人工准确率");
if (humanIdx >= 0) totalRow[humanIdx] = `**${pct(data.humanAccuracy)}**`;
}
rows.push(totalRow);
}
return rows;
}
return null;