import { createWriteStream, mkdirSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { ZipArchive } from "archiver"; import ExcelJS from "exceljs"; import type { KyInstance } from "ky"; import type { CorpConfig } from "../../../core/config/types.js"; import * as api from "../api.js"; import { extractApprovalRunAttachments, sanitizeFileName } from "../attachments.js"; import type { ApprovalRun } from "../types.js"; import type { ResourcePackExportOptions, ResourcePackExportResult } from "./types.js"; export function resolveResourcePackOutputPath(options: ResourcePackExportOptions, corp: CorpConfig): string { if (options.outputFile) { return resolve(options.outputFile); } const dateStr = new Date().toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" }); const fileName = `webhook-resource-pack-${corp.id}-${dateStr}.zip`; if (options.toDownloads) { return join(homedir(), "Downloads", fileName); } return resolve(fileName); } interface DownloadedAttachment { fileName: string; zipPath: string; buffer: Buffer; sourceField: string; } export async function exportApprovalRunsToResourcePack( client: KyInstance, corp: CorpConfig, options: ResourcePackExportOptions = {} ): Promise { let runs: ApprovalRun[] = []; if (options.recordId) { process.stderr.write(`🔍 查询单据记录: ${options.recordId}...\n`); const record = await api.getApprovalRun(client, options.recordId); runs = [record]; } else if (options.recordIds && options.recordIds.length > 0) { process.stderr.write(`🔍 批量查询 ${options.recordIds.length} 条单据记录...\n`); runs = await Promise.all(options.recordIds.map((id) => api.getApprovalRun(client, id))); } else { const limit = options.limit ?? 10; process.stderr.write(`🔍 检索企业「${corp.name}」(${corp.id}) 的线上审核记录 (限制 ${limit} 条)...\n`); const listRes = await api.listApprovalRuns(client, { limit, status: options.status, startDate: options.startDate !== undefined ? String(options.startDate) : undefined, endDate: options.endDate !== undefined ? String(options.endDate) : undefined }); const summaryRecords = listRes.records ?? []; if (summaryRecords.length === 0) { throw new Error(`未检索到符合条件的线上审核记录,无法导出 webhook 资源包。`); } process.stderr.write(`📥 正在拉取 ${summaryRecords.length} 条审核记录完整详情...\n`); runs = await Promise.all(summaryRecords.map((r) => api.getApprovalRun(client, r.id))); } // 1. 提取并下载附件 const docAttachmentsMap = new Map(); let totalDownloadedCount = 0; for (const run of runs) { const rawDoc = run.document as Record | undefined; const originalDocId = run.sourceDocumentId ?? (typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ?? (typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ?? run.documentId ?? run.id; const docId = `${options.docIdPrefix ?? ""}${originalDocId}${options.docIdSuffix ?? ""}`; const downloadedList: DownloadedAttachment[] = []; if (options.includeAttachments !== false) { const extraction = extractApprovalRunAttachments(run, { summary: false }); const attachments = extraction.attachments as Array>; const usedFileNames = new Set(); for (const att of attachments) { const downloadUrl = (att.ossSignedUrl as string | undefined) ?? (att.url as string | undefined); if (!downloadUrl) continue; const rawName = (att.fileName as string | undefined) ?? (att.fileId as string | undefined) ?? "attachment"; const safeBase = sanitizeFileName(rawName); let targetName = safeBase; const lastDot = safeBase.lastIndexOf("."); const stem = lastDot > 0 ? safeBase.slice(0, lastDot) : safeBase; const ext = lastDot > 0 ? safeBase.slice(lastDot) : ""; let counter = 1; while (usedFileNames.has(targetName.toLowerCase())) { targetName = `${stem}_${counter}${ext}`; counter++; } usedFileNames.add(targetName.toLowerCase()); try { process.stderr.write(`⬇ 下载单据「${docId}」附件: ${rawName}...\n`); const res = await fetch(downloadUrl); if (res.ok) { const arrBuf = await res.arrayBuffer(); const buf = Buffer.from(arrBuf); downloadedList.push({ fileName: targetName, zipPath: `${docId}/${targetName}`, buffer: buf, sourceField: (att.sourceField as string | undefined) ?? "附件" }); totalDownloadedCount++; } } catch (err) { process.stderr.write(`⚠️ [跳过附件] 下载失败 ${rawName}: ${err}\n`); } } } docAttachmentsMap.set(docId, downloadedList); } // 2. 构建符合 Webhook 资源包标准的「信息表.xlsx」 const workbook = new ExcelJS.Workbook(); workbook.creator = "seal-use"; workbook.created = new Date(); // 收集所有出现的附件类别列标签 const allAttachmentLabels = new Set(); for (const attachments of docAttachmentsMap.values()) { for (const att of attachments) { allAttachmentLabels.add(att.sourceField); } } if (allAttachmentLabels.size === 0) { allAttachmentLabels.add("附件"); } // 收集动态普通字段列 const dynamicFieldLabels = new Set(); for (const run of runs) { const rawDoc = run.document as Record | undefined; const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : []; for (const f of rawFields) { if (f && typeof f === "object") { const item = f as Record; const label = typeof item.label === "string" ? item.label.trim() : typeof item.key === "string" ? item.key.trim() : ""; const type = typeof item.type === "string" ? item.type.toUpperCase() : ""; if (label && type !== "ATTACHMENT" && type !== "LIST") { dynamicFieldLabels.add(label); } } } } // 基础标准列 const baseHeaders = ["会议编号", "会议名称", "状态", "总金额", "报销事由", "申请日期"]; // 排除已在基础列的动态字段 const filteredDynamicHeaders = Array.from(dynamicFieldLabels).filter( (h) => !baseHeaders.includes(h) && h !== "单据编号" && h !== "单号" ); // 附件列,严格加上 [附件] 前缀 const attachmentHeaders = Array.from(allAttachmentLabels).map((label) => `[附件]${label}`); const mainHeaders = [...baseHeaders, ...filteredDynamicHeaders, ...attachmentHeaders]; const mainSheet = workbook.addWorksheet("主表"); mainSheet.addRow(mainHeaders); // 设置表头粗体 mainSheet.getRow(1).font = { bold: true }; for (const run of runs) { const rawDoc = run.document as Record | undefined; const originalSN = run.sourceDocumentSN ?? (typeof rawDoc?.sn === "string" ? rawDoc.sn : undefined) ?? (typeof rawDoc?.sourceDocumentSN === "string" ? rawDoc.sourceDocumentSN : undefined) ?? run.id; const originalDocId = run.sourceDocumentId ?? (typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ?? (typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ?? run.documentId ?? run.id; const docId = `${options.docIdPrefix ?? ""}${originalDocId}${options.docIdSuffix ?? ""}`; const sn = `${options.docIdPrefix ?? ""}${originalSN}${options.docIdSuffix ?? ""}`; const title = (typeof rawDoc?.title === "string" ? rawDoc.title : undefined) ?? (typeof rawDoc?.name === "string" ? rawDoc.name : undefined) ?? sn; // 申请日期 let applyDateStr = ""; if (typeof rawDoc?.sourceStartTime === "number") { applyDateStr = new Date(rawDoc.sourceStartTime * 1000).toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" }); } else if (typeof run.createdAt === "number") { applyDateStr = new Date(run.createdAt).toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" }); } else if (typeof run.createdAt === "string") { applyDateStr = run.createdAt.slice(0, 10); } // 字段映射 const fieldMap = new Map(); const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : []; for (const f of rawFields) { if (f && typeof f === "object") { const item = f as Record; const label = typeof item.label === "string" ? item.label.trim() : typeof item.key === "string" ? item.key.trim() : ""; if (label) { fieldMap.set(label, item.value); } } } // 提取金额 let totalAmount: number | undefined; const amountVal = fieldMap.get("总金额") ?? fieldMap.get("报销金额") ?? fieldMap.get("total_amount"); if (typeof amountVal === "number") { totalAmount = amountVal; } else if (amountVal && typeof amountVal === "object" && "amount" in amountVal && typeof (amountVal as any).amount === "number") { totalAmount = (amountVal as any).amount; } const rowValues: unknown[] = []; rowValues.push(docId); // 会议编号 rowValues.push(title); // 会议名称 rowValues.push(run.status ?? "已审批"); // 状态 rowValues.push(totalAmount ?? ""); // 总金额 rowValues.push(fieldMap.get("报销事由") ?? fieldMap.get("事由") ?? title); // 报销事由 rowValues.push(applyDateStr); // 申请日期 // 动态字段 for (const header of filteredDynamicHeaders) { const val = fieldMap.get(header); if (val === undefined || val === null) { rowValues.push(""); } else if (typeof val === "object") { if ("amount" in (val as any)) { rowValues.push((val as any).amount); } else { rowValues.push(JSON.stringify(val)); } } else { rowValues.push(val); } } // 附件字段 const docAttachments = docAttachmentsMap.get(docId) ?? []; for (const rawLabel of allAttachmentLabels) { const matching = docAttachments.filter((a) => a.sourceField === rawLabel || (allAttachmentLabels.size === 1)); if (matching.length > 0) { rowValues.push(matching.map((m) => m.zipPath).join("\n")); } else { rowValues.push(""); } } mainSheet.addRow(rowValues); } // 3. 打包生成 ZIP 资源包 const outputFilePath = resolveResourcePackOutputPath(options, corp); mkdirSync(dirname(outputFilePath), { recursive: true }); const xlsxBuffer = await workbook.xlsx.writeBuffer(); process.stderr.write(`📦 正在压缩生成 Webhook 资源包: ${outputFilePath}...\n`); await new Promise((resolvePromise, rejectPromise) => { const outputStream = createWriteStream(outputFilePath); const archive = new ZipArchive({ zlib: { level: 9 } }); outputStream.on("close", () => resolvePromise()); archive.on("error", (err: unknown) => rejectPromise(err)); archive.pipe(outputStream); // 根目录写入 信息表.xlsx archive.append(Buffer.from(xlsxBuffer), { name: "信息表.xlsx" }); // 写入各单据目录及附件 for (const attachments of docAttachmentsMap.values()) { for (const att of attachments) { archive.append(att.buffer, { name: att.zipPath }); } } archive.finalize(); }); const stats = statSync(outputFilePath); return { filePath: outputFilePath, corpId: corp.id, corpName: corp.name, recordCount: runs.length, attachmentCount: totalDownloadedCount, fileSizeBytes: stats.size, exportedAt: new Date().toISOString(), nextAction: `seal-use webhook resource-pack push ${outputFilePath} --corp ` }; }