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
@@ -792,6 +792,73 @@ describe("corps list & current", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("corps replay-test", () => {
|
||||
test("fails if production corp has no bound test corp", async () => {
|
||||
setupTestEnv();
|
||||
const result = await runCli(["corps", "replay-test", "corp-test"]);
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.stderr).toContain("has no bound test enterprise");
|
||||
expect(result.stderr).toContain("seal-use corps bind-test");
|
||||
});
|
||||
|
||||
test("pulls production record and executes dry-run to bound test enterprise", async () => {
|
||||
setupTestEnv();
|
||||
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
||||
|
||||
const mockRun = {
|
||||
id: "run-prod-001",
|
||||
sourceSystem: "hosecloud",
|
||||
sourceDocumentSN: "BX-PROD-001",
|
||||
sourceDocumentId: "DOC-PROD-001",
|
||||
document: {
|
||||
id: "DOC-PROD-001",
|
||||
sn: "BX-PROD-001",
|
||||
fields: [{ key: "f1", label: "项目", type: "TEXT", value: "团建" }]
|
||||
}
|
||||
};
|
||||
|
||||
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")) {
|
||||
return jsonResponse({ data: { records: [mockRun] } });
|
||||
}
|
||||
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
integrations: [
|
||||
{
|
||||
type: "webhook",
|
||||
id: "wh-1",
|
||||
name: "测试通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: { id: "wh-1", url: "https://test.example/wh" },
|
||||
outgoingResultWebhook: "https://test.example/out",
|
||||
incomingManualResultWebhook: { id: "wh-1", url: "https://test.example/manual" },
|
||||
secret: "sec"
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
}
|
||||
return jsonResponse({ error: "not found" }, 404);
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["corps", "replay-test", "corp-prod", "--dry-run"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toContain("正式企业「Acme Production」");
|
||||
expect(result.stderr).toContain("测试企业「Acme Staging Test」");
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
expect(parsed.sourceCorp.id).toBe("corp-prod");
|
||||
expect(parsed.targetCorp.id).toBe("corp-test");
|
||||
expect(parsed.document.documentSN).toBe("BX-PROD-001");
|
||||
});
|
||||
});
|
||||
|
||||
function mockSealSyncRequests(options: {
|
||||
onMutation?: (method: string, path: string, body?: unknown) => void;
|
||||
} = {}) {
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
formatSyncVersionName,
|
||||
saveRuleMappingSnapshot
|
||||
} from "../../domains/seal/rule-mapping.js";
|
||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
||||
import { selectCorp } from "../helpers.js";
|
||||
import { confirmationRequired, usageError } from "../errors.js";
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
inferCorpIdFromStaffId,
|
||||
booleanOption,
|
||||
jsonObject,
|
||||
numberOption,
|
||||
optionalNumber,
|
||||
optionalString,
|
||||
requiredString,
|
||||
@@ -779,6 +781,117 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "replay-test") {
|
||||
const targetCorpId =
|
||||
maybeName ??
|
||||
stringOption(args.options.corp) ??
|
||||
stringOption(args.options.prodCorp) ??
|
||||
stringOption(args.options["prod-corp"]);
|
||||
const prodCorp = selectCorp(targetCorpId);
|
||||
|
||||
if (!prodCorp.testCorpId) {
|
||||
throw usageError(
|
||||
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
|
||||
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
|
||||
);
|
||||
}
|
||||
|
||||
const testCorp = selectCorp(prodCorp.testCorpId);
|
||||
if (testCorp.environment !== "test") {
|
||||
throw new Error(
|
||||
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments.`
|
||||
);
|
||||
}
|
||||
|
||||
const recordId =
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.id);
|
||||
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
|
||||
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
|
||||
const sn =
|
||||
stringOption(args.options.sn) ??
|
||||
stringOption(args.options.documentSn) ??
|
||||
stringOption(args.options["document-sn"]);
|
||||
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
|
||||
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
|
||||
const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined);
|
||||
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 prodClient = await createSealClient(prodCorp);
|
||||
const testClient = await createSealClient(testCorp);
|
||||
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
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 dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
|
||||
const query: ReplayRecordsQuery = {
|
||||
recordId,
|
||||
recordIds,
|
||||
sn,
|
||||
sns,
|
||||
limit,
|
||||
status,
|
||||
startDate,
|
||||
endDate
|
||||
};
|
||||
|
||||
console.error(
|
||||
`[corps-replay-test] 正式企业「${prodCorp.name}」(${prodCorp.id}) -> 测试企业「${testCorp.name}」(${testCorp.id})`
|
||||
);
|
||||
|
||||
const result = await executeApprovalRunsReplay({
|
||||
query,
|
||||
sourceClient: prodClient,
|
||||
targetClient: testClient,
|
||||
sourceCorp: prodCorp,
|
||||
targetCorp: testCorp,
|
||||
webhookSelector: selector,
|
||||
snPrefix,
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
dryRun
|
||||
});
|
||||
|
||||
if (dryRun) {
|
||||
console.error(
|
||||
`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
|
||||
);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
if (result.totalCount === 1 && result.replayedDocument) {
|
||||
console.error(
|
||||
`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${testCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`
|
||||
);
|
||||
} else {
|
||||
console.error(
|
||||
`🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${testCorp.name}」`
|
||||
);
|
||||
}
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${testCorp.id} --limit ${result.totalCount}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (!result.success) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "switch") {
|
||||
const corpId = maybeName;
|
||||
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
|
||||
|
||||
@@ -47,6 +47,7 @@ function setupMockEnv() {
|
||||
const corpConfig = {
|
||||
id: "test-corp-replay",
|
||||
name: "测试企业重放",
|
||||
environment: "test",
|
||||
sourceType: "seal",
|
||||
seal: {
|
||||
url: "https://test-replay.sealai.cc",
|
||||
@@ -244,4 +245,185 @@ describe("seal-use webhook replay CLI", () => {
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
});
|
||||
|
||||
test("executes batch replay with --limit 2", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
const mockRuns = [
|
||||
mockApprovalRun,
|
||||
{
|
||||
...mockApprovalRun,
|
||||
id: "run-002",
|
||||
sourceDocumentSN: "BX9990002",
|
||||
document: {
|
||||
id: "DOC-998",
|
||||
sn: "BX9990002",
|
||||
fields: [{ key: "f1", label: "项目", type: "TEXT", value: "差旅" }]
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
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")) {
|
||||
return new Response(JSON.stringify({ data: { records: mockRuns } }), {
|
||||
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", "--limit", "2", "--dry-run"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.dryRun).toBe(true);
|
||||
expect(parsed.totalCount).toBe(2);
|
||||
expect(parsed.records.length).toBe(2);
|
||||
expect(parsed.records[0].document.documentSN).toBe("BX9990001");
|
||||
expect(parsed.records[1].document.documentSN).toBe("BX9990002");
|
||||
});
|
||||
|
||||
test("auto-infers bound test enterprise when running from production enterprise", async () => {
|
||||
const enterprises = setupMockEnv();
|
||||
|
||||
// Create production corp bound to test-corp-replay
|
||||
const prodCorpConfig = {
|
||||
id: "prod-corp-main",
|
||||
name: "正式生产企业",
|
||||
environment: "production",
|
||||
sourceType: "seal",
|
||||
testCorpId: "test-corp-replay",
|
||||
seal: {
|
||||
url: "https://prod-main.sealai.cc",
|
||||
tenantSlug: "prod-main",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/system/preferences/approval-style",
|
||||
sourceStatus: "api/v1/source/status",
|
||||
token: "api/v1/auth/token"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "prod-token-123",
|
||||
sealUrl: "https://prod-main.sealai.cc"
|
||||
}
|
||||
};
|
||||
writeFileSync(join(enterprises, "prod-corp-main.json"), JSON.stringify(prodCorpConfig, null, 2));
|
||||
|
||||
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;
|
||||
|
||||
// Running with --corp prod-corp-main: source should be prod, target auto-inferred as test-corp-replay
|
||||
const result = await runCli(["webhook", "replay", "run-001", "--corp", "prod-corp-main", "--dry-run"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.sourceCorp.id).toBe("prod-corp-main");
|
||||
expect(parsed.targetCorp.id).toBe("test-corp-replay");
|
||||
});
|
||||
|
||||
test("blocks replay targeting production enterprise unless --force is specified", async () => {
|
||||
const enterprises = setupMockEnv();
|
||||
|
||||
const prodCorpConfig = {
|
||||
id: "prod-corp-target",
|
||||
name: "生产目标企业",
|
||||
environment: "production",
|
||||
sourceType: "seal",
|
||||
seal: {
|
||||
url: "https://prod-target.sealai.cc",
|
||||
tenantSlug: "prod-target",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/system/preferences/approval-style",
|
||||
sourceStatus: "api/v1/source/status",
|
||||
token: "api/v1/auth/token"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "prod-token-xyz",
|
||||
sealUrl: "https://prod-target.sealai.cc"
|
||||
}
|
||||
};
|
||||
writeFileSync(join(enterprises, "prod-corp-target.json"), JSON.stringify(prodCorpConfig, null, 2));
|
||||
|
||||
// Target is prod-corp-target without --force
|
||||
const blockedResult = await runCli([
|
||||
"webhook",
|
||||
"replay",
|
||||
"run-001",
|
||||
"--target-corp",
|
||||
"prod-corp-target",
|
||||
"--dry-run"
|
||||
]);
|
||||
expect(blockedResult.isError).toBe(true);
|
||||
expect(blockedResult.exitCode).toBe(1);
|
||||
expect(blockedResult.stderr).toContain("标记为生产正式环境");
|
||||
|
||||
// With --force
|
||||
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 forceResult = await runCli([
|
||||
"webhook",
|
||||
"replay",
|
||||
"run-001",
|
||||
"--target-corp",
|
||||
"prod-corp-target",
|
||||
"--force",
|
||||
"--dry-run"
|
||||
]);
|
||||
expect(forceResult.isError).toBe(false);
|
||||
expect(forceResult.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(forceResult.stdout);
|
||||
expect(parsed.targetCorp.id).toBe("prod-corp-target");
|
||||
});
|
||||
});
|
||||
+84
-75
@@ -7,9 +7,9 @@ import * as api from "../../domains/seal/api.js";
|
||||
import { findWebhookIntegration } from "../../domains/seal/api.js";
|
||||
import type { ApprovalRun, WebhookIntegration } from "../../domains/seal/types.js";
|
||||
import {
|
||||
pushWebhookDocument,
|
||||
selectWebhookIntegration,
|
||||
transformApprovalRunToWebhookDocument
|
||||
executeApprovalRunsReplay,
|
||||
resolveReplayCorpPair,
|
||||
type ReplayRecordsQuery
|
||||
} from "../../domains/seal/webhook-replay.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import {
|
||||
booleanOption,
|
||||
materialPackFilePolicyOptions,
|
||||
numberOption,
|
||||
parseWebhookMode,
|
||||
stringOption,
|
||||
webhookRateOption,
|
||||
@@ -88,106 +89,114 @@ export async function handleWebhookCommand(
|
||||
stringOption(args.options.recordId) ??
|
||||
stringOption(args.options["record-id"]) ??
|
||||
stringOption(args.options.id);
|
||||
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
|
||||
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
|
||||
const sn =
|
||||
stringOption(args.options.sn) ??
|
||||
stringOption(args.options.documentSn) ??
|
||||
stringOption(args.options["document-sn"]);
|
||||
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
|
||||
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
||||
|
||||
if (!recordId && !sn) {
|
||||
const limit = numberOption(args.options.limit);
|
||||
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"]);
|
||||
|
||||
if (!recordId && !recordIds && !sn && !sns && limit === undefined) {
|
||||
throw new Error(
|
||||
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--webhook <idOrName>] [--source-corp <corpId>] [--sn-suffix <str>] [--dry-run]"
|
||||
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--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);
|
||||
const sourceCorpId =
|
||||
stringOption(args.options.sourceCorp) ??
|
||||
stringOption(args.options["source-corp"]) ??
|
||||
stringOption(args.options.prodCorp) ??
|
||||
stringOption(args.options["prod-corp"]);
|
||||
|
||||
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 targetCorpId =
|
||||
stringOption(args.options.targetCorp) ??
|
||||
stringOption(args.options["target-corp"]) ??
|
||||
stringOption(args.options.testCorp) ??
|
||||
stringOption(args.options["test-corp"]);
|
||||
|
||||
const force = booleanOption(args.options.force) === true;
|
||||
|
||||
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
|
||||
{
|
||||
sourceCorpId,
|
||||
targetCorpId,
|
||||
activeCorp: corp,
|
||||
force
|
||||
},
|
||||
selectCorp
|
||||
);
|
||||
|
||||
const sourceClient = sourceCorp.id === corp.id ? client : await createNewSealClient(sourceCorp);
|
||||
const targetClient = targetCorp.id === corp.id ? client : await createNewSealClient(targetCorp);
|
||||
|
||||
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,
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
|
||||
const query: ReplayRecordsQuery = {
|
||||
recordId,
|
||||
recordIds,
|
||||
sn,
|
||||
sns,
|
||||
limit,
|
||||
status,
|
||||
startDate,
|
||||
endDate
|
||||
};
|
||||
|
||||
const result = await executeApprovalRunsReplay({
|
||||
query,
|
||||
sourceClient,
|
||||
targetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
webhookSelector: selector,
|
||||
snPrefix,
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
docIdPrefix
|
||||
dryRun
|
||||
});
|
||||
|
||||
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));
|
||||
console.log(JSON.stringify(result, 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`);
|
||||
if (result.success) {
|
||||
if (result.totalCount === 1 && result.replayedDocument) {
|
||||
console.error(
|
||||
`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${targetCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`
|
||||
);
|
||||
} else {
|
||||
console.error(
|
||||
`🟢 成功重放 ${result.successCount} 条单据(来自「${sourceCorp.name}」)至「${targetCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${targetCorp.name}」`
|
||||
);
|
||||
}
|
||||
console.error(`👉 Next action: seal-use approval-runs list --corp ${targetCorp.id} --limit ${result.totalCount}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (!result.success) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +148,15 @@ describe("CLI help execution via runCli", () => {
|
||||
expect(result.stdout).toContain("--dry-run");
|
||||
});
|
||||
|
||||
test("seal-use corps replay-test --help renders replay-test usage and options with exitCode 0", async () => {
|
||||
const result = await runCli(["corps", "replay-test", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.stdout).toContain("seal-use corps replay-test");
|
||||
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);
|
||||
|
||||
+33
-7
@@ -111,6 +111,24 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
],
|
||||
description: "Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."
|
||||
},
|
||||
{
|
||||
name: "replay-test",
|
||||
summary: "Replay approval records from production enterprise to bound test enterprise via Webhook",
|
||||
usage: [
|
||||
"seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<prodCorpId>", description: "Production enterprise ID (default: active enterprise)" },
|
||||
{ flag: "--record-id <id>", description: "Replay a specific approval run ID" },
|
||||
{ flag: "--sn <sn>", description: "Replay a specific document SN" },
|
||||
{ flag: "--limit <n>", description: "Batch replay latest N records from production (default: 1)" },
|
||||
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, failed, rejected)" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration on test enterprise" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
||||
],
|
||||
description: "Pulls production approval records from the production enterprise and replays them into the bound test enterprise's Webhook channel for rule verification."
|
||||
},
|
||||
{
|
||||
name: "add-hose",
|
||||
summary: "Add a Hose/Ekuaibao enterprise configuration",
|
||||
@@ -247,21 +265,25 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
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>]"
|
||||
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
||||
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-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: "--limit <n>", description: "Batch replay latest N records from source enterprise" },
|
||||
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, failed, rejected)" },
|
||||
{ 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: "--source-corp <corpId>", description: "Source enterprise where records reside (alias: --prod-corp)" },
|
||||
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed (alias: --test-corp)" },
|
||||
{ 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" }
|
||||
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" },
|
||||
{ flag: "--force", description: "Allow replaying to a production enterprise" }
|
||||
],
|
||||
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."
|
||||
description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -349,13 +371,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
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>]"
|
||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
||||
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
||||
{ flag: "--status <status>", description: "Filter records by status" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where the approval record resides" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
|
||||
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
||||
]
|
||||
|
||||
@@ -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