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;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user