Add approval run to webhook replay capability
This commit is contained in:
1 parent
4adecf990d
commit
770fd9d672
10 files changed
+972
-125
No files matched your search
@@ -10,6 +10,7 @@ import { runTool, runToolResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
|
||||
export async function handleApprovalRunsCommand(
|
||||
action: string | undefined,
|
||||
@@ -18,6 +19,11 @@ export async function handleApprovalRunsCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "replay") {
|
||||
await handleWebhookCommand("replay", maybeName, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "summary") {
|
||||
const result = await runToolResult(
|
||||
"seal_approval_runs_summary",
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.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-replay-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");
|
||||
|
||||
// Create enterprises dir
|
||||
const fs = require("node:fs");
|
||||
fs.mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
// Write test enterprise config
|
||||
const corpConfig = {
|
||||
id: "test-corp-replay",
|
||||
name: "测试企业重放",
|
||||
sourceType: "seal",
|
||||
seal: {
|
||||
url: "https://test-replay.sealai.cc",
|
||||
tenantSlug: "test-replay",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/system/preferences/approval-style",
|
||||
sourceStatus: "api/v1/source/status",
|
||||
token: "api/v1/auth/token"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "mock-token-xyz",
|
||||
sealUrl: "https://test-replay.sealai.cc"
|
||||
}
|
||||
};
|
||||
writeFileSync(join(enterprises, "test-corp-replay.json"), JSON.stringify(corpConfig, null, 2));
|
||||
|
||||
// Write global config
|
||||
writeFileSync(
|
||||
join(root, "config.json"),
|
||||
JSON.stringify({ defaultCorpId: "test-corp-replay", stateful: true }, null, 2)
|
||||
);
|
||||
|
||||
return enterprises;
|
||||
}
|
||||
|
||||
const mockApprovalRun = {
|
||||
id: "run-001",
|
||||
status: "completed",
|
||||
sourceSystem: "hosecloud",
|
||||
sourceDocumentSN: "BX9990001",
|
||||
sourceDocumentId: "DOC-999",
|
||||
createdAt: 1789115000000,
|
||||
document: {
|
||||
id: "DOC-999",
|
||||
sn: "BX9990001",
|
||||
fields: [
|
||||
{ key: "cost_type", label: "费用类型", type: "TEXT", value: "打车" },
|
||||
{ key: "amount", label: "金额", type: "AMOUNT", value: { amount: 120 } },
|
||||
{ key: "ref_doc", label: "关联申请", type: "REFERENCE", value: "SQ001" }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
const mockWebhookIntegrations = [
|
||||
{
|
||||
type: "webhook",
|
||||
id: "wh-integration-1",
|
||||
name: "默认重放通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: {
|
||||
id: "wh_endpoint_1",
|
||||
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/document"
|
||||
},
|
||||
outgoingResultWebhook: "https://example.com/result",
|
||||
incomingManualResultWebhook: {
|
||||
id: "wh_endpoint_1",
|
||||
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/manual-result"
|
||||
},
|
||||
secret: "mock-secret-456"
|
||||
}
|
||||
];
|
||||
|
||||
describe("seal-use webhook replay CLI", () => {
|
||||
test("fails with usage error if neither recordId nor sn is provided", async () => {
|
||||
setupMockEnv();
|
||||
const result = await runCli(["webhook", "replay"]);
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.stderr).toContain("Usage: seal-use webhook replay");
|
||||
});
|
||||
|
||||
test("executes dry-run preview and strips unallowed types like REFERENCE", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli([
|
||||
"webhook",
|
||||
"replay",
|
||||
"run-001",
|
||||
"--dry-run",
|
||||
"--sn-suffix",
|
||||
"_replay"
|
||||
]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toContain("预览模式");
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
expect(parsed.originalRecord.sourceDocumentSN).toBe("BX9990001");
|
||||
expect(parsed.document.documentSN).toBe("BX9990001_replay");
|
||||
expect(parsed.document.documentId).toBe("DOC-999_replay");
|
||||
// REFERENCE must be normalized to TEXT
|
||||
const refField = parsed.document.fields.find((f: any) => f.key === "ref_doc");
|
||||
expect(refField.type).toBe("TEXT");
|
||||
});
|
||||
|
||||
test("executes live webhook replay with successful response", async () => {
|
||||
setupMockEnv();
|
||||
let pushedBody: any = null;
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (requestUrl.includes("/integrations/webhook/wh_endpoint_1/document")) {
|
||||
let rawBody = init?.body;
|
||||
if (typeof rawBody !== "string" && typeof input === "object" && "text" in input) {
|
||||
rawBody = await (input as Request).clone().text();
|
||||
}
|
||||
pushedBody = JSON.parse(String(rawBody));
|
||||
return new Response(
|
||||
JSON.stringify({ data: { success: true, documentId: "spawned-run-doc-123" } }),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["webhook", "replay", "run-001"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toContain("成功重放单据");
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.pushResult.data.success).toBe(true);
|
||||
expect(pushedBody.documentSN).toBe("BX9990001");
|
||||
});
|
||||
|
||||
test("approval-runs replay routes to webhook replay", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (requestUrl.includes("/api/v1/approvals/run-001")) {
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockWebhookIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["approval-runs", "replay", "run-001", "--dry-run"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
});
|
||||
});
|
||||
+117
-2
@@ -1,10 +1,16 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { createSealClient as createNewSealClient } from "../../core/http/factory.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { runTool } from "../helpers.js";
|
||||
import { runTool, selectCorp } from "../helpers.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { findWebhookIntegration } from "../../domains/seal/api.js";
|
||||
import type { WebhookIntegration } from "../../domains/seal/types.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "../../domains/seal/types.js";
|
||||
import {
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
transformApprovalRunToWebhookDocument
|
||||
} from "../../domains/seal/webhook-replay.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
previewMaterialPack,
|
||||
@@ -76,6 +82,115 @@ export async function handleWebhookCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "replay") {
|
||||
const recordId =
|
||||
maybeName ??
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.id);
|
||||
const sn =
|
||||
stringOption(args.options.sn) ??
|
||||
stringOption(args.options.documentSn) ??
|
||||
stringOption(args.options["document-sn"]);
|
||||
|
||||
if (!recordId && !sn) {
|
||||
throw new Error(
|
||||
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--webhook <idOrName>] [--source-corp <corpId>] [--sn-suffix <str>] [--dry-run]"
|
||||
);
|
||||
}
|
||||
|
||||
const sourceCorpId = stringOption(args.options.sourceCorp) ?? stringOption(args.options["source-corp"]);
|
||||
const sourceCorp = sourceCorpId ? selectCorp(sourceCorpId) : corp;
|
||||
const sourceClient = sourceCorp.id === corp.id ? client : await createNewSealClient(sourceCorp);
|
||||
|
||||
let run: ApprovalRun;
|
||||
if (recordId) {
|
||||
run = await api.getApprovalRun(sourceClient, recordId);
|
||||
} else {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
|
||||
}
|
||||
run = search.records[0]!;
|
||||
}
|
||||
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
const integration = selectWebhookIntegration(integrations, selector, corp.id);
|
||||
|
||||
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
|
||||
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
|
||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||
const doc = transformApprovalRunToWebhookDocument(run, {
|
||||
snSuffix,
|
||||
snPrefix,
|
||||
docIdSuffix,
|
||||
docIdPrefix
|
||||
});
|
||||
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
if (dryRun) {
|
||||
const dryRunOutput = {
|
||||
dryRun: true,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name },
|
||||
targetCorp: { id: corp.id, name: corp.name },
|
||||
targetWebhook: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
mode: integration.mode,
|
||||
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
|
||||
},
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
document: doc
|
||||
};
|
||||
console.error(
|
||||
`[webhook-replay] 预览模式:已成功从 ${sourceCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
|
||||
);
|
||||
console.log(JSON.stringify(dryRunOutput, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
process.stderr.write(`[webhook-replay] 正在向 Webhook 通道「${integration.name}」推送单据: ${doc.documentSN}...\n`);
|
||||
const pushResult = await pushWebhookDocument(
|
||||
integration.incomingDocumentWebhook.url,
|
||||
integration.secret,
|
||||
doc
|
||||
);
|
||||
const result = {
|
||||
success: true,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name },
|
||||
targetCorp: { id: corp.id, name: corp.name },
|
||||
targetWebhook: {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
mode: integration.mode,
|
||||
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
|
||||
},
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
replayedDocument: {
|
||||
documentSN: doc.documentSN,
|
||||
documentId: doc.documentId,
|
||||
fieldCount: doc.fields.length
|
||||
},
|
||||
pushResult
|
||||
};
|
||||
console.error(`🟢 成功重放单据「${doc.documentSN}」至 ${corp.name} (${integration.name})`);
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${corp.id} --limit 1`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "material-pack" || action === "material-pack-push") {
|
||||
const operation = action === "material-pack-push" ? "push" : maybeName;
|
||||
const filePath = action === "material-pack-push"
|
||||
|
||||
@@ -130,6 +130,24 @@ describe("CLI help execution via runCli", () => {
|
||||
expect(result.stdout).not.toContain("seal-use simulation");
|
||||
});
|
||||
|
||||
test("seal-use webhook replay --help renders replay usage and options with exitCode 0", async () => {
|
||||
const result = await runCli(["webhook", "replay", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use webhook replay");
|
||||
expect(result.stdout).toContain("--sn-suffix");
|
||||
expect(result.stdout).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("seal-use approval-runs replay --help renders replay usage and options with exitCode 0", async () => {
|
||||
const result = await runCli(["approval-runs", "replay", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use approval-runs replay");
|
||||
expect(result.stdout).toContain("--sn-suffix");
|
||||
expect(result.stdout).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("seal-use corps unknown-cmd --help exits with code 2", async () => {
|
||||
const result = await runCli(["corps", "unknown-cmd", "--help"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
|
||||
@@ -222,6 +222,24 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
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: "replay",
|
||||
summary: "Replay an existing approval record into a Webhook channel",
|
||||
usage: [
|
||||
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID to replay" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN if recordId not given" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration (auto-locks if only one exists)" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where the approval record resides (default: active)" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
|
||||
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
|
||||
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" }
|
||||
],
|
||||
description: "Extracts structured form fields from any historical approval record (Webhook or Hose source), sanitizes field types, and pushes a new document to the target Webhook channel."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -302,6 +320,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "bridge",
|
||||
summary: "Inspect browser bridge integration payload",
|
||||
usage: ["seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "replay",
|
||||
summary: "Replay approval run record into a Webhook integration",
|
||||
usage: [
|
||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where the approval record resides" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
transformApprovalRunToWebhookDocument,
|
||||
sanitizeFieldForWebhook,
|
||||
extractWebhookInfo,
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
ALLOWED_WEBHOOK_FIELD_TYPES
|
||||
} from "./webhook-replay.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
|
||||
describe("webhook-replay domain", () => {
|
||||
const mockWebhookIntegration: WebhookIntegration = {
|
||||
type: "webhook",
|
||||
id: "wh-int-1",
|
||||
name: "测试通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: {
|
||||
id: "wh_hook_abc123",
|
||||
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/document"
|
||||
},
|
||||
outgoingResultWebhook: "https://example.com/callback",
|
||||
incomingManualResultWebhook: {
|
||||
id: "wh_hook_abc123",
|
||||
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/manual-result"
|
||||
},
|
||||
secret: "test-secret-key-xyz",
|
||||
materialPackFilePolicy: {
|
||||
minFileSizeBytes: 500,
|
||||
allowedExtensions: [".pdf"]
|
||||
}
|
||||
};
|
||||
|
||||
test("sanitizeFieldForWebhook preserves allowed types and normalizes unknown types", () => {
|
||||
// Known allowed types
|
||||
for (const type of ALLOWED_WEBHOOK_FIELD_TYPES) {
|
||||
const field = { key: "f1", label: "F1", type, value: "val" };
|
||||
expect(sanitizeFieldForWebhook(field, 0)).toEqual({
|
||||
key: "f1",
|
||||
label: "F1",
|
||||
type,
|
||||
value: "val"
|
||||
});
|
||||
}
|
||||
|
||||
// Hose REFERENCE type -> TEXT
|
||||
const refField = {
|
||||
key: "ref",
|
||||
label: "关联单据",
|
||||
type: "REFERENCE",
|
||||
value: "DOC123"
|
||||
};
|
||||
expect(sanitizeFieldForWebhook(refField, 1)).toEqual({
|
||||
key: "ref",
|
||||
label: "关联单据",
|
||||
type: "TEXT",
|
||||
value: "DOC123"
|
||||
});
|
||||
|
||||
// Object value with unknown type -> OBJECT
|
||||
const objField = {
|
||||
key: "extra",
|
||||
label: "附加信息",
|
||||
type: "CUSTOM_UNKNOWN",
|
||||
value: { foo: "bar" }
|
||||
};
|
||||
expect(sanitizeFieldForWebhook(objField, 2)).toEqual({
|
||||
key: "extra",
|
||||
label: "附加信息",
|
||||
type: "OBJECT",
|
||||
value: { foo: "bar" }
|
||||
});
|
||||
|
||||
// Recursive LIST fields normalization
|
||||
const listField = {
|
||||
key: "items",
|
||||
label: "明细列表",
|
||||
type: "LIST",
|
||||
value: [
|
||||
[
|
||||
{ key: "cost", label: "金额", type: "AMOUNT", value: { amount: 50 } },
|
||||
{ key: "subRef", label: "引用", type: "REFERENCE", value: "R1" }
|
||||
]
|
||||
]
|
||||
};
|
||||
const sanitizedList = sanitizeFieldForWebhook(listField, 3);
|
||||
expect(sanitizedList.type).toBe("LIST");
|
||||
const rows = sanitizedList.value as any[][];
|
||||
expect(rows[0]![0].type).toBe("AMOUNT");
|
||||
expect(rows[0]![1].type).toBe("TEXT");
|
||||
});
|
||||
|
||||
test("transformApprovalRunToWebhookDocument builds clean document payload with prefix/suffix support", () => {
|
||||
const run: ApprovalRun = {
|
||||
id: "run-uuid-1",
|
||||
status: "failed",
|
||||
sourceSystem: "hosecloud",
|
||||
sourceDocumentSN: "BX2026090001",
|
||||
sourceDocumentId: "ID01DocABC",
|
||||
createdAt: 1789115000000,
|
||||
document: {
|
||||
id: "doc-uuid-1",
|
||||
sn: "BX2026090001",
|
||||
fields: [
|
||||
{ key: "title", label: "标题", type: "TEXT", value: "出差报销" },
|
||||
{ key: "supplement", label: "补充说明", type: "REFERENCE", value: "none" }
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
// Default transformation
|
||||
const doc = transformApprovalRunToWebhookDocument(run);
|
||||
expect(doc.type).toBe("document");
|
||||
expect(doc.documentSN).toBe("BX2026090001");
|
||||
expect(doc.documentId).toBe("ID01DocABC");
|
||||
expect(doc.startTime).toBe(1789115000);
|
||||
expect(doc.fields.length).toBe(2);
|
||||
expect(doc.fields[0]!.type).toBe("TEXT");
|
||||
expect(doc.fields[1]!.type).toBe("TEXT");
|
||||
|
||||
// With prefix and suffix
|
||||
const modified = transformApprovalRunToWebhookDocument(run, {
|
||||
snPrefix: "TEST_",
|
||||
snSuffix: "_v2"
|
||||
});
|
||||
expect(modified.documentSN).toBe("TEST_BX2026090001_v2");
|
||||
expect(modified.documentId).toBe("TEST_ID01DocABC_v2");
|
||||
});
|
||||
|
||||
test("extractWebhookInfo extracts webhookId, baseUrl, and documentEndpoint", () => {
|
||||
const info = extractWebhookInfo("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
|
||||
expect(info.baseUrl).toBe("https://staging.sealai.cc");
|
||||
expect(info.webhookId).toBe("wh_abc_123");
|
||||
expect(info.documentEndpoint).toBe("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
|
||||
|
||||
expect(() => extractWebhookInfo("https://staging.sealai.cc/invalid/path")).toThrow(
|
||||
/Webhook URL 必须包含/
|
||||
);
|
||||
});
|
||||
|
||||
test("pushWebhookDocument signs and posts payload", async () => {
|
||||
let capturedUrl = "";
|
||||
let capturedMethod = "";
|
||||
let capturedHeaders: Record<string, string> = {};
|
||||
let capturedBody = "";
|
||||
|
||||
const mockFetch = (async (url: any, init: any) => {
|
||||
capturedUrl = String(url);
|
||||
capturedMethod = init.method;
|
||||
capturedHeaders = init.headers;
|
||||
capturedBody = init.body;
|
||||
return new Response(JSON.stringify({ data: { success: true, documentId: "doc-out-1" } }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}) as any;
|
||||
|
||||
const doc = {
|
||||
type: "document" as const,
|
||||
documentId: "doc-1",
|
||||
documentSN: "SN-1",
|
||||
startTime: 123456,
|
||||
fields: [{ key: "f1", label: "L1", type: "TEXT", value: "v1" }]
|
||||
};
|
||||
|
||||
const res = await pushWebhookDocument(
|
||||
mockWebhookIntegration.incomingDocumentWebhook.url,
|
||||
mockWebhookIntegration.secret,
|
||||
doc,
|
||||
mockFetch
|
||||
);
|
||||
|
||||
expect(capturedUrl).toBe(mockWebhookIntegration.incomingDocumentWebhook.url);
|
||||
expect(capturedMethod).toBe("POST");
|
||||
expect(capturedHeaders["Authorization"]).toBe(`Bearer ${mockWebhookIntegration.secret}`);
|
||||
expect(capturedHeaders["x-webhook-signature"]).toBeDefined();
|
||||
expect(capturedHeaders["x-webhook-timestamp"]).toBeDefined();
|
||||
expect(capturedHeaders["x-webhook-nonce"]).toBeDefined();
|
||||
expect(JSON.parse(capturedBody)).toEqual(doc);
|
||||
expect(res).toEqual({ data: { success: true, documentId: "doc-out-1" } });
|
||||
});
|
||||
|
||||
test("pushWebhookDocument throws error when endpoint returns failure status", async () => {
|
||||
const mockFetch = (async () => {
|
||||
return new Response("Invalid parameter: missing field", { status: 400 });
|
||||
}) as any;
|
||||
|
||||
const doc = {
|
||||
type: "document" as const,
|
||||
documentId: "doc-1",
|
||||
documentSN: "SN-1",
|
||||
startTime: null,
|
||||
fields: []
|
||||
};
|
||||
|
||||
expect(
|
||||
pushWebhookDocument(
|
||||
mockWebhookIntegration.incomingDocumentWebhook.url,
|
||||
mockWebhookIntegration.secret,
|
||||
doc,
|
||||
mockFetch
|
||||
)
|
||||
).rejects.toThrow(/Webhook 单据推送失败 \(400\)/);
|
||||
});
|
||||
|
||||
test("selectWebhookIntegration auto-locks single integration and selects by query", () => {
|
||||
// Single integration
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration])).toBe(mockWebhookIntegration);
|
||||
|
||||
// Multiple integrations - select by name
|
||||
const second: WebhookIntegration = {
|
||||
...mockWebhookIntegration,
|
||||
id: "wh-int-2",
|
||||
name: "备用通道"
|
||||
};
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration, second], "备用通道")).toBe(second);
|
||||
expect(selectWebhookIntegration([mockWebhookIntegration, second], "wh-int-1")).toBe(mockWebhookIntegration);
|
||||
|
||||
// Ambiguous without selector
|
||||
expect(() => selectWebhookIntegration([mockWebhookIntegration, second])).toThrow(/存在多个 Webhook 通道/);
|
||||
|
||||
// Empty integrations
|
||||
expect(() => selectWebhookIntegration([])).toThrow(/未配置任何 Webhook 集成通道/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
import type { MaterialField } from "./material-pack/types.js";
|
||||
import { webhookHeaders } from "./material-pack/signature.js";
|
||||
import { CliError } from "../../cli/errors.js";
|
||||
|
||||
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
|
||||
"TEXT",
|
||||
"NUMBER",
|
||||
"DATE",
|
||||
"AMOUNT",
|
||||
"PERSON",
|
||||
"ATTACHMENT",
|
||||
"DATE_RANGE",
|
||||
"DEPARTMENT",
|
||||
"LIST",
|
||||
"CITY",
|
||||
"OBJECT"
|
||||
]);
|
||||
|
||||
export interface WebhookReplayDocument {
|
||||
type: "document";
|
||||
documentId: string;
|
||||
documentSN: string;
|
||||
startTime: number | null;
|
||||
fields: MaterialField[];
|
||||
}
|
||||
|
||||
export interface WebhookReplayTransformOptions {
|
||||
snSuffix?: string;
|
||||
snPrefix?: string;
|
||||
docIdSuffix?: string;
|
||||
docIdPrefix?: string;
|
||||
}
|
||||
|
||||
export function sanitizeFieldForWebhook(field: unknown, index: number): MaterialField {
|
||||
const f = field && typeof field === "object" ? (field as Record<string, unknown>) : {};
|
||||
const rawType = typeof f.type === "string" ? f.type.toUpperCase().trim() : "";
|
||||
const key =
|
||||
typeof f.key === "string" && f.key.trim()
|
||||
? f.key.trim()
|
||||
: typeof f.label === "string" && f.label.trim()
|
||||
? f.label.trim()
|
||||
: `field_${index}`;
|
||||
const label = typeof f.label === "string" && f.label.trim() ? f.label.trim() : key;
|
||||
|
||||
let value = f.value !== undefined ? f.value : null;
|
||||
|
||||
// Recursively sanitize rows inside LIST fields
|
||||
if (rawType === "LIST" && Array.isArray(value)) {
|
||||
value = value.map((row) => {
|
||||
if (Array.isArray(row)) {
|
||||
return row.map((nested, nestedIdx) => sanitizeFieldForWebhook(nested, nestedIdx));
|
||||
}
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
let type = rawType;
|
||||
if (!ALLOWED_WEBHOOK_FIELD_TYPES.has(type)) {
|
||||
if (Array.isArray(value)) {
|
||||
type = "LIST";
|
||||
} else if (value && typeof value === "object") {
|
||||
type = "OBJECT";
|
||||
} else if (typeof value === "number") {
|
||||
type = "NUMBER";
|
||||
} else {
|
||||
type = "TEXT";
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
key,
|
||||
label,
|
||||
type,
|
||||
value
|
||||
};
|
||||
}
|
||||
|
||||
export function transformApprovalRunToWebhookDocument(
|
||||
record: ApprovalRun,
|
||||
options: WebhookReplayTransformOptions = {}
|
||||
): WebhookReplayDocument {
|
||||
const rawDoc = record.document as Record<string, unknown> | undefined;
|
||||
|
||||
const originalSN =
|
||||
record.sourceDocumentSN ??
|
||||
(typeof rawDoc?.sn === "string" ? rawDoc.sn : undefined) ??
|
||||
(typeof rawDoc?.sourceDocumentSN === "string" ? rawDoc.sourceDocumentSN : undefined) ??
|
||||
record.id;
|
||||
|
||||
const originalDocId =
|
||||
record.sourceDocumentId ??
|
||||
(typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ??
|
||||
(typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ??
|
||||
record.documentId ??
|
||||
record.id;
|
||||
|
||||
const snPrefix = options.snPrefix ?? "";
|
||||
const snSuffix = options.snSuffix ?? "";
|
||||
const docIdPrefix = options.docIdPrefix ?? snPrefix;
|
||||
const docIdSuffix = options.docIdSuffix ?? snSuffix;
|
||||
|
||||
const documentSN = `${snPrefix}${originalSN}${snSuffix}`;
|
||||
const documentId = `${docIdPrefix}${originalDocId}${docIdSuffix}`;
|
||||
|
||||
const startTime =
|
||||
typeof rawDoc?.sourceStartTime === "number"
|
||||
? rawDoc.sourceStartTime
|
||||
: typeof record.createdAt === "number"
|
||||
? Math.floor(record.createdAt / 1000)
|
||||
: null;
|
||||
|
||||
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
|
||||
const fields = rawFields.map((field, idx) => sanitizeFieldForWebhook(field, idx));
|
||||
|
||||
return {
|
||||
type: "document",
|
||||
documentId,
|
||||
documentSN,
|
||||
startTime,
|
||||
fields
|
||||
};
|
||||
}
|
||||
|
||||
export function extractWebhookInfo(url: string): { baseUrl: string; webhookId: string; documentEndpoint: string } {
|
||||
const parsed = new URL(url);
|
||||
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
|
||||
if (!match) {
|
||||
throw new Error(`Webhook URL 必须包含 /webhook/{webhookId}/document,收到: ${url}`);
|
||||
}
|
||||
const webhookId = match[1]!;
|
||||
const baseUrl = `${parsed.protocol}//${parsed.host}`;
|
||||
const documentEndpoint = `${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`;
|
||||
return { baseUrl, webhookId, documentEndpoint };
|
||||
}
|
||||
|
||||
export async function pushWebhookDocument(
|
||||
endpointUrl: string,
|
||||
secret: string,
|
||||
document: WebhookReplayDocument,
|
||||
fetchFn: typeof fetch = fetch
|
||||
): Promise<unknown> {
|
||||
const { webhookId, documentEndpoint } = extractWebhookInfo(endpointUrl);
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
...webhookHeaders({ webhookId, ...document }, secret)
|
||||
};
|
||||
|
||||
const response = await fetchFn(documentEndpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(document)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Webhook 单据推送失败 (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function selectWebhookIntegration(
|
||||
integrations: WebhookIntegration[],
|
||||
selector?: string,
|
||||
corpId?: string
|
||||
): WebhookIntegration {
|
||||
if (selector) {
|
||||
const normalized = selector.trim().toLowerCase();
|
||||
const found = integrations.find(
|
||||
(item) =>
|
||||
item.id.toLowerCase() === normalized ||
|
||||
item.name.toLowerCase() === normalized ||
|
||||
item.incomingDocumentWebhook.id.toLowerCase() === normalized
|
||||
);
|
||||
if (!found) {
|
||||
const available = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`未找到匹配 "${selector}" 的 Webhook 集成通道。可用通道: [${available}]`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
if (integrations.length === 1) {
|
||||
return integrations[0]!;
|
||||
}
|
||||
|
||||
if (integrations.length > 1) {
|
||||
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
"当前租户未配置任何 Webhook 集成通道。",
|
||||
1,
|
||||
`seal-use webhook add --name <name> --result-url <url>${corpId ? ` --corp ${corpId}` : ""}`
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user