Add Webhook resource pack export and rename dataset to resource-pack
- Clarify dataset naming as Webhook 资源包 (CLI: resource-pack, alias: pack), distinguishing from backend native simulation material pack while retaining material-pack as backward-compatible alias - Implement exportApprovalRunsToResourcePack for exporting online approval runs and attachments into local resource pack ZIP - Support seal-use webhook resource-pack export with record filters, docId prefix/suffix, and destination options - Refine bidirectional directory validation to allow documents without attachments - Update CLI runner, help definitions, and skill references - Add comprehensive export, preview, and CLI command unit tests
This commit is contained in:
1 parent
9afd169b50
commit
e54bf6f2a4
16 files changed
+1068
-68
No files matched your search
@@ -0,0 +1,238 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { exportApprovalRunsToResourcePack } from "../../domains/seal/material-pack/export.js";
|
||||
import { previewResourcePack } from "../../domains/seal/material-pack/service.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
config: process.env.SEAL_USE_CONFIG_FILE,
|
||||
tokenStore: process.env.SEAL_USE_TOKEN_STORE
|
||||
};
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
||||
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
|
||||
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function setupMockEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-pack-cli-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
|
||||
const fs = require("node:fs");
|
||||
fs.mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
const corpConfig = {
|
||||
id: "test-corp-pack",
|
||||
name: "测试资源包企业",
|
||||
environment: "test",
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "mock-valid-token",
|
||||
sealUrl: "https://test-pack.sealai.cc"
|
||||
},
|
||||
seal: {
|
||||
baseUrl: "https://test-pack.sealai.cc",
|
||||
token: "mock-valid-token",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/system/preferences/approval-style"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
writeFileSync(join(enterprises, "test-corp-pack.json"), JSON.stringify(corpConfig, null, 2));
|
||||
|
||||
const tokens = {
|
||||
"test-corp-pack": {
|
||||
token: "mock-valid-token",
|
||||
expiresAt: Date.now() + 3600_000
|
||||
}
|
||||
};
|
||||
writeFileSync(join(root, "tokens.json"), JSON.stringify(tokens, null, 2));
|
||||
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
describe("Webhook Resource Pack CLI Commands", () => {
|
||||
test("preview works via resource-pack, pack, and material-pack aliases", async () => {
|
||||
const { root } = setupMockEnv();
|
||||
|
||||
// Generate a valid pack first
|
||||
const mockRuns = [
|
||||
{
|
||||
id: "run-p1",
|
||||
corpId: "test-corp-pack",
|
||||
status: "APPROVED",
|
||||
sourceDocumentId: "DOC-CLI-01",
|
||||
createdAt: "2026-09-12T10:00:00Z",
|
||||
document: {
|
||||
id: "DOC-CLI-01",
|
||||
sn: "SN-CLI-01",
|
||||
title: "战略合作交流会",
|
||||
fields: [
|
||||
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: 5000 },
|
||||
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "年度战略会议" }
|
||||
]
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
const mockClient = {
|
||||
get: () => ({
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: mockRuns[0]
|
||||
})
|
||||
})
|
||||
} as any;
|
||||
|
||||
const testZipPath = join(root, "test-resource-pack.zip");
|
||||
await exportApprovalRunsToResourcePack(
|
||||
mockClient,
|
||||
{
|
||||
id: "test-corp-pack",
|
||||
name: "测试企业",
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "mock-valid-token",
|
||||
sealUrl: "https://test-pack.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "direct"
|
||||
},
|
||||
seal: { url: "https://test-pack.sealai.cc", endpoints: { approvalStylePreferences: "" } }
|
||||
} as any,
|
||||
{
|
||||
outputFile: testZipPath,
|
||||
recordId: "run-p1"
|
||||
}
|
||||
);
|
||||
|
||||
expect(existsSync(testZipPath)).toBe(true);
|
||||
|
||||
// 1. Test seal-use webhook resource-pack preview
|
||||
const cliRes1 = await runCli(["webhook", "resource-pack", "preview", testZipPath]);
|
||||
if (cliRes1.isError) {
|
||||
throw new Error(`CLI Error 1: ${cliRes1.stderr}`);
|
||||
}
|
||||
const res1 = JSON.parse(cliRes1.stdout);
|
||||
expect(res1.documents).toHaveLength(1);
|
||||
expect(res1.documents[0].documentId).toBe("DOC-CLI-01");
|
||||
|
||||
// 2. Test seal-use webhook pack preview (alias)
|
||||
const cliRes2 = await runCli(["webhook", "pack", "preview", testZipPath]);
|
||||
if (cliRes2.isError) {
|
||||
throw new Error(`CLI Error 2: ${cliRes2.stderr}`);
|
||||
}
|
||||
const res2 = JSON.parse(cliRes2.stdout);
|
||||
expect(res2.documents).toHaveLength(1);
|
||||
expect(res2.documents[0].documentId).toBe("DOC-CLI-01");
|
||||
|
||||
// 3. Test legacy seal-use webhook material-pack preview (backward compatibility)
|
||||
const cliRes3 = await runCli(["webhook", "material-pack", "preview", testZipPath]);
|
||||
if (cliRes3.isError) {
|
||||
throw new Error(`CLI Error 3: ${cliRes3.stderr}`);
|
||||
}
|
||||
const res3 = JSON.parse(cliRes3.stdout);
|
||||
expect(res3.documents).toHaveLength(1);
|
||||
expect(res3.documents[0].documentId).toBe("DOC-CLI-01");
|
||||
});
|
||||
|
||||
test("export CLI command generates resource pack ZIP", async () => {
|
||||
const { root } = setupMockEnv();
|
||||
|
||||
const mockRun = {
|
||||
id: "run-exp-1",
|
||||
corpId: "test-corp-pack",
|
||||
status: "APPROVED",
|
||||
sourceDocumentId: "DOC-EXP-01",
|
||||
createdAt: "2026-09-12T10:00:00Z",
|
||||
document: {
|
||||
id: "DOC-EXP-01",
|
||||
sn: "SN-EXP-01",
|
||||
title: "新零售峰会支出",
|
||||
fields: [
|
||||
{ key: "total_amount", label: "总金额", type: "AMOUNT", value: 8800 },
|
||||
{ key: "reimbursement_reason", label: "报销事由", type: "TEXT", value: "峰会场地租用" }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
// Mock fetch for online calls
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === "string" ? input : (input as any).url ? String((input as any).url) : String(input);
|
||||
if (url.includes("auth/me") || url.includes("get-session")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 0,
|
||||
data: {
|
||||
user: { id: "u-1", name: "Admin", isAdmin: true },
|
||||
tenant: { id: "t-1", name: "测试租户", tenantSlug: "test-pack" }
|
||||
}
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.includes("run-exp-1") || url.includes("approvals")) {
|
||||
return new Response(JSON.stringify({ code: 0, data: mockRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ code: 0, data: {} }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}) as any;
|
||||
|
||||
const outZip = join(root, "exported-by-cli.zip");
|
||||
|
||||
const exportCliRes = await runCli([
|
||||
"webhook",
|
||||
"resource-pack",
|
||||
"export",
|
||||
"run-exp-1",
|
||||
"-o",
|
||||
outZip,
|
||||
"--corp",
|
||||
"test-corp-pack"
|
||||
]);
|
||||
|
||||
if (exportCliRes.isError) {
|
||||
throw new Error(`Export CLI Error: ${exportCliRes.stderr}`);
|
||||
}
|
||||
|
||||
expect(existsSync(outZip)).toBe(true);
|
||||
const parsedOut = JSON.parse(exportCliRes.stdout);
|
||||
expect(parsedOut.recordCount).toBe(1);
|
||||
expect(parsedOut.filePath).toBe(outZip);
|
||||
expect(parsedOut.nextAction).toContain("seal-use webhook resource-pack push");
|
||||
|
||||
// Verify it with preview
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const preview = await previewResourcePack(readFileSync(outZip), "exported-by-cli.zip");
|
||||
expect(preview.documents).toHaveLength(1);
|
||||
expect(preview.documents[0]?.documentId).toBe("DOC-EXP-01");
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "../../domains/seal/webhook-replay.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
exportApprovalRunsToResourcePack,
|
||||
previewMaterialPack,
|
||||
pushMaterialPack,
|
||||
readMaterialPackFile
|
||||
@@ -32,7 +33,7 @@ import type { ParsedArgs } from "../types.js";
|
||||
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../errors.js";
|
||||
|
||||
export async function handleWebhookMaterialPackPreview(
|
||||
export async function handleWebhookResourcePackPreview(
|
||||
filePath: string,
|
||||
filePolicy?: MaterialPackFilePolicyPatch
|
||||
) {
|
||||
@@ -41,6 +42,8 @@ export async function handleWebhookMaterialPackPreview(
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2));
|
||||
}
|
||||
|
||||
export const handleWebhookMaterialPackPreview = handleWebhookResourcePackPreview;
|
||||
|
||||
export async function handleWebhookCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
@@ -201,19 +204,81 @@ export async function handleWebhookCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "material-pack" || action === "material-pack-push") {
|
||||
const operation = action === "material-pack-push" ? "push" : maybeName;
|
||||
const filePath = action === "material-pack-push"
|
||||
if (
|
||||
action === "resource-pack" ||
|
||||
action === "pack" ||
|
||||
action === "material-pack" ||
|
||||
action === "material-pack-push" ||
|
||||
action === "resource-pack-push"
|
||||
) {
|
||||
const operation = (action === "material-pack-push" || action === "resource-pack-push")
|
||||
? "push"
|
||||
: maybeName;
|
||||
|
||||
if (operation === "export" || operation === "pull") {
|
||||
const recordId =
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.id) ??
|
||||
(args.command[3] && !args.command[3].endsWith(".zip") && !args.command[3].startsWith("-") ? args.command[3] : undefined);
|
||||
|
||||
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
|
||||
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
|
||||
const limit = numberOption(args.options.limit) ?? (recordId || recordIds ? undefined : 10);
|
||||
const status = stringOption(args.options.status);
|
||||
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
|
||||
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
|
||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||
const includeAttachments =
|
||||
booleanOption(args.options["no-attachments"]) === true
|
||||
? false
|
||||
: booleanOption(args.options.attachments) !== false;
|
||||
const outputFile =
|
||||
stringOption(args.options.output) ??
|
||||
stringOption(args.options.outputFile) ??
|
||||
stringOption(args.options["output-file"]) ??
|
||||
stringOption(args.options.o) ??
|
||||
stringOption(args.options.file) ??
|
||||
(args.command[3]?.endsWith(".zip") ? args.command[3] : undefined);
|
||||
const toDownloads =
|
||||
booleanOption(args.options.toDownloads) ?? booleanOption(args.options["to-downloads"]) ?? false;
|
||||
|
||||
const result = await exportApprovalRunsToResourcePack(client, corp, {
|
||||
recordId,
|
||||
recordIds,
|
||||
limit,
|
||||
status,
|
||||
startDate,
|
||||
endDate,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
includeAttachments,
|
||||
outputFile,
|
||||
toDownloads
|
||||
});
|
||||
|
||||
console.error(
|
||||
`🟢 成功导出 Webhook 资源包: ${result.filePath} (共 ${result.recordCount} 条单据,${result.attachmentCount} 个附件,${(result.fileSizeBytes / 1024).toFixed(1)} KB)`
|
||||
);
|
||||
console.error(`👉 Next action: ${result.nextAction}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = (action === "material-pack-push" || action === "resource-pack-push")
|
||||
? stringOption(args.options.file) ?? stringOption(args.options.input)
|
||||
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
|
||||
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
|
||||
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
||||
const input = readMaterialPackFile(filePath);
|
||||
if (operation === "preview") {
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
|
||||
return;
|
||||
}
|
||||
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
|
||||
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
let integration: WebhookIntegration;
|
||||
@@ -238,6 +303,8 @@ export async function handleWebhookCommand(
|
||||
materialPackFilePolicy: integration.materialPackFilePolicy,
|
||||
customHeaders: resolveSealCustomHeaders(corp.seal)
|
||||
});
|
||||
console.error(`🟢 Webhook 资源包推送完成 (成功 ${result.results.length} 条单据)`);
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${corp.id} --limit ${result.results.length}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
+29
-6
@@ -272,14 +272,37 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
usage: ["seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "material-pack preview",
|
||||
summary: "Inspect and validate a material pack ZIP or Excel sheet",
|
||||
usage: ["seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]"]
|
||||
name: "resource-pack export",
|
||||
summary: "Export online approval records to a local Webhook resource pack ZIP (alias: pack export)",
|
||||
usage: [
|
||||
"seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]",
|
||||
"seal-use webhook resource-pack export <recordId> [--output <file.zip>] [--corp <corpId>]",
|
||||
"seal-use webhook resource-pack export --record-ids <id1,id2> [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Single approval run record ID to export" },
|
||||
{ flag: "--record-ids <ids>", description: "Comma-separated list of approval run record IDs" },
|
||||
{ flag: "--limit <n>", description: "Limit number of records to export (default: 10)" },
|
||||
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, approved)" },
|
||||
{ flag: "--start-date <YYYY-MM-DD>", description: "Filter records starting from date" },
|
||||
{ flag: "--end-date <YYYY-MM-DD>", description: "Filter records up to date" },
|
||||
{ flag: "--doc-id-prefix <str>", description: "Optional prefix prepended to exported documentId/meetingId" },
|
||||
{ flag: "--doc-id-suffix <str>", description: "Optional suffix appended to exported documentId/meetingId" },
|
||||
{ flag: "--no-attachments", description: "Skip downloading and packaging attachments" },
|
||||
{ flag: "-o, --output <file.zip>", description: "Target ZIP file path" },
|
||||
{ flag: "--to-downloads", description: "Save directly to ~/Downloads" },
|
||||
{ flag: "--corp <corpId>", description: "Source enterprise configuration ID" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "material-pack push",
|
||||
summary: "Upload and push a material pack to webhook endpoint",
|
||||
usage: ["seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
|
||||
name: "resource-pack preview",
|
||||
summary: "Inspect and validate a Webhook resource pack ZIP or Excel sheet (alias: pack preview)",
|
||||
usage: ["seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "resource-pack push",
|
||||
summary: "Upload attachments and push documents from a resource pack ZIP to Webhook (alias: pack push)",
|
||||
usage: ["seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "replay",
|
||||
|
||||
+12
-4
@@ -34,7 +34,11 @@ import { handleToolCommand } from "./commands/tool.js";
|
||||
import { handleToolsListCommand } from "./commands/tools.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleUsersCommand } from "./commands/users.js";
|
||||
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
|
||||
import {
|
||||
handleWebhookCommand,
|
||||
handleWebhookMaterialPackPreview,
|
||||
handleWebhookResourcePackPreview
|
||||
} from "./commands/webhook.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { selectCorp } from "./helpers.js";
|
||||
import {
|
||||
@@ -193,10 +197,14 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
|
||||
if (
|
||||
area === "webhook" &&
|
||||
(action === "resource-pack" || action === "pack" || action === "material-pack") &&
|
||||
maybeName === "preview"
|
||||
) {
|
||||
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
|
||||
await handleWebhookMaterialPackPreview(filePath, materialPackFilePolicyOptions(args.options));
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
|
||||
await handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
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<ResourcePackExportResult> {
|
||||
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<string, DownloadedAttachment[]>();
|
||||
let totalDownloadedCount = 0;
|
||||
|
||||
for (const run of runs) {
|
||||
const rawDoc = run.document as Record<string, unknown> | 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<Record<string, unknown>>;
|
||||
const usedFileNames = new Set<string>();
|
||||
|
||||
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<string>();
|
||||
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<string>();
|
||||
for (const run of runs) {
|
||||
const rawDoc = run.document as Record<string, unknown> | undefined;
|
||||
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
|
||||
for (const f of rawFields) {
|
||||
if (f && typeof f === "object") {
|
||||
const item = f as Record<string, unknown>;
|
||||
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<string, unknown> | 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<string, unknown>();
|
||||
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
|
||||
for (const f of rawFields) {
|
||||
if (f && typeof f === "object") {
|
||||
const item = f as Record<string, unknown>;
|
||||
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<void>((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 <targetCorpId>`
|
||||
};
|
||||
}
|
||||
@@ -6,3 +6,4 @@ export * from "./parse.js";
|
||||
export * from "./attachments.js";
|
||||
export * from "./service.js";
|
||||
export * from "./ready.js";
|
||||
export * from "./export.js";
|
||||
@@ -329,7 +329,7 @@ describe("Webhook material pack", () => {
|
||||
expect(res.activeWebhooks).toHaveLength(1)
|
||||
expect(res.activeWebhooks[0]?.isDefault).toBe(true)
|
||||
expect(res.defaultWebhook).toEqual({ id: "wh-only", name: "唯一通道", mode: "assisted" })
|
||||
expect(res.nextAction).toContain("seal-use webhook material-pack push")
|
||||
expect(res.nextAction).toContain("seal-use webhook resource-pack push")
|
||||
expect(res.statusMessage).toContain("已自动锁定唯一 Webhook 通道")
|
||||
})
|
||||
|
||||
@@ -458,7 +458,8 @@ describe("Webhook material pack", () => {
|
||||
const notFoundRes = await checkWebhookReadiness(client, mockCorp, { filePath: "/tmp/non-existent-pack.zip" })
|
||||
expect(notFoundRes.ready).toBe(false)
|
||||
expect(notFoundRes.materialPack?.valid).toBe(false)
|
||||
expect(notFoundRes.statusMessage).toContain("材料包预检失败")
|
||||
expect(notFoundRes.resourcePack?.valid).toBe(false)
|
||||
expect(notFoundRes.statusMessage).toContain("资源包预检失败")
|
||||
|
||||
const tmpFile = `/tmp/test-material-${Date.now()}.xlsx`
|
||||
const { writeFileSync, unlinkSync } = await import("node:fs")
|
||||
@@ -467,7 +468,9 @@ describe("Webhook material pack", () => {
|
||||
const validRes = await checkWebhookReadiness(client, mockCorp, { filePath: tmpFile })
|
||||
expect(validRes.ready).toBe(true)
|
||||
expect(validRes.materialPack?.valid).toBe(true)
|
||||
expect(validRes.resourcePack?.valid).toBe(true)
|
||||
expect(validRes.materialPack?.documentCount).toBe(1)
|
||||
expect(validRes.resourcePack?.documentCount).toBe(1)
|
||||
expect(validRes.nextAction).toContain(tmpFile)
|
||||
} finally {
|
||||
unlinkSync(tmpFile)
|
||||
|
||||
@@ -111,11 +111,29 @@ function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialFi
|
||||
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
|
||||
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
|
||||
]
|
||||
return specs.flatMap(([label, key, type]) => {
|
||||
const handledLabels = new Set(specs.map(([label]) => label))
|
||||
const fields = specs.flatMap(([label, key, type]) => {
|
||||
const value = cell(row, map, label)
|
||||
if (value == null || value === "") return []
|
||||
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))]
|
||||
})
|
||||
|
||||
// Dynamic non-attachment columns
|
||||
for (const [colLabel, colIdx] of map.entries()) {
|
||||
if (handledLabels.has(colLabel) || isAttachmentColumn(colLabel)) continue
|
||||
const value = row.getCell(colIdx).value
|
||||
if (value == null || value === "") continue
|
||||
const key = colLabel.toLowerCase().replace(/\s+/g, "_")
|
||||
if (typeof value === "number") {
|
||||
fields.push(field(key, colLabel, "NUMBER", value))
|
||||
} else if (value instanceof Date) {
|
||||
fields.push(field(key, colLabel, "DATE", value.toISOString()))
|
||||
} else {
|
||||
fields.push(text(key, colLabel, String(value)))
|
||||
}
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
|
||||
|
||||
@@ -123,16 +123,16 @@ export async function checkWebhookReadiness(
|
||||
statusMessage = "当前企业尚未配置任何 Webhook 集成通道";
|
||||
nextAction = `seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${corpFlag}`;
|
||||
} else if (materialPack && !materialPack.valid) {
|
||||
statusMessage = `材料包预检失败: ${materialPack.errors?.join("; ")}`;
|
||||
nextAction = `seal-use webhook material-pack preview ${materialPack.filePath}${corpFlag}`;
|
||||
statusMessage = `资源包预检失败: ${materialPack.errors?.join("; ")}`;
|
||||
nextAction = `seal-use webhook resource-pack preview ${materialPack.filePath}${corpFlag}`;
|
||||
} else {
|
||||
statusMessage = isSingle
|
||||
? "所有通道正常,已自动锁定唯一 Webhook 通道,等待载入"
|
||||
: `所有通道正常,检测到 ${activeWebhooks.length} 个 Webhook 通道,等待载入`;
|
||||
|
||||
const targetFile = materialPack?.filePath ?? "<材料包.zip>";
|
||||
const targetFile = materialPack?.filePath ?? "<资源包.zip>";
|
||||
const webhookOption = isSingle ? "" : ` --webhook ${defaultWebhook ? defaultWebhook.id : "<webhookIdOrName>"}`;
|
||||
nextAction = `seal-use webhook material-pack push ${targetFile}${webhookOption}${corpFlag}`;
|
||||
nextAction = `seal-use webhook resource-pack push ${targetFile}${webhookOption}${corpFlag}`;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -149,6 +149,7 @@ export async function checkWebhookReadiness(
|
||||
authError,
|
||||
activeWebhooks,
|
||||
defaultWebhook,
|
||||
resourcePack: materialPack,
|
||||
materialPack,
|
||||
statusMessage,
|
||||
nextAction
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import { readFileSync } from "node:fs"
|
||||
import { webhookHeaders } from "./signature.js"
|
||||
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js"
|
||||
import { parseMaterialWorkbook } from "./parse.js"
|
||||
import { parseMaterialWorkbook, type Parsed } from "./parse.js"
|
||||
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js"
|
||||
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult } from "./types.js"
|
||||
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult, type ResourcePackPreview, type ResourcePackPushResult } from "./types.js"
|
||||
import type { MaterialPackFilePolicyPatch } from "./policy.js"
|
||||
|
||||
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
|
||||
@@ -17,7 +17,7 @@ function isZip(buffer: Uint8Array, fileName: string): boolean {
|
||||
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"))
|
||||
}
|
||||
|
||||
function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): void {
|
||||
function validateDocIdDirectories(entries: ZipEntry[], parsed: Parsed[]): void {
|
||||
if (!entries.length) return // xlsx-only mode, skip
|
||||
|
||||
// Extract documentId from dir name: strip @annotation suffix
|
||||
@@ -33,17 +33,23 @@ function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): v
|
||||
|
||||
const errors: string[] = []
|
||||
|
||||
// Every documentId must have a matching root directory (possibly with @annotation)
|
||||
for (const id of documentIds) {
|
||||
if (!zipDocIds.has(id)) {
|
||||
// Documents with declared attachments must have a matching root directory (possibly with @annotation)
|
||||
for (const item of parsed) {
|
||||
const id = item.document.documentId
|
||||
const hasAttachments =
|
||||
item.documentAttachments.length > 0 ||
|
||||
Object.values(item.expenseAttachments).some((arr) => arr.length > 0) ||
|
||||
Object.values(item.personAttachments).some((arr) => arr.length > 0)
|
||||
|
||||
if (hasAttachments && !zipDocIds.has(id)) {
|
||||
errors.push(
|
||||
`Excel 会议编号「${id}」在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
|
||||
`Excel 会议编号「${id}」声明了附件,但在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Every root directory must correspond to a known documentId
|
||||
const docIdSet = new Set(documentIds)
|
||||
const docIdSet = new Set(parsed.map((p) => p.document.documentId))
|
||||
for (const zipDocId of zipDocIds) {
|
||||
if (!docIdSet.has(zipDocId)) {
|
||||
errors.push(
|
||||
@@ -71,7 +77,7 @@ async function prepare(
|
||||
}
|
||||
const parsed = await parseMaterialWorkbook(workbook)
|
||||
// Validate: ZIP root dir names must correspond to documentIds (supports @annotation suffix)
|
||||
validateDocIdDirectories(entries, parsed.map((p) => p.document.documentId))
|
||||
validateDocIdDirectories(entries, parsed)
|
||||
const plans = buildAttachmentPlans(entries, parsed)
|
||||
const documents = parsed.map((item) => item.document)
|
||||
return { entries, parsed, plans, documents, fileBuffer }
|
||||
@@ -168,3 +174,12 @@ export async function pushMaterialPack(
|
||||
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
|
||||
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\\/]/).pop() ?? "material-pack.zip" }
|
||||
}
|
||||
|
||||
export const previewResourcePack = previewMaterialPack
|
||||
export const pushResourcePack = pushMaterialPack
|
||||
export const readResourcePackFile = readMaterialPackFile
|
||||
export {
|
||||
exportApprovalRunsToResourcePack,
|
||||
exportApprovalRunsToResourcePack as exportResourcePack
|
||||
} from "./export.js"
|
||||
|
||||
@@ -32,18 +32,51 @@ export type MaterialPackPreview = {
|
||||
attachmentPlan: MaterialAttachmentPlan[];
|
||||
};
|
||||
|
||||
export type ResourcePackPreview = MaterialPackPreview;
|
||||
|
||||
export type MaterialPackPushResult = {
|
||||
warnings: string[];
|
||||
results: Array<{ documentId: string; document: MaterialDocument; pushResult: unknown }>;
|
||||
};
|
||||
|
||||
export class MaterialPackValidationError extends Error {
|
||||
export type ResourcePackPushResult = MaterialPackPushResult;
|
||||
|
||||
export class ResourcePackValidationError extends Error {
|
||||
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
|
||||
super([`材料包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
|
||||
this.name = "MaterialPackValidationError"
|
||||
super([`webhook 资源包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
|
||||
this.name = "ResourcePackValidationError"
|
||||
}
|
||||
}
|
||||
|
||||
export const MaterialPackValidationError = ResourcePackValidationError;
|
||||
export type MaterialPackValidationError = ResourcePackValidationError;
|
||||
|
||||
export interface ResourcePackExportOptions {
|
||||
recordId?: string;
|
||||
recordIds?: string[];
|
||||
limit?: number;
|
||||
startDate?: string | number;
|
||||
endDate?: string | number;
|
||||
status?: string;
|
||||
outputFile?: string;
|
||||
toDownloads?: boolean;
|
||||
includeAttachments?: boolean;
|
||||
docIdPrefix?: string;
|
||||
docIdSuffix?: string;
|
||||
customHeaders?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface ResourcePackExportResult {
|
||||
filePath: string;
|
||||
corpId: string;
|
||||
corpName: string;
|
||||
recordCount: number;
|
||||
attachmentCount: number;
|
||||
fileSizeBytes: number;
|
||||
exportedAt: string;
|
||||
nextAction: string;
|
||||
}
|
||||
|
||||
export type WebhookReadyResult = {
|
||||
ready: boolean;
|
||||
corp: {
|
||||
@@ -79,6 +112,14 @@ export type WebhookReadyResult = {
|
||||
name: string;
|
||||
mode: string;
|
||||
} | null;
|
||||
resourcePack?: {
|
||||
valid: boolean;
|
||||
filePath: string;
|
||||
fileName: string;
|
||||
documentCount: number;
|
||||
errors?: string[];
|
||||
warnings?: string[];
|
||||
};
|
||||
materialPack?: {
|
||||
valid: boolean;
|
||||
filePath: string;
|
||||
|
||||
Reference in new issue
Block a user