Release v0.10.11: Standard approval runs Excel export command and tool
This commit is contained in:
1 parent
b950e2b562
commit
06561bc893
13 files changed
+936
-145
No files matched your search
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import ExcelJS from "exceljs";
|
||||
import {
|
||||
getRuleBriefTitle,
|
||||
normalizeManualApprovalStatus,
|
||||
normalizeTimestamp,
|
||||
resolveOutputFilePath,
|
||||
exportApprovalRunsToExcel
|
||||
} from "./approval-runs-export.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("approval-runs-export helpers", () => {
|
||||
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
|
||||
const start = normalizeTimestamp("2026-08-07", false);
|
||||
expect(start).toBe(String(new Date("2026-08-07T00:00:00.000+08:00").getTime()));
|
||||
|
||||
const end = normalizeTimestamp("2026-08-07", true);
|
||||
expect(end).toBe(String(new Date("2026-08-07T23:59:59.999+08:00").getTime()));
|
||||
|
||||
// 10-digit epoch
|
||||
expect(normalizeTimestamp("1786032000")).toBe("1786032000000");
|
||||
// 13-digit epoch
|
||||
expect(normalizeTimestamp("1786032000123")).toBe("1786032000123");
|
||||
// number
|
||||
expect(normalizeTimestamp(1786032000000)).toBe("1786032000000");
|
||||
// undefined/empty
|
||||
expect(normalizeTimestamp(undefined)).toBeUndefined();
|
||||
expect(normalizeTimestamp("")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("normalizeManualApprovalStatus maps human words to backend enum", () => {
|
||||
expect(normalizeManualApprovalStatus("APPROVED")).toEqual(["APPROVED"]);
|
||||
expect(normalizeManualApprovalStatus("已通过")).toEqual(["APPROVED"]);
|
||||
expect(normalizeManualApprovalStatus("已支付/审批完成")).toEqual(["APPROVED"]);
|
||||
expect(normalizeManualApprovalStatus("TERMINATED")).toEqual(["TERMINATED"]);
|
||||
expect(normalizeManualApprovalStatus("被驳回")).toEqual(["TERMINATED"]);
|
||||
expect(normalizeManualApprovalStatus("处理中")).toEqual(["PROCESSING"]);
|
||||
expect(normalizeManualApprovalStatus("已撤回")).toEqual(["CANCELLED"]);
|
||||
expect(normalizeManualApprovalStatus(["已通过", "被驳回"])).toEqual(["APPROVED", "TERMINATED"]);
|
||||
expect(normalizeManualApprovalStatus(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("getRuleBriefTitle extracts clean concise summary", () => {
|
||||
expect(getRuleBriefTitle("rule-0", "所有单据:报销公司不是浙江大黄蜂建筑机械设备有限公司时提示")).toBe(
|
||||
"所有单据:报销公司不是浙江大黄蜂建筑机械设备"
|
||||
);
|
||||
expect(getRuleBriefTitle("rule-1", "### 发票合规校验\n第二行内容")).toBe("发票合规校验");
|
||||
expect(getRuleBriefTitle("rule-2", undefined, "通用范围")).toBe("rule-2 (通用范围)");
|
||||
});
|
||||
|
||||
test("resolveOutputFilePath supports custom path, downloads, and default exports dir", () => {
|
||||
const custom = resolveOutputFilePath({
|
||||
outputFile: "/tmp/custom-export.xlsx",
|
||||
corpName: "TestCorp",
|
||||
recordCount: 10
|
||||
});
|
||||
expect(custom).toBe("/tmp/custom-export.xlsx");
|
||||
|
||||
const dl = resolveOutputFilePath({
|
||||
toDownloads: true,
|
||||
corpName: "大黄蜂",
|
||||
dateTag: "2026-08-07至今",
|
||||
recordCount: 50
|
||||
});
|
||||
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至今_50条.xlsx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("exportApprovalRunsToExcel integration", () => {
|
||||
const testCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "测试企业",
|
||||
seal: {
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "test-token",
|
||||
sealUrl: "https://mock.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "direct"
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
}
|
||||
};
|
||||
|
||||
test("generates valid formatted excel workbook", async () => {
|
||||
const mockClient = {
|
||||
get: (url: string, opts?: any) => {
|
||||
if (url.includes("api/v1/rules")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
rules: [
|
||||
{ id: "r1", code: 0, description: "发票与收据真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" },
|
||||
{ id: "r2", code: 1, description: "差旅标准不得超标", scope: "差旅", strictness: "MUST_FOLLOW" }
|
||||
]
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url.includes("api/v1/approvals")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
total: 2,
|
||||
records: [
|
||||
{
|
||||
id: "run-1",
|
||||
sourceDocumentSN: "B26001",
|
||||
status: "completed",
|
||||
taskMode: "assisted",
|
||||
sourceSystem: "hosecloud",
|
||||
document: {
|
||||
fields: [{ label: "单据模板", value: "差旅报销单" }]
|
||||
},
|
||||
result: {
|
||||
decision: "APPROVE",
|
||||
rulesResult: [{ id: "rule-0", checkResult: "PASS" }]
|
||||
},
|
||||
manualApprovalRecord: {
|
||||
status: { label: "已支付/审批完成", type: "APPROVED" }
|
||||
},
|
||||
createdAt: 1788760000000,
|
||||
updatedAt: 1788760020000
|
||||
},
|
||||
{
|
||||
id: "run-2",
|
||||
sourceDocumentSN: "B26002",
|
||||
status: "completed",
|
||||
taskMode: "assisted",
|
||||
sourceSystem: "hosecloud",
|
||||
document: {
|
||||
fields: [{ label: "单据模板", value: "差旅报销单" }]
|
||||
},
|
||||
result: {
|
||||
decision: "REJECT",
|
||||
rulesResult: [{ id: "rule-0", checkResult: "FAIL" }]
|
||||
},
|
||||
manualApprovalRecord: {
|
||||
status: { label: "被驳回", type: "TERMINATED" },
|
||||
rejectComment: "请上传正确的行程单凭据"
|
||||
},
|
||||
createdAt: 1788760000000,
|
||||
updatedAt: 1788760030000
|
||||
}
|
||||
]
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const tmpOut = join(tmpdir(), `test-export-${Date.now()}.xlsx`);
|
||||
|
||||
try {
|
||||
const result = await exportApprovalRunsToExcel(mockClient, testCorp, {
|
||||
outputFile: tmpOut,
|
||||
limit: 10,
|
||||
pageDelayMs: 0
|
||||
});
|
||||
|
||||
expect(result.recordCount).toBe(2);
|
||||
expect(result.ruleColumnCount).toBe(2);
|
||||
expect(result.statusCounts["已支付/审批完成"]).toBe(1);
|
||||
expect(result.statusCounts["被驳回"]).toBe(1);
|
||||
expect(result.rejectReasonCount).toBe(1);
|
||||
expect(existsSync(tmpOut)).toBe(true);
|
||||
|
||||
// Verify Excel contents with ExcelJS
|
||||
const wb = new ExcelJS.Workbook();
|
||||
await wb.xlsx.readFile(tmpOut);
|
||||
const ws = wb.worksheets[0]!;
|
||||
expect(ws.rowCount).toBe(3); // 1 header + 2 rows
|
||||
expect(ws.getRow(1).getCell(1).value).toBe("单据编号");
|
||||
expect(ws.getRow(2).getCell(1).value).toBe("B26001");
|
||||
expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成");
|
||||
expect(ws.getRow(3).getCell(1).value).toBe("B26002");
|
||||
expect(ws.getRow(3).getCell(9).value).toBe("被驳回");
|
||||
expect(ws.getRow(3).getCell(10).value).toBe("请上传正确的行程单凭据");
|
||||
} finally {
|
||||
if (existsSync(tmpOut)) {
|
||||
rmSync(tmpOut, { force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,531 @@
|
||||
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 type { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
|
||||
|
||||
export interface ApprovalRunsExportOptions {
|
||||
limit?: number;
|
||||
startDate?: string | number;
|
||||
endDate?: string | number;
|
||||
status?: string;
|
||||
manualApprovalStatus?: string | string[];
|
||||
includeCompletedOnly?: boolean;
|
||||
outputFile?: string;
|
||||
toDownloads?: boolean;
|
||||
pageSize?: number;
|
||||
pageDelayMs?: number;
|
||||
}
|
||||
|
||||
export interface ApprovalRunsExportResult {
|
||||
filePath: string;
|
||||
corpId: string;
|
||||
corpName: string;
|
||||
recordCount: number;
|
||||
ruleColumnCount: number;
|
||||
statusCounts: Record<string, number>;
|
||||
rejectReasonCount: number;
|
||||
fileSizeBytes: number;
|
||||
exportedAt: string;
|
||||
}
|
||||
|
||||
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
|
||||
if (val === undefined || val === null || val === "") return undefined;
|
||||
if (typeof val === "number") return String(val);
|
||||
const str = String(val).trim();
|
||||
if (!str) return undefined;
|
||||
if (/^\d{10,13}$/.test(str)) {
|
||||
return str.length === 10 ? `${str}000` : str;
|
||||
}
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
|
||||
const timeSuffix = endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
|
||||
const parsed = new Date(`${str}${timeSuffix}`).getTime();
|
||||
if (!Number.isNaN(parsed)) return String(parsed);
|
||||
}
|
||||
const parsed = new Date(str).getTime();
|
||||
if (!Number.isNaN(parsed)) return String(parsed);
|
||||
return str;
|
||||
}
|
||||
|
||||
export function normalizeManualApprovalStatus(status?: string | string[]): string[] | undefined {
|
||||
if (!status) return undefined;
|
||||
const rawList = Array.isArray(status) ? status : [status];
|
||||
const list: string[] = [];
|
||||
for (const s of rawList) {
|
||||
const normalized = s.trim().toUpperCase();
|
||||
if (["APPROVED", "已通过", "已完成", "已支付", "已支付/审批完成"].includes(normalized)) {
|
||||
list.push("APPROVED");
|
||||
} else if (["TERMINATED", "REJECTED", "REJECT", "驳回", "被驳回", "已驳回"].includes(normalized)) {
|
||||
list.push("TERMINATED");
|
||||
} else if (["PROCESSING", "审批中", "处理中"].includes(normalized)) {
|
||||
list.push("PROCESSING");
|
||||
} else if (["CANCELLED", "CANCELED", "已撤回", "已撤销"].includes(normalized)) {
|
||||
list.push("CANCELLED");
|
||||
} else if (normalized) {
|
||||
list.push(normalized);
|
||||
}
|
||||
}
|
||||
return list.length > 0 ? list : undefined;
|
||||
}
|
||||
|
||||
export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string): string {
|
||||
if (!desc) return scope ? `${ruleId} (${scope})` : ruleId;
|
||||
const firstSentence = desc.split(/[。\n\r;;!!]/)[0]?.trim() || desc.trim();
|
||||
const clean = firstSentence.replace(/[*#`_]/g, "").trim();
|
||||
return clean.slice(0, 22);
|
||||
}
|
||||
|
||||
export function resolveOutputFilePath(options: {
|
||||
outputFile?: string;
|
||||
toDownloads?: boolean;
|
||||
corpName: string;
|
||||
dateTag?: string;
|
||||
recordCount: number;
|
||||
}): string {
|
||||
if (options.outputFile) {
|
||||
const p = resolve(options.outputFile);
|
||||
const dir = dirname(p);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
const safeCorpName = options.corpName.replace(/[/\\?%*:|"<>]/g, "_").trim() || "审批记录";
|
||||
const dateTag = options.dateTag || new Date().toISOString().slice(0, 10);
|
||||
const countTag = options.recordCount > 0 ? `${options.recordCount}条` : "空数据";
|
||||
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}.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 exportApprovalRunsToExcel(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig,
|
||||
options: ApprovalRunsExportOptions = {}
|
||||
): Promise<ApprovalRunsExportResult> {
|
||||
const corpName = corp.name || corp.id;
|
||||
const pageSize = options.pageSize ?? 100;
|
||||
const pageDelayMs = options.pageDelayMs ?? 250;
|
||||
const limit = options.limit ?? 100000;
|
||||
|
||||
const startDateTs = normalizeTimestamp(options.startDate, false);
|
||||
const endDateTs = normalizeTimestamp(options.endDate, true);
|
||||
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
|
||||
|
||||
// 1. 动态加载企业规则集,生成列定义
|
||||
console.error(`正在加载企业「${corpName}」审核规则集...`);
|
||||
const ruleMap = new Map<string, { id: string; code: string; title: string; desc: string }>();
|
||||
|
||||
try {
|
||||
const rulesData = await api.listApprovalRules(client);
|
||||
rulesData.rules.forEach((r, idx) => {
|
||||
const runtimeId = `rule-${r.code ?? idx}`;
|
||||
const title = getRuleBriefTitle(runtimeId, r.description, r.scope);
|
||||
ruleMap.set(runtimeId, {
|
||||
id: runtimeId,
|
||||
code: String(r.code ?? idx),
|
||||
title: `[${runtimeId}] ${title}`,
|
||||
desc: r.description
|
||||
});
|
||||
});
|
||||
} catch (err: any) {
|
||||
console.error(`⚠️ 加载规则字典失败: ${err.message},将仅导出基础信息列。`);
|
||||
}
|
||||
|
||||
const sortedRuleKeys = Array.from(ruleMap.keys()).sort((a, b) => {
|
||||
const numA = parseInt(a.replace(/\D/g, ""), 10) || 0;
|
||||
const numB = parseInt(b.replace(/\D/g, ""), 10) || 0;
|
||||
return numA - numB;
|
||||
});
|
||||
|
||||
console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`);
|
||||
|
||||
// 2. 温和分页拉取单据记录
|
||||
const fetchedRecords: ApprovalRun[] = [];
|
||||
let offset = 0;
|
||||
let totalAvailable = 0;
|
||||
|
||||
while (fetchedRecords.length < limit) {
|
||||
let batch: ApprovalRunListData | undefined;
|
||||
let retries = 3;
|
||||
|
||||
while (retries > 0) {
|
||||
try {
|
||||
batch = await api.listApprovalRuns(client, {
|
||||
limit: pageSize,
|
||||
offset,
|
||||
startDate: startDateTs,
|
||||
endDate: endDateTs,
|
||||
status: options.status,
|
||||
manualApprovalStatus: manualStatusFilter
|
||||
});
|
||||
break;
|
||||
} catch (e: any) {
|
||||
retries--;
|
||||
console.error(`分页拉取失败 (offset=${offset}): ${e.message},剩余重试 ${retries} 次...`);
|
||||
if (retries === 0) throw e;
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
}
|
||||
}
|
||||
|
||||
if (!batch || !batch.records || batch.records.length === 0) break;
|
||||
totalAvailable = batch.total ?? totalAvailable;
|
||||
|
||||
for (const r of batch.records) {
|
||||
if (options.includeCompletedOnly && r.status !== "completed") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果是已完成单据但列表未附带规则结果,做安全补查
|
||||
if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) {
|
||||
try {
|
||||
const full = await api.getApprovalRun(client, r.id);
|
||||
fetchedRecords.push(full);
|
||||
} catch {
|
||||
fetchedRecords.push(r);
|
||||
}
|
||||
} else {
|
||||
fetchedRecords.push(r);
|
||||
}
|
||||
|
||||
if (fetchedRecords.length >= limit) break;
|
||||
}
|
||||
|
||||
offset += batch.records.length;
|
||||
const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-";
|
||||
if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) {
|
||||
console.error(
|
||||
`[进度] 已读取单据: ${offset}/${totalAvailable} (${currentProgress}%),有效加入: ${fetchedRecords.length} 条`
|
||||
);
|
||||
}
|
||||
|
||||
if (batch.records.length < pageSize || offset >= totalAvailable) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (pageDelayMs > 0) {
|
||||
await new Promise((r) => setTimeout(r, pageDelayMs));
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`成功拉取 ${fetchedRecords.length} 条单据数据,正在生成高保真 Excel...`);
|
||||
|
||||
// 3. 构建 Excel 工作簿
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = "Seal AI (seal-use)";
|
||||
workbook.created = new Date();
|
||||
|
||||
const worksheet = workbook.addWorksheet("审核记录明细", {
|
||||
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
|
||||
});
|
||||
|
||||
const baseColumns: Array<{ header: string; key: string; width: number }> = [
|
||||
{ header: "单据编号", key: "sn", width: 16 },
|
||||
{ header: "单据模板名称", key: "templateName", width: 26 },
|
||||
{ header: "来源系统", key: "sourceSystem", width: 12 },
|
||||
{ header: "任务模式", key: "taskMode", width: 12 },
|
||||
{ header: "状态", key: "status", width: 12 },
|
||||
{ header: "AI行为", key: "aiAction", width: 14 },
|
||||
{ header: "AI决策", key: "aiDecision", width: 14 },
|
||||
{ header: "思考深度", key: "thinkingDepth", width: 12 },
|
||||
{ header: "人工审核", key: "manualStatus", width: 16 },
|
||||
{ header: "人工驳回原因", key: "humanRejectReason", width: 36 },
|
||||
{ header: "创建时间", key: "createdAt", width: 20 },
|
||||
{ header: "任务耗时", key: "duration", width: 12 },
|
||||
{ header: "关联规则数", key: "hitRuleCount", width: 12 },
|
||||
{ header: "关联规则汇总", key: "hitRulesSummary", width: 30 },
|
||||
{ header: "AI审核结论摘要", key: "aiSummary", width: 45 }
|
||||
];
|
||||
|
||||
const ruleColumns = sortedRuleKeys.map((ruleKey) => {
|
||||
const rInfo = ruleMap.get(ruleKey)!;
|
||||
return {
|
||||
header: rInfo.title,
|
||||
key: `rule_${ruleKey}`,
|
||||
width: 22
|
||||
};
|
||||
});
|
||||
|
||||
worksheet.columns = [...baseColumns, ...ruleColumns];
|
||||
|
||||
// 表头样式设置
|
||||
const headerRow = worksheet.getRow(1);
|
||||
headerRow.height = 32;
|
||||
headerRow.eachCell((cell, colNumber) => {
|
||||
const isBase = colNumber <= baseColumns.length;
|
||||
cell.font = {
|
||||
name: "Microsoft YaHei",
|
||||
bold: true,
|
||||
color: { argb: "FFFFFFFF" },
|
||||
size: 11
|
||||
};
|
||||
cell.fill = {
|
||||
type: "pattern",
|
||||
pattern: "solid",
|
||||
fgColor: { argb: isBase ? "FF1E3A8A" : "FF334155" }
|
||||
};
|
||||
cell.alignment = {
|
||||
vertical: "middle",
|
||||
horizontal: isBase && colNumber <= 2 ? "left" : "center",
|
||||
wrapText: false
|
||||
};
|
||||
});
|
||||
|
||||
const statusCounts: Record<string, number> = {};
|
||||
let rejectReasonCount = 0;
|
||||
|
||||
// 填充数据行
|
||||
for (const record of fetchedRecords) {
|
||||
const res = (record.result as any) || {};
|
||||
const doc = (record.document as any) || {};
|
||||
|
||||
// 1. 提取单据模板名称
|
||||
let templateName = "未知模板";
|
||||
if (Array.isArray(doc.fields)) {
|
||||
const tField = doc.fields.find(
|
||||
(f: any) =>
|
||||
f.label === "单据模板" ||
|
||||
f.label === "流程名称" ||
|
||||
f.key === "templateName" ||
|
||||
f.key === "specificationId" ||
|
||||
f.key === "formName"
|
||||
);
|
||||
if (tField?.value) templateName = String(tField.value);
|
||||
}
|
||||
if (templateName === "未知模板" && (doc.name || doc.title)) {
|
||||
templateName = doc.name || doc.title;
|
||||
}
|
||||
|
||||
// 2. 映射任务模式
|
||||
let taskModeDesc = record.taskMode || "-";
|
||||
if (taskModeDesc === "assisted") taskModeDesc = "辅助审核";
|
||||
else if (taskModeDesc === "simulation") taskModeDesc = "测试任务";
|
||||
else if (taskModeDesc === "automatic") taskModeDesc = "自动审批";
|
||||
|
||||
// 3. 映射状态
|
||||
let statusDesc = record.status || "-";
|
||||
if (statusDesc === "completed") statusDesc = "已完成";
|
||||
else if (statusDesc === "processing") statusDesc = "处理中";
|
||||
else if (statusDesc === "failed") statusDesc = "失败";
|
||||
|
||||
// 4. AI 决策与行为
|
||||
const aiDecision = res.decision || (record as any).aiDecision || "-";
|
||||
let aiDecisionDesc = aiDecision;
|
||||
let aiAction = "-";
|
||||
if (aiDecision === "APPROVE") {
|
||||
aiDecisionDesc = "通过";
|
||||
aiAction = "添加评论";
|
||||
} else if (aiDecision === "REVIEW") {
|
||||
aiDecisionDesc = "转交复核";
|
||||
aiAction = "转交复核";
|
||||
} else if (aiDecision === "REJECT") {
|
||||
aiDecisionDesc = "驳回";
|
||||
aiAction = "驳回";
|
||||
}
|
||||
|
||||
// 5. 耗时计算
|
||||
let durationStr = "-";
|
||||
if (record.createdAt && record.updatedAt && record.status === "completed") {
|
||||
const diffSec = Math.round((Number(record.updatedAt) - Number(record.createdAt)) / 1000);
|
||||
if (diffSec >= 60) {
|
||||
durationStr = `${Math.floor(diffSec / 60)}分${diffSec % 60}秒`;
|
||||
} else if (diffSec > 0) {
|
||||
durationStr = `${diffSec}秒`;
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 人工审核状态与驳回原因
|
||||
const mar = (record as any).manualApprovalRecord || {};
|
||||
let manualStatus = "-";
|
||||
if (mar.status?.label) {
|
||||
manualStatus = String(mar.status.label);
|
||||
} else if (mar.status?.type) {
|
||||
const t = String(mar.status.type);
|
||||
if (t === "APPROVED") manualStatus = "已通过";
|
||||
else if (t === "TERMINATED") manualStatus = "被驳回";
|
||||
else if (t === "PROCESSING") manualStatus = "处理中";
|
||||
else if (t === "CANCELLED") manualStatus = "已撤回";
|
||||
else manualStatus = t;
|
||||
}
|
||||
|
||||
statusCounts[manualStatus] = (statusCounts[manualStatus] || 0) + 1;
|
||||
|
||||
const humanRejectReason = mar.rejectComment ? String(mar.rejectComment).trim() : "-";
|
||||
if (humanRejectReason !== "-") {
|
||||
rejectReasonCount++;
|
||||
}
|
||||
|
||||
// 7. 解析规则核验结果
|
||||
const ruleResultMap = new Map<string, string>();
|
||||
const hitRuleIds: string[] = [];
|
||||
|
||||
if (Array.isArray(res.rulesResult)) {
|
||||
for (const rr of res.rulesResult) {
|
||||
if (rr.id) {
|
||||
ruleResultMap.set(rr.id, rr.checkResult || "PASS");
|
||||
hitRuleIds.push(rr.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(res.hitRules)) {
|
||||
for (const hr of res.hitRules) {
|
||||
if (hr.id && !ruleResultMap.has(hr.id)) {
|
||||
ruleResultMap.set(hr.id, "TRIGGERED");
|
||||
hitRuleIds.push(hr.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 创建时间
|
||||
let createdAtStr = "-";
|
||||
if (record.createdAt) {
|
||||
const d = new Date(Number(record.createdAt));
|
||||
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
|
||||
}
|
||||
|
||||
const rowData: Record<string, any> = {
|
||||
sn: record.sourceDocumentSN || record.sourceDocumentId || "-",
|
||||
templateName,
|
||||
sourceSystem: record.sourceSystem || "合思",
|
||||
taskMode: taskModeDesc,
|
||||
status: statusDesc,
|
||||
aiAction,
|
||||
aiDecision: aiDecisionDesc,
|
||||
thinkingDepth: "标准",
|
||||
manualStatus,
|
||||
humanRejectReason,
|
||||
createdAt: createdAtStr,
|
||||
duration: durationStr,
|
||||
hitRuleCount: hitRuleIds.length,
|
||||
hitRulesSummary: hitRuleIds.join(", ") || "-",
|
||||
aiSummary: res.summary || "-"
|
||||
};
|
||||
|
||||
for (const ruleKey of sortedRuleKeys) {
|
||||
const checkResult = ruleResultMap.get(ruleKey);
|
||||
if (checkResult) {
|
||||
if (checkResult === "PASS") rowData[`rule_${ruleKey}`] = "关联 (通过)";
|
||||
else if (checkResult === "FAIL") rowData[`rule_${ruleKey}`] = "关联 (不通过)";
|
||||
else if (checkResult === "UNKNOWN") rowData[`rule_${ruleKey}`] = "关联 (待复核)";
|
||||
else rowData[`rule_${ruleKey}`] = "已关联";
|
||||
} else {
|
||||
rowData[`rule_${ruleKey}`] = "未关联";
|
||||
}
|
||||
}
|
||||
|
||||
const addedRow = worksheet.addRow(rowData);
|
||||
addedRow.height = 24;
|
||||
|
||||
addedRow.eachCell((cell, colNumber) => {
|
||||
const val = String(cell.value || "");
|
||||
cell.font = { name: "Microsoft YaHei", size: 10 };
|
||||
cell.border = {
|
||||
top: { style: "thin", color: { argb: "FFE2E8F0" } },
|
||||
bottom: { style: "thin", color: { argb: "FFE2E8F0" } },
|
||||
left: { style: "thin", color: { argb: "FFE2E8F0" } },
|
||||
right: { style: "thin", color: { argb: "FFE2E8F0" } }
|
||||
};
|
||||
|
||||
if (colNumber <= baseColumns.length) {
|
||||
cell.alignment = {
|
||||
vertical: "middle",
|
||||
horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center",
|
||||
wrapText: [10, 14, 15].includes(colNumber)
|
||||
};
|
||||
|
||||
// AI 决策颜色区分
|
||||
if (colNumber === 7) {
|
||||
if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true };
|
||||
else if (val === "转交复核") cell.font = { color: { argb: "FFD97706" }, bold: true };
|
||||
else if (val === "驳回") cell.font = { color: { argb: "FFDC2626" }, bold: true };
|
||||
}
|
||||
|
||||
// 人工审核高亮
|
||||
if (colNumber === 9) {
|
||||
if (val.includes("驳回")) {
|
||||
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true };
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
|
||||
} else if (val.includes("通过") || val.includes("支付") || val.includes("完成")) {
|
||||
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF16A34A" }, bold: true };
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
|
||||
} else if (val.includes("处理中") || val.includes("审批中")) {
|
||||
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } };
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } };
|
||||
}
|
||||
}
|
||||
|
||||
// 人工驳回原因字体
|
||||
if (colNumber === 10 && val !== "-") {
|
||||
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } };
|
||||
}
|
||||
} else {
|
||||
cell.alignment = { vertical: "middle", horizontal: "center" };
|
||||
if (val.includes("不通过")) {
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
|
||||
cell.font = { color: { argb: "FF991B1B" }, bold: true };
|
||||
} else if (val.includes("通过")) {
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
|
||||
cell.font = { color: { argb: "FF166534" }, bold: true };
|
||||
} else if (val.includes("待复核") || val.includes("已关联")) {
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
|
||||
cell.font = { color: { argb: "FF92400E" } };
|
||||
} else {
|
||||
cell.font = { color: { argb: "FF94A3B8" } };
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 保存文件落地
|
||||
let dateTag: string | undefined;
|
||||
if (options.startDate) {
|
||||
const rawStart = String(options.startDate);
|
||||
if (/^\d{4}-\d{2}-\d{2}/.test(rawStart)) {
|
||||
dateTag = `${rawStart.slice(0, 10)}至今`;
|
||||
} else if (/^\d+$/.test(rawStart)) {
|
||||
const d = new Date(Number(rawStart));
|
||||
dateTag = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}至今`;
|
||||
}
|
||||
}
|
||||
|
||||
const targetPath = resolveOutputFilePath({
|
||||
outputFile: options.outputFile,
|
||||
toDownloads: options.toDownloads,
|
||||
corpName,
|
||||
dateTag,
|
||||
recordCount: fetchedRecords.length
|
||||
});
|
||||
|
||||
await workbook.xlsx.writeFile(targetPath);
|
||||
console.error(`Excel 文件已成功落地: ${targetPath}`);
|
||||
|
||||
const stat = statSync(targetPath);
|
||||
|
||||
return {
|
||||
filePath: targetPath,
|
||||
corpId: corp.id,
|
||||
corpName,
|
||||
recordCount: fetchedRecords.length,
|
||||
ruleColumnCount: sortedRuleKeys.length,
|
||||
statusCounts,
|
||||
rejectReasonCount,
|
||||
fileSizeBytes: stat.size,
|
||||
exportedAt: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "./m
|
||||
import {
|
||||
extractApprovalRunAttachments
|
||||
} from "./attachments.js";
|
||||
import { exportApprovalRunsToExcel } from "./approval-runs-export.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
@@ -1164,6 +1165,34 @@ export const sealTools = [
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_runs_export",
|
||||
description: "将企业的审批审核记录导出为高保真 Excel 报表(包含单据模板、AI决策、人工审核结论、驳回原因及企业规则列细分结果)",
|
||||
parameters: z.object({
|
||||
startDate: z.string().optional().describe("起始时间,支持 YYYY-MM-DD 或毫秒时间戳"),
|
||||
endDate: z.string().optional().describe("截止时间,支持 YYYY-MM-DD 或毫秒时间戳"),
|
||||
limit: z.number().int().positive().optional().describe("最大拉取记录条数"),
|
||||
status: z.string().optional().describe("单据状态过滤,如 completed, processing, failed"),
|
||||
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态过滤,如 APPROVED, TERMINATED, PROCESSING"),
|
||||
includeCompletedOnly: z.boolean().optional().describe("是否仅导出已完成单据"),
|
||||
outputFile: z.string().optional().describe("输出 Excel 文件的自定义绝对或相对路径"),
|
||||
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
limit?: number;
|
||||
status?: string;
|
||||
manualApprovalStatus?: string | string[];
|
||||
includeCompletedOnly?: boolean;
|
||||
outputFile?: string;
|
||||
toDownloads?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => exportApprovalRunsToExcel(client, context.corp, params)
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_get",
|
||||
description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段",
|
||||
|
||||
Reference in new issue
Block a user