import { describe, expect, test, beforeEach, afterEach } from "bun:test"; import { existsSync, unlinkSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import type { KyInstance } from "ky"; import type { CorpConfig } from "../../../core/config/types.js"; import type { ApprovalRun } from "../types.js"; import { exportApprovalRunsToResourcePack, resolveResourcePackOutputPath } from "./export.js"; import { previewResourcePack } from "./service.js"; const mockCorp: CorpConfig = { id: "test-corp", name: "测试研发企业", environment: "test", source: { type: "direct", token: "mock-token", sealUrl: "https://seal.example.com", expiresIn: 3600, staffId: "direct" }, auth: { refreshTtl: 300 }, seal: { url: "https://seal.example.com", endpoints: { approvalStylePreferences: "/api/v1/approval-preferences" } } }; describe("Webhook Resource Pack Export", () => { let originalFetch: typeof globalThis.fetch; const tempFiles: string[] = []; beforeEach(() => { originalFetch = globalThis.fetch; }); afterEach(() => { globalThis.fetch = originalFetch; for (const f of tempFiles) { if (existsSync(f)) { try { unlinkSync(f); } catch {} } } tempFiles.length = 0; }); test("resolveResourcePackOutputPath generates correct paths", () => { const defaultPath = resolveResourcePackOutputPath({}, mockCorp); expect(defaultPath).toContain("webhook-resource-pack-test-corp-"); expect(defaultPath.endsWith(".zip")).toBe(true); const customPath = resolveResourcePackOutputPath({ outputFile: "/tmp/custom-pack.zip" }, mockCorp); expect(customPath).toBe("/tmp/custom-pack.zip"); const dlPath = resolveResourcePackOutputPath({ toDownloads: true }, mockCorp); expect(dlPath).toContain("Downloads"); expect(dlPath.endsWith(".zip")).toBe(true); }); test("exports online approval runs to valid Webhook resource pack ZIP and passes preview validation", async () => { const mockRuns: ApprovalRun[] = [ { id: "run-001", corpId: "test-corp", status: "APPROVED", sourceDocumentId: "DOC-2026-001", sourceDocumentSN: "SN-2026-001", createdAt: "2026-09-10T08:00:00.000Z", document: { id: "DOC-2026-001", sn: "SN-2026-001", title: "上海差旅会议报销", fields: [ { key: "total_amount", label: "总金额", type: "AMOUNT", value: { amount: 3500, currency: "CNY" } }, { key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "参加行业研讨峰会" }, { key: "attachments", label: "发票", type: "ATTACHMENT", value: [ { fileId: "att-101", fileName: "hotel_invoice.pdf", fileType: "application/pdf", sourceField: "发票", ossSignedUrl: "https://oss.example.com/hotel_invoice.pdf" } ] } ] } }, { id: "run-002", corpId: "test-corp", status: "APPROVED", sourceDocumentId: "DOC-2026-002", sourceDocumentSN: "SN-2026-002", createdAt: "2026-09-11T09:30:00.000Z", document: { id: "DOC-2026-002", sn: "SN-2026-002", title: "技术评审会议(无附件)", fields: [ { key: "total_amount", label: "总金额", type: "AMOUNT", value: 1200 }, { key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "架构设计评审" } ] } } ]; // Mock fetch for downloading attachment (> 500 bytes to satisfy default attachment policy) const dummyPdfContent = Buffer.concat([ Buffer.from("%PDF-1.4 Mock PDF content for test verification\n"), Buffer.alloc(1000, "A") ]); globalThis.fetch = (async (input: RequestInfo | URL) => { const url = String(input); if (url === "https://oss.example.com/hotel_invoice.pdf") { return new Response(dummyPdfContent, { status: 200, headers: { "Content-Type": "application/pdf" } }); } return new Response("Not found", { status: 404 }); }) as any; // Mock KyInstance const mockClient = { get: (url: string) => ({ json: async () => { if (url.includes("run-001")) { return { code: 0, data: mockRuns[0] }; } if (url.includes("run-002")) { return { code: 0, data: mockRuns[1] }; } if (url.includes("approvals")) { return { code: 0, data: { total: 2, records: [ { id: "run-001", sourceDocumentId: "DOC-2026-001", status: "APPROVED" }, { id: "run-002", sourceDocumentId: "DOC-2026-002", status: "APPROVED" } ] } }; } throw new Error(`Unexpected GET: ${url}`); } }) } as unknown as KyInstance; const tmpZipPath = join(tmpdir(), `test-pack-export-${Date.now()}.zip`); tempFiles.push(tmpZipPath); const exportResult = await exportApprovalRunsToResourcePack(mockClient, mockCorp, { outputFile: tmpZipPath, limit: 2 }); expect(exportResult.filePath).toBe(tmpZipPath); expect(exportResult.recordCount).toBe(2); expect(exportResult.attachmentCount).toBe(1); expect(exportResult.fileSizeBytes).toBeGreaterThan(500); expect(exportResult.nextAction).toContain("seal-use webhook resource-pack push"); expect(existsSync(tmpZipPath)).toBe(true); // Verify the exported ZIP with previewResourcePack const zipBuffer = readFileSync(tmpZipPath); const preview = await previewResourcePack(zipBuffer, "test-pack.zip"); expect(preview.warnings).toEqual([]); expect(preview.documents).toHaveLength(2); const doc1 = preview.documents.find((d) => d.documentId === "DOC-2026-001"); expect(doc1).toBeDefined(); expect(doc1?.fields.some((f) => f.key === "meeting_name" && String(f.value).includes("上海差旅"))).toBe(true); // Check attachment injection on doc1 const invoiceAttField = doc1?.fields.find((f) => f.label === "发票" && f.type === "ATTACHMENT"); expect(invoiceAttField).toBeDefined(); expect(invoiceAttField?.value).toEqual([ { path: "DOC-2026-001/hotel_invoice.pdf", fileName: "hotel_invoice.pdf" } ]); const doc2 = preview.documents.find((d) => d.documentId === "DOC-2026-002"); expect(doc2).toBeDefined(); expect(doc2?.fields.some((f) => f.key === "meeting_name" && String(f.value).includes("技术评审"))).toBe(true); }); });