Add formal to test enterprise webhook replay capability
This commit is contained in:
1 parent
ce066206df
commit
35720fa36a
14 files changed
+1305
-263
No files matched your search
@@ -121,6 +121,7 @@ describe("sealTools", () => {
|
||||
expect(sealTools.find((item) => item.name === "seal_webhook_add")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_webhook_update")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_webhook_delete")).toBeDefined();
|
||||
expect(sealTools.find((item) => item.name === "seal_webhook_replay")).toBeDefined();
|
||||
});
|
||||
|
||||
test("includes deploy hosecloud tools", () => {
|
||||
|
||||
@@ -5,9 +5,11 @@ import { randomBytes } from "node:crypto";
|
||||
import * as api from "./api.js";
|
||||
import { defaultSealUrl, getHoseEnterpriseUrl, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { createSealClientForToken } from "../../core/http/factory.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../core/config/manager.js";
|
||||
import { createSealClient, createSealClientForToken } from "../../core/http/factory.js";
|
||||
import { searchApprovalContent } from "./search.js";
|
||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "./webhook-replay.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
@@ -1214,6 +1216,84 @@ export const sealTools = [
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_replay",
|
||||
description: "将正式(生产)企业或指定企业的审批记录通过 Webhook 渠道重放到测试企业进行规则回归与模拟验证",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional().describe("待重放的单条审批记录 ID"),
|
||||
sn: z.string().optional().describe("待重放的单据编号 (sourceDocumentSN)"),
|
||||
sourceCorpId: z.string().optional().describe("单据来源企业 ID (若省略,基于绑定关系自动解析为正式企业)"),
|
||||
targetCorpId: z.string().optional().describe("重放目标企业 ID (若省略,基于绑定关系自动解析为测试企业)"),
|
||||
webhook: z.string().optional().describe("目标 Webhook 通道 ID 或名称"),
|
||||
limit: z.number().optional().describe("批量重放单据数量 (默认 1)"),
|
||||
status: z.string().optional().describe("单据状态过滤 (例如 completed, failed 等)"),
|
||||
snPrefix: z.string().optional().describe("重放单号前缀"),
|
||||
snSuffix: z.string().optional().describe("重放单号后缀"),
|
||||
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
|
||||
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
recordId?: string;
|
||||
sn?: string;
|
||||
sourceCorpId?: string;
|
||||
targetCorpId?: string;
|
||||
webhook?: string;
|
||||
limit?: number;
|
||||
status?: string;
|
||||
snPrefix?: string;
|
||||
snSuffix?: string;
|
||||
dryRun?: boolean;
|
||||
force?: boolean;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const selectCorpFn = (id?: string) => {
|
||||
const corps = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
return resolveCorpConfig(
|
||||
corps,
|
||||
{
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corpId: id
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
};
|
||||
|
||||
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
|
||||
{
|
||||
sourceCorpId: params.sourceCorpId,
|
||||
targetCorpId: params.targetCorpId,
|
||||
activeCorp: context.corp,
|
||||
force: params.force
|
||||
},
|
||||
selectCorpFn
|
||||
);
|
||||
|
||||
const sourceClient = sourceCorp.id === context.corp.id ? client : await createSealClient(sourceCorp);
|
||||
const targetClient = targetCorp.id === context.corp.id ? client : await createSealClient(targetCorp);
|
||||
|
||||
return executeApprovalRunsReplay({
|
||||
query: {
|
||||
recordId: params.recordId,
|
||||
sn: params.sn,
|
||||
limit: params.limit,
|
||||
status: params.status
|
||||
},
|
||||
sourceClient,
|
||||
targetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
webhookSelector: params.webhook,
|
||||
snPrefix: params.snPrefix,
|
||||
snSuffix: params.snSuffix,
|
||||
dryRun: params.dryRun
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_runs_search",
|
||||
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
|
||||
|
||||
@@ -5,9 +5,13 @@ import {
|
||||
extractWebhookInfo,
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
resolveReplayCorpPair,
|
||||
ensureTestWebhookIntegration,
|
||||
executeApprovalRunsReplay,
|
||||
ALLOWED_WEBHOOK_FIELD_TYPES
|
||||
} from "./webhook-replay.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "./types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("webhook-replay domain", () => {
|
||||
const mockWebhookIntegration: WebhookIntegration = {
|
||||
@@ -222,4 +226,138 @@ describe("webhook-replay domain", () => {
|
||||
// Empty integrations
|
||||
expect(() => selectWebhookIntegration([])).toThrow(/未配置任何 Webhook 集成通道/);
|
||||
});
|
||||
|
||||
describe("resolveReplayCorpPair", () => {
|
||||
const prodCorp = {
|
||||
id: "corp-prod",
|
||||
name: "生产企业",
|
||||
environment: "production",
|
||||
sourceType: "hose",
|
||||
testCorpId: "corp-test",
|
||||
seal: {
|
||||
url: "https://prod.sealai.cc",
|
||||
tenantSlug: "prod",
|
||||
endpoints: { approvalStylePreferences: "api/pref" }
|
||||
},
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
staffId: "s1",
|
||||
corpId: "c1",
|
||||
appKey: "k",
|
||||
appSecurity: "s"
|
||||
}
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const testCorp = {
|
||||
id: "corp-test",
|
||||
name: "测试企业",
|
||||
environment: "test",
|
||||
sourceType: "seal",
|
||||
prodCorpId: "corp-prod",
|
||||
seal: {
|
||||
url: "https://test.sealai.cc",
|
||||
tenantSlug: "test",
|
||||
endpoints: { approvalStylePreferences: "api/pref" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "tok",
|
||||
sealUrl: "https://test.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "seal"
|
||||
}
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const dummyCorpMap = new Map<string, CorpConfig>([
|
||||
["corp-prod", prodCorp],
|
||||
["corp-test", testCorp]
|
||||
]);
|
||||
|
||||
const mockSelectCorp = (id?: string): CorpConfig => {
|
||||
const found = id ? dummyCorpMap.get(id) : undefined;
|
||||
if (!found) throw new Error(`Unknown corp: ${id}`);
|
||||
return found;
|
||||
};
|
||||
|
||||
test("auto-infers testCorp as target when activeCorp is production and has testCorpId", () => {
|
||||
const pair = resolveReplayCorpPair({ activeCorp: prodCorp }, mockSelectCorp);
|
||||
expect(pair.sourceCorp.id).toBe("corp-prod");
|
||||
expect(pair.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
|
||||
test("auto-infers prodCorp as source when activeCorp is test and has prodCorpId", () => {
|
||||
const pair = resolveReplayCorpPair({ activeCorp: testCorp }, mockSelectCorp);
|
||||
expect(pair.sourceCorp.id).toBe("corp-prod");
|
||||
expect(pair.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
|
||||
test("respects explicit sourceCorpId and targetCorpId", () => {
|
||||
const pair = resolveReplayCorpPair(
|
||||
{ sourceCorpId: "corp-prod", targetCorpId: "corp-test", activeCorp: prodCorp },
|
||||
mockSelectCorp
|
||||
);
|
||||
expect(pair.sourceCorp.id).toBe("corp-prod");
|
||||
expect(pair.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
|
||||
test("blocks pushing to production enterprise when target is production and force is false", () => {
|
||||
expect(() =>
|
||||
resolveReplayCorpPair(
|
||||
{ sourceCorpId: "corp-test", targetCorpId: "corp-prod", activeCorp: testCorp, force: false },
|
||||
mockSelectCorp
|
||||
)
|
||||
).toThrow(/标记为生产正式环境/);
|
||||
});
|
||||
|
||||
test("permits pushing to production enterprise when force is true", () => {
|
||||
const pair = resolveReplayCorpPair(
|
||||
{ sourceCorpId: "corp-test", targetCorpId: "corp-prod", activeCorp: testCorp, force: true },
|
||||
mockSelectCorp
|
||||
);
|
||||
expect(pair.targetCorp.id).toBe("corp-prod");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ensureTestWebhookIntegration", () => {
|
||||
test("automatically provisions assisted test webhook if none exist in test corp", async () => {
|
||||
let savedIntegration: any = null;
|
||||
const testCorp = {
|
||||
id: "corp-test",
|
||||
name: "测试企业",
|
||||
environment: "test",
|
||||
sourceType: "seal",
|
||||
seal: {
|
||||
url: "https://test.sealai.cc",
|
||||
tenantSlug: "test",
|
||||
endpoints: { approvalStylePreferences: "api/pref" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "tok",
|
||||
sealUrl: "https://test.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "seal"
|
||||
}
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const mockClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: { integrations: [] } })
|
||||
}),
|
||||
post: (_url: string, opts: any) => {
|
||||
savedIntegration = opts.json.integrations[0];
|
||||
return {
|
||||
json: async () => ({ data: { success: true } })
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const integration = await ensureTestWebhookIntegration(mockClient, testCorp);
|
||||
expect(integration.name).toBe("(Seal测-回放通道)");
|
||||
expect(integration.mode).toBe("assisted");
|
||||
expect(savedIntegration).toBeDefined();
|
||||
expect(savedIntegration.name).toBe("(Seal测-回放通道)");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { KyInstance } from "ky";
|
||||
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";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import * as api from "./api.js";
|
||||
|
||||
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
|
||||
"TEXT",
|
||||
@@ -185,6 +188,12 @@ export function selectWebhookIntegration(
|
||||
}
|
||||
|
||||
if (integrations.length > 1) {
|
||||
const replayHook = integrations.find(
|
||||
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
|
||||
);
|
||||
if (replayHook) {
|
||||
return replayHook;
|
||||
}
|
||||
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||||
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
|
||||
}
|
||||
@@ -195,3 +204,386 @@ export function selectWebhookIntegration(
|
||||
`seal-use webhook add --name <name> --result-url <url>${corpId ? ` --corp ${corpId}` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
export interface ResolveReplayCorpPairOptions {
|
||||
sourceCorpId?: string;
|
||||
targetCorpId?: string;
|
||||
activeCorp: CorpConfig;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface ReplayCorpPair {
|
||||
sourceCorp: CorpConfig;
|
||||
targetCorp: CorpConfig;
|
||||
}
|
||||
|
||||
export function resolveReplayCorpPair(
|
||||
options: ResolveReplayCorpPairOptions,
|
||||
selectCorpFn: (id?: string) => CorpConfig
|
||||
): ReplayCorpPair {
|
||||
let sourceCorp: CorpConfig;
|
||||
let targetCorp: CorpConfig;
|
||||
|
||||
const { sourceCorpId, targetCorpId, activeCorp, force } = options;
|
||||
|
||||
if (sourceCorpId && targetCorpId) {
|
||||
sourceCorp = selectCorpFn(sourceCorpId);
|
||||
targetCorp = selectCorpFn(targetCorpId);
|
||||
} else if (sourceCorpId && !targetCorpId) {
|
||||
sourceCorp = selectCorpFn(sourceCorpId);
|
||||
if (sourceCorp.testCorpId) {
|
||||
targetCorp = selectCorpFn(sourceCorp.testCorpId);
|
||||
} else if (activeCorp.id !== sourceCorp.id && activeCorp.environment === "test") {
|
||||
targetCorp = activeCorp;
|
||||
} else {
|
||||
targetCorp = activeCorp;
|
||||
}
|
||||
} else if (!sourceCorpId && targetCorpId) {
|
||||
targetCorp = selectCorpFn(targetCorpId);
|
||||
if (targetCorp.prodCorpId) {
|
||||
sourceCorp = selectCorpFn(targetCorp.prodCorpId);
|
||||
} else if (activeCorp.id !== targetCorp.id) {
|
||||
sourceCorp = activeCorp;
|
||||
} else {
|
||||
sourceCorp = activeCorp;
|
||||
}
|
||||
} else {
|
||||
// Neither source nor target explicitly given
|
||||
if (activeCorp.environment === "test") {
|
||||
targetCorp = activeCorp;
|
||||
if (activeCorp.prodCorpId) {
|
||||
sourceCorp = selectCorpFn(activeCorp.prodCorpId);
|
||||
} else {
|
||||
sourceCorp = activeCorp;
|
||||
}
|
||||
} else if (activeCorp.environment === "production") {
|
||||
sourceCorp = activeCorp;
|
||||
if (activeCorp.testCorpId) {
|
||||
targetCorp = selectCorpFn(activeCorp.testCorpId);
|
||||
} else {
|
||||
targetCorp = activeCorp;
|
||||
}
|
||||
} else {
|
||||
sourceCorp = activeCorp;
|
||||
targetCorp = activeCorp;
|
||||
}
|
||||
}
|
||||
|
||||
// Safety guard: prevent pushing replay test records to production
|
||||
if (targetCorp.environment === "production" && !force) {
|
||||
throw new CliError(
|
||||
`目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` +
|
||||
`为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。`,
|
||||
1,
|
||||
`seal-use webhook replay --target-corp <testCorpId>${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
return { sourceCorp, targetCorp };
|
||||
}
|
||||
|
||||
export async function ensureTestWebhookIntegration(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig,
|
||||
selector?: string
|
||||
): Promise<WebhookIntegration> {
|
||||
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
if (selector || integrations.length > 0) {
|
||||
return selectWebhookIntegration(integrations, selector, corp.id);
|
||||
}
|
||||
|
||||
// If 0 integrations and target is a test enterprise: automatically provision an assisted replay channel
|
||||
if (corp.environment === "test" || corp.id.toLowerCase().includes("test")) {
|
||||
console.error(`[webhook-replay] 测试企业「${corp.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);
|
||||
const sealUrl = (corp.seal.url ?? (corp.source as any)?.sealUrl ?? `https://${corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
||||
const created = await api.addWebhookIntegration(
|
||||
client,
|
||||
sealUrl,
|
||||
{
|
||||
name: "(Seal测-回放通道)",
|
||||
mode: "assisted",
|
||||
outgoingResultWebhook: `${sealUrl}/api/v1/integrations/webhook/replay-mock-callback`
|
||||
},
|
||||
corp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
return created;
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
`当前租户「${corp.name}」未配置任何 Webhook 集成通道。`,
|
||||
1,
|
||||
`seal-use webhook add --name <name> --result-url <url> --corp ${corp.id}`
|
||||
);
|
||||
}
|
||||
|
||||
export interface ReplayRecordsQuery {
|
||||
recordId?: string;
|
||||
recordIds?: string[];
|
||||
sn?: string;
|
||||
sns?: string[];
|
||||
limit?: number;
|
||||
status?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
}
|
||||
|
||||
export interface ReplayApprovalRunsOptions {
|
||||
query: ReplayRecordsQuery;
|
||||
sourceClient: KyInstance;
|
||||
targetClient: KyInstance;
|
||||
sourceCorp: CorpConfig;
|
||||
targetCorp: CorpConfig;
|
||||
webhookSelector?: string;
|
||||
snPrefix?: string;
|
||||
snSuffix?: string;
|
||||
docIdPrefix?: string;
|
||||
docIdSuffix?: string;
|
||||
dryRun?: boolean;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface ReplayExecutionRecord {
|
||||
originalRecord: {
|
||||
id: string;
|
||||
sourceSystem?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
};
|
||||
replayedDocument?: {
|
||||
documentSN: string;
|
||||
documentId: string;
|
||||
fieldCount: number;
|
||||
};
|
||||
document?: WebhookReplayDocument;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
pushResult?: unknown;
|
||||
}
|
||||
|
||||
export interface ReplayExecutionResult {
|
||||
success: boolean;
|
||||
dryRun: boolean;
|
||||
sourceCorp: { id: string; name: string; environment?: string };
|
||||
targetCorp: { id: string; name: string; environment?: string };
|
||||
targetWebhook?: {
|
||||
id: string;
|
||||
name: string;
|
||||
mode: string;
|
||||
incomingDocumentWebhookUrl: string;
|
||||
};
|
||||
totalCount: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
// Backward-compatible fields for single-record replay
|
||||
originalRecord?: {
|
||||
id: string;
|
||||
sourceSystem?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
};
|
||||
replayedDocument?: {
|
||||
documentSN: string;
|
||||
documentId: string;
|
||||
fieldCount: number;
|
||||
};
|
||||
document?: WebhookReplayDocument;
|
||||
pushResult?: unknown;
|
||||
records: ReplayExecutionRecord[];
|
||||
}
|
||||
|
||||
export async function executeApprovalRunsReplay(
|
||||
options: ReplayApprovalRunsOptions
|
||||
): Promise<ReplayExecutionResult> {
|
||||
const {
|
||||
query,
|
||||
sourceClient,
|
||||
targetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
webhookSelector,
|
||||
snPrefix,
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
dryRun,
|
||||
fetchFn = fetch
|
||||
} = options;
|
||||
|
||||
let runs: ApprovalRun[] = [];
|
||||
|
||||
if (query.recordId) {
|
||||
const run = await api.getApprovalRun(sourceClient, query.recordId);
|
||||
runs.push(run);
|
||||
} else if (query.recordIds && query.recordIds.length > 0) {
|
||||
for (const id of query.recordIds) {
|
||||
runs.push(await api.getApprovalRun(sourceClient, id));
|
||||
}
|
||||
} else if (query.sn) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: query.sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${query.sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
} else if (query.sns && query.sns.length > 0) {
|
||||
for (const sn of query.sns) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
}
|
||||
} else if (query.limit !== undefined) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
limit: query.limit,
|
||||
status: query.status,
|
||||
startDate: query.startDate,
|
||||
endDate: query.endDate
|
||||
});
|
||||
if (!search.records.length) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未检索到符合条件的审批记录。`);
|
||||
}
|
||||
runs = search.records;
|
||||
} else {
|
||||
throw new Error(
|
||||
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
|
||||
);
|
||||
}
|
||||
|
||||
const docs = runs.map((run) => ({
|
||||
run,
|
||||
doc: transformApprovalRunToWebhookDocument(run, {
|
||||
snPrefix,
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix
|
||||
})
|
||||
}));
|
||||
|
||||
if (dryRun) {
|
||||
let integrationInfo = {
|
||||
id: "preview-webhook",
|
||||
name: webhookSelector ?? "预览目标通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhookUrl: `${targetCorp.seal.url}/api/v1/integrations/webhook/preview`
|
||||
};
|
||||
|
||||
try {
|
||||
const integrations = await api.listWebhookIntegrations(
|
||||
targetClient,
|
||||
targetCorp.seal.endpoints.approvalStylePreferences
|
||||
);
|
||||
if (integrations.length > 0) {
|
||||
const matched = selectWebhookIntegration(integrations, webhookSelector, targetCorp.id);
|
||||
integrationInfo = {
|
||||
id: matched.id,
|
||||
name: matched.name,
|
||||
mode: matched.mode,
|
||||
incomingDocumentWebhookUrl: matched.incomingDocumentWebhook.url
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// In dryRun, keep preview info if list fails
|
||||
}
|
||||
|
||||
const records: ReplayExecutionRecord[] = docs.map(({ run, doc }) => ({
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
document: doc,
|
||||
success: true
|
||||
}));
|
||||
|
||||
const isSingle = records.length === 1;
|
||||
return {
|
||||
dryRun: true,
|
||||
success: true,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment },
|
||||
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment },
|
||||
targetWebhook: integrationInfo,
|
||||
totalCount: records.length,
|
||||
successCount: records.length,
|
||||
failureCount: 0,
|
||||
originalRecord: isSingle ? records[0]!.originalRecord : undefined,
|
||||
document: isSingle ? records[0]!.document : undefined,
|
||||
records
|
||||
};
|
||||
}
|
||||
|
||||
const integration = await ensureTestWebhookIntegration(targetClient, targetCorp, webhookSelector);
|
||||
const targetWebhook = {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
mode: integration.mode,
|
||||
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
|
||||
};
|
||||
|
||||
const records: ReplayExecutionRecord[] = [];
|
||||
let successCount = 0;
|
||||
let failureCount = 0;
|
||||
|
||||
for (const { run, doc } of docs) {
|
||||
console.error(`[webhook-replay] 正在向 Webhook 通道「${integration.name}」推送单据: ${doc.documentSN}...`);
|
||||
try {
|
||||
const pushResult = await pushWebhookDocument(
|
||||
integration.incomingDocumentWebhook.url,
|
||||
integration.secret,
|
||||
doc,
|
||||
fetchFn
|
||||
);
|
||||
records.push({
|
||||
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,
|
||||
success: true
|
||||
});
|
||||
successCount += 1;
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||
records.push({
|
||||
originalRecord: {
|
||||
id: run.id,
|
||||
sourceSystem: run.sourceSystem,
|
||||
sourceDocumentSN: run.sourceDocumentSN,
|
||||
sourceDocumentId: run.sourceDocumentId
|
||||
},
|
||||
replayedDocument: {
|
||||
documentSN: doc.documentSN,
|
||||
documentId: doc.documentId,
|
||||
fieldCount: doc.fields.length
|
||||
},
|
||||
error: errorMsg,
|
||||
success: false
|
||||
});
|
||||
failureCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const isSingle = records.length === 1;
|
||||
return {
|
||||
success: failureCount === 0,
|
||||
dryRun: false,
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment },
|
||||
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment },
|
||||
targetWebhook,
|
||||
totalCount: records.length,
|
||||
successCount,
|
||||
failureCount,
|
||||
originalRecord: isSingle ? records[0]!.originalRecord : undefined,
|
||||
replayedDocument: isSingle ? records[0]!.replayedDocument : undefined,
|
||||
pushResult: isSingle ? records[0]!.pushResult : undefined,
|
||||
records
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user