Turn on noUnusedLocals/noUnusedParameters so the compiler keeps flagging dead symbols, then clear the 737 findings it reports: unused imports across src/, unused parameters, unreachable locals, and the copy-pasted 135-line import prologues in the seal tool modules (each tool file now imports only what it uses). Also applies the equivalent-safe lint rewrites (Array.from instead of new Array(n).fill, non-null assertions in tests after toBeDefined, simplified spreads, unused catch params) that oxlint will gate in a later commit.
385 lines
14 KiB
TypeScript
385 lines
14 KiB
TypeScript
import { existsSync, mkdirSync, statSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { dirname, resolve } from "node:path";
|
|
import ExcelJS from "exceljs";
|
|
import type { KyInstance } from "ky";
|
|
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
|
import type { CorpConfig } from "../../core/config/types.js";
|
|
import * as api from "./api.js";
|
|
import { getBeijingDate, resolveExportDateRange } from "./approval-runs-export.js";
|
|
import type { InsightPerformance } from "./types.js";
|
|
|
|
export interface InsightExportOptions {
|
|
startDate?: string | number;
|
|
endDate?: string | number;
|
|
limit?: number;
|
|
outputFile?: string;
|
|
toDownloads?: boolean;
|
|
force?: boolean;
|
|
}
|
|
|
|
export interface InsightExportResult {
|
|
filePath: string;
|
|
corpId: string;
|
|
corpName: string;
|
|
totalRisks: number;
|
|
tagCount: number;
|
|
riskDetailCount: number;
|
|
fileSizeBytes: number;
|
|
exportedAt: string;
|
|
}
|
|
|
|
export function resolveInsightOutputFilePath(options: {
|
|
outputFile?: string;
|
|
toDownloads?: boolean;
|
|
corpName?: string;
|
|
corpId?: string;
|
|
dateTag?: string;
|
|
}): string {
|
|
if (options.outputFile) {
|
|
const customPath = resolve(options.outputFile);
|
|
const parentDir = dirname(customPath);
|
|
if (!existsSync(parentDir)) {
|
|
mkdirSync(parentDir, { recursive: true });
|
|
}
|
|
return customPath;
|
|
}
|
|
|
|
const name = options.corpName || options.corpId || "企业";
|
|
const safeCorpName = name.replace(/[/\\?%*:|"<>]/g, "_").trim() || "企业";
|
|
const dateTag = options.dateTag || getBeijingDate(0);
|
|
const fileName = `${safeCorpName}_智能洞察报告_${dateTag}.xlsx`;
|
|
|
|
let targetDir: string;
|
|
if (options.toDownloads) {
|
|
targetDir = resolve(homedir(), "Downloads");
|
|
} else {
|
|
targetDir = resolve(process.cwd(), "exports");
|
|
}
|
|
|
|
if (!existsSync(targetDir)) {
|
|
mkdirSync(targetDir, { recursive: true });
|
|
}
|
|
|
|
return resolve(targetDir, fileName);
|
|
}
|
|
|
|
export async function exportInsightReportToExcel(
|
|
client: KyInstance,
|
|
corp: CorpConfig,
|
|
options: InsightExportOptions = {}
|
|
): Promise<InsightExportResult> {
|
|
const corpName = corp.name || corp.id;
|
|
const dateRange = resolveExportDateRange({
|
|
startDate: options.startDate,
|
|
endDate: options.endDate,
|
|
force: options.force
|
|
});
|
|
const exportedAt = formatBeijingIso();
|
|
|
|
// 1. 并发拉取基础统计与性能指标
|
|
const [stats, perf] = await Promise.all([
|
|
api.getInsightStats(client, {
|
|
startDate: dateRange.startDateStr,
|
|
endDate: dateRange.endDateStr,
|
|
limit: options.limit ?? 100
|
|
}),
|
|
api.getInsightPerformance(client, {
|
|
startDate: dateRange.startDateStr,
|
|
endDate: dateRange.endDateStr
|
|
}).catch((): InsightPerformance => ({
|
|
metrics: {},
|
|
sankeyData: { nodes: [], links: [] }
|
|
}))
|
|
]);
|
|
|
|
// 2. 按标签下钻拉取具体的风险单据明细
|
|
const tagStats = stats.tagStats || [];
|
|
const riskDetailRows: Array<{
|
|
tagId: string;
|
|
tagName: string;
|
|
documentSN: string;
|
|
documentType: string;
|
|
riskLevel: string;
|
|
confidence: number;
|
|
riskDetails: string;
|
|
reasoning: string;
|
|
sourceDocumentURL?: string | null;
|
|
createdAt?: string | number | Date;
|
|
}> = [];
|
|
|
|
const maxTagsForDetails = Math.min(tagStats.length, options.limit ?? 50);
|
|
for (let i = 0; i < maxTagsForDetails; i++) {
|
|
const tag = tagStats[i];
|
|
if (!tag?.tagId) continue;
|
|
try {
|
|
const risksResult = await api.getInsightRisksByTag(client, {
|
|
tagId: tag.tagId,
|
|
startDate: dateRange.startDateStr,
|
|
endDate: dateRange.endDateStr
|
|
});
|
|
for (const r of risksResult.risks || []) {
|
|
riskDetailRows.push({
|
|
tagId: tag.tagId,
|
|
tagName: tag.tagName || tag.tagId,
|
|
documentSN: r.documentSN || "-",
|
|
documentType: r.documentType || "-",
|
|
riskLevel: r.riskLevel || "warning",
|
|
confidence: r.confidence ?? 0,
|
|
riskDetails: r.riskDetails || "-",
|
|
reasoning: r.reasoning || "-",
|
|
sourceDocumentURL: r.sourceDocumentURL,
|
|
createdAt: r.createdAt
|
|
});
|
|
}
|
|
} catch {
|
|
// 容错处理:单个标签下钻失败不中断整个报表生成
|
|
}
|
|
}
|
|
|
|
// 3. 构建 Excel Workbook
|
|
const workbook = new ExcelJS.Workbook();
|
|
workbook.creator = "seal-use";
|
|
workbook.lastModifiedBy = "seal-use";
|
|
workbook.created = new Date();
|
|
workbook.modified = new Date();
|
|
|
|
const headerFill: ExcelJS.Fill = {
|
|
type: "pattern",
|
|
pattern: "solid",
|
|
fgColor: { argb: "FF1E293B" } // Slate 800
|
|
};
|
|
|
|
const headerFont: Partial<ExcelJS.Font> = {
|
|
name: "Microsoft YaHei",
|
|
size: 11,
|
|
bold: true,
|
|
color: { argb: "FFFFFFFF" }
|
|
};
|
|
|
|
const borderStyle: Partial<ExcelJS.Borders> = {
|
|
top: { style: "thin", color: { argb: "FFE2E8F0" } },
|
|
bottom: { style: "thin", color: { argb: "FFE2E8F0" } },
|
|
left: { style: "thin", color: { argb: "FFE2E8F0" } },
|
|
right: { style: "thin", color: { argb: "FFE2E8F0" } }
|
|
};
|
|
|
|
// -------------------------------------------------------------
|
|
// Sheet 1: 审核效能概览与决策流向
|
|
// -------------------------------------------------------------
|
|
const overviewSheet = workbook.addWorksheet("审核效能与决策流向", {
|
|
views: [{ showGridLines: true }]
|
|
});
|
|
|
|
overviewSheet.columns = [
|
|
{ header: "分类", key: "category", width: 20 },
|
|
{ header: "指标名称", key: "name", width: 28 },
|
|
{ header: "数值", key: "val", width: 22 },
|
|
{ header: "环比/趋势", key: "trend", width: 18 },
|
|
{ header: "说明", key: "desc", width: 36 }
|
|
];
|
|
|
|
overviewSheet.getRow(1).height = 28;
|
|
overviewSheet.getRow(1).font = headerFont;
|
|
overviewSheet.getRow(1).fill = headerFill;
|
|
overviewSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
|
|
|
|
const m = perf.metrics || {};
|
|
const overviewData = [
|
|
{ category: "基本信息", name: "企业名称", val: corpName, trend: "-", desc: `企业 ID: ${corp.id}` },
|
|
{ category: "基本信息", name: "报告生成时间", val: new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }), trend: "-", desc: "Seal AI 自动生成" },
|
|
{ category: "风险大盘", name: "发现风险总数", val: stats.totalRisks ?? 0, trend: "-", desc: `已分析 ${stats.analyzedRisks ?? 0} 项,待处理 ${stats.pendingRisks ?? 0} 项` },
|
|
{ category: "核心效能", name: "累计审核单据量", val: m.approvalCount?.value ?? "-", trend: m.approvalCount?.trend !== undefined ? `${m.approvalCount.trend}%` : "-", desc: "所选统计周期内" },
|
|
{ category: "核心效能", name: "AI 审核准确率", val: m.accuracy?.value !== undefined ? `${m.accuracy.value}%` : "-", trend: m.accuracy?.trend !== undefined ? `${m.accuracy.trend}%` : "-", desc: "人工与 AI 决策一致比率" },
|
|
{ category: "核心效能", name: "自动审核采纳率", val: m.automationRate?.value !== undefined ? `${m.automationRate.value}%` : "-", trend: m.automationRate?.trend !== undefined ? `${m.automationRate.trend}%` : "-", desc: "自动通过或无需人工干预占比" },
|
|
{ category: "核心效能", name: "平均审核耗时", val: m.avgDuration?.value !== undefined ? `${Math.round(m.avgDuration.value * 10) / 10} 秒` : "-", trend: m.avgDuration?.trend !== undefined ? `${m.avgDuration.trend}%` : "-", desc: "单张单据审核端到端耗时" }
|
|
];
|
|
|
|
for (const item of overviewData) {
|
|
const row = overviewSheet.addRow(item);
|
|
row.height = 22;
|
|
row.eachCell((cell) => {
|
|
cell.border = borderStyle;
|
|
cell.font = { name: "Microsoft YaHei", size: 10 };
|
|
cell.alignment = { vertical: "middle" };
|
|
});
|
|
}
|
|
|
|
const links = perf.sankeyData?.links || [];
|
|
if (links.length > 0) {
|
|
overviewSheet.addRow({});
|
|
const sankeyHeaderRow = overviewSheet.addRow(["决策流向", "流向阶段 (起点)", "走向阶段 (终点)", "流转单据数", "占比/流向说明"]);
|
|
sankeyHeaderRow.height = 24;
|
|
sankeyHeaderRow.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FF0F172A" } };
|
|
sankeyHeaderRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFE2E8F0" } };
|
|
sankeyHeaderRow.eachCell((cell) => {
|
|
cell.border = borderStyle;
|
|
cell.alignment = { vertical: "middle", horizontal: "center" };
|
|
});
|
|
|
|
for (const link of links) {
|
|
const row = overviewSheet.addRow({
|
|
category: "决策流向",
|
|
name: link.source,
|
|
val: link.target,
|
|
trend: link.value,
|
|
desc: "流向连接"
|
|
});
|
|
row.height = 20;
|
|
row.eachCell((cell) => {
|
|
cell.border = borderStyle;
|
|
cell.font = { name: "Microsoft YaHei", size: 9 };
|
|
cell.alignment = { vertical: "middle" };
|
|
});
|
|
}
|
|
}
|
|
|
|
// -------------------------------------------------------------
|
|
// Sheet 2: Top 风险标签分析
|
|
// -------------------------------------------------------------
|
|
const tagSheet = workbook.addWorksheet("Top 风险标签分析", {
|
|
views: [{ showGridLines: true }]
|
|
});
|
|
|
|
tagSheet.columns = [
|
|
{ header: "标签编号", key: "tagId", width: 14 },
|
|
{ header: "风险标签名称", key: "tagName", width: 26 },
|
|
{ header: "风险分类路径", key: "tagPath", width: 44 },
|
|
{ header: "风险出现次数", key: "count", width: 16 },
|
|
{ header: "严重错误数 (Error)", key: "errorCount", width: 20 },
|
|
{ header: "合规预警数 (Warning)", key: "warningCount", width: 22 },
|
|
{ header: "平均置信度", key: "avgConfidence", width: 16 }
|
|
];
|
|
|
|
tagSheet.getRow(1).height = 28;
|
|
tagSheet.getRow(1).font = headerFont;
|
|
tagSheet.getRow(1).fill = headerFill;
|
|
tagSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
|
|
|
|
for (const tag of tagStats) {
|
|
const row = tagSheet.addRow({
|
|
tagId: tag.tagId || "-",
|
|
tagName: tag.tagName || "-",
|
|
tagPath: tag.tagPath || "-",
|
|
count: tag.count ?? 0,
|
|
errorCount: tag.errorCount ?? 0,
|
|
warningCount: tag.warningCount ?? 0,
|
|
avgConfidence: tag.avgConfidence ? `${Math.round(tag.avgConfidence * 100)}%` : "-"
|
|
});
|
|
row.height = 22;
|
|
row.eachCell((cell, colNumber) => {
|
|
cell.border = borderStyle;
|
|
cell.font = { name: "Microsoft YaHei", size: 10 };
|
|
cell.alignment = {
|
|
vertical: "middle",
|
|
horizontal: [1, 4, 5, 6, 7].includes(colNumber) ? "center" : "left"
|
|
};
|
|
|
|
if (colNumber === 5 && (tag.errorCount ?? 0) > 0) {
|
|
cell.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FFDC2626" } };
|
|
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
|
|
}
|
|
if (colNumber === 6 && (tag.warningCount ?? 0) > 0) {
|
|
cell.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FFD97706" } };
|
|
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
|
|
}
|
|
});
|
|
}
|
|
|
|
// -------------------------------------------------------------
|
|
// Sheet 3: 风险单据穿透明细
|
|
// -------------------------------------------------------------
|
|
const detailSheet = workbook.addWorksheet("风险单据穿透明细", {
|
|
views: [{ showGridLines: true }]
|
|
});
|
|
|
|
detailSheet.columns = [
|
|
{ header: "序号", key: "idx", width: 8 },
|
|
{ header: "风险标签", key: "tag", width: 24 },
|
|
{ header: "关联单据流水号", key: "documentSN", width: 20 },
|
|
{ header: "单据类型", key: "documentType", width: 16 },
|
|
{ header: "风险等级", key: "riskLevel", width: 14 },
|
|
{ header: "置信度", key: "confidence", width: 12 },
|
|
{ header: "风险具体描述", key: "riskDetails", width: 48 },
|
|
{ header: "AI 审核判断依据", key: "reasoning", width: 48 },
|
|
{ header: "单据链接", key: "sourceDocumentURL", width: 30 },
|
|
{ header: "发现时间", key: "createdAt", width: 22 }
|
|
];
|
|
|
|
detailSheet.getRow(1).height = 28;
|
|
detailSheet.getRow(1).font = headerFont;
|
|
detailSheet.getRow(1).fill = headerFill;
|
|
detailSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
|
|
|
|
let rowIdx = 1;
|
|
for (const item of riskDetailRows) {
|
|
let createdAtStr = "-";
|
|
if (item.createdAt) {
|
|
const d = new Date(item.createdAt);
|
|
if (!isNaN(d.getTime())) {
|
|
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
|
|
}
|
|
}
|
|
|
|
const row = detailSheet.addRow({
|
|
idx: rowIdx++,
|
|
tag: `${item.tagName} (${item.tagId})`,
|
|
documentSN: item.documentSN,
|
|
documentType: item.documentType,
|
|
riskLevel: item.riskLevel === "error" ? "严重错误" : "合规预警",
|
|
confidence: `${Math.round(item.confidence * 100)}%`,
|
|
riskDetails: item.riskDetails,
|
|
reasoning: item.reasoning,
|
|
sourceDocumentURL: item.sourceDocumentURL || "-",
|
|
createdAt: createdAtStr
|
|
});
|
|
|
|
row.height = 36;
|
|
row.eachCell((cell, colNumber) => {
|
|
cell.border = borderStyle;
|
|
cell.font = { name: "Microsoft YaHei", size: 9 };
|
|
cell.alignment = {
|
|
vertical: "middle",
|
|
horizontal: [1, 3, 4, 5, 6, 10].includes(colNumber) ? "center" : "left",
|
|
wrapText: [7, 8].includes(colNumber)
|
|
};
|
|
|
|
if (colNumber === 5) {
|
|
if (item.riskLevel === "error") {
|
|
cell.font = { name: "Microsoft YaHei", size: 9, bold: true, color: { argb: "FFDC2626" } };
|
|
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
|
|
} else {
|
|
cell.font = { name: "Microsoft YaHei", size: 9, bold: true, color: { argb: "FFD97706" } };
|
|
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// 4. 写入本地文件
|
|
const dateTag = dateRange.dateTag;
|
|
|
|
const targetPath = resolveInsightOutputFilePath({
|
|
outputFile: options.outputFile,
|
|
toDownloads: options.toDownloads,
|
|
corpName,
|
|
dateTag
|
|
});
|
|
|
|
await workbook.xlsx.writeFile(targetPath);
|
|
console.error(`智能洞察 Excel 报告已成功保存至: ${targetPath}`);
|
|
|
|
const stat = statSync(targetPath);
|
|
|
|
return {
|
|
filePath: targetPath,
|
|
corpId: corp.id,
|
|
corpName,
|
|
totalRisks: stats.totalRisks ?? 0,
|
|
tagCount: tagStats.length,
|
|
riskDetailCount: riskDetailRows.length,
|
|
fileSizeBytes: stat.size,
|
|
exportedAt
|
|
};
|
|
}
|