494 lines
20 KiB
TypeScript
494 lines
20 KiB
TypeScript
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 { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
|
import { existsSync } from "node:fs";
|
|
import { runCapability, 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 {
|
|
executeApprovalRunsReplay,
|
|
resolveReplayCorpPair,
|
|
type ReplayRecordsQuery
|
|
} from "../../domains/seal/replay/webhook.js";
|
|
import { executeHoseOutboundReplay } from "../../domains/seal/replay/hose-outbound.js";
|
|
import {
|
|
checkWebhookReadiness,
|
|
exportApprovalRunsToResourcePack,
|
|
previewMaterialPack,
|
|
pushMaterialPack,
|
|
readMaterialPackFile
|
|
} from "../../domains/seal/material-pack/index.js";
|
|
import {
|
|
booleanOption,
|
|
materialPackFilePolicyOptions,
|
|
numberOption,
|
|
parseWebhookMode,
|
|
stringOption,
|
|
webhookRateOption,
|
|
webhookShowSecretOption
|
|
} from "../parser.js";
|
|
import { outputOptions, printJson } from "../printer.js";
|
|
import type { ParsedArgs } from "../types.js";
|
|
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
|
|
import { CliError, confirmationRequired, usageError, validationError } from "../errors.js";
|
|
|
|
export async function handleWebhookResourcePackPreview(
|
|
filePath: string,
|
|
filePolicy?: MaterialPackFilePolicyPatch
|
|
) {
|
|
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
|
const input = readMaterialPackFile(filePath);
|
|
printJson(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy));
|
|
}
|
|
|
|
export const handleWebhookMaterialPackPreview = handleWebhookResourcePackPreview;
|
|
|
|
export async function handleWebhookCommand(
|
|
action: string | undefined,
|
|
maybeName: string | undefined,
|
|
client: Awaited<ReturnType<typeof createSealClient>>,
|
|
corp: CorpConfig,
|
|
args: ParsedArgs
|
|
) {
|
|
if (action === "ready" || action === "status") {
|
|
const filePath = maybeName ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
|
const result = await checkWebhookReadiness(client, corp, {
|
|
filePath,
|
|
webhook: stringOption(args.options.webhook) ?? stringOption(args.options.selector)
|
|
});
|
|
console.error(`[webhook-ready] 企业环境: ${result.corp.name} (${result.corp.id}) [${result.stateMode}]`);
|
|
if (result.corp.tenant?.name) {
|
|
console.error(`[webhook-ready] 租户信息: ${result.corp.tenant.name} (${result.corp.tenant.id})`);
|
|
}
|
|
console.error(`[webhook-ready] 凭证状态: ${result.authStatus === "ok" ? "OK" : `异常 (${result.authError})`}`);
|
|
console.error(`[webhook-ready] Webhook 通道: ${result.activeWebhooks.length} 个可用`);
|
|
for (const hook of result.activeWebhooks) {
|
|
const defLabel = hook.isDefault ? " [默认通道]" : "";
|
|
console.error(` - ${hook.name} (${hook.id}) mode=${hook.mode}${defLabel}`);
|
|
}
|
|
if (result.materialPack) {
|
|
console.error(
|
|
`[webhook-ready] 材料包预检: ${
|
|
result.materialPack.valid
|
|
? `通过 (${result.materialPack.documentCount} 单)`
|
|
: `失败 (${result.materialPack.errors?.join("; ")})`
|
|
}`
|
|
);
|
|
}
|
|
if (result.ready) {
|
|
console.error(`🟢 ${result.statusMessage}`);
|
|
console.error(`👉 Next action: ${result.nextAction}`);
|
|
} else {
|
|
console.error(`🔴 准备阶段未通过: ${result.statusMessage}`);
|
|
console.error(`👉 Next action: ${result.nextAction}`);
|
|
}
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
if (action === "replay") {
|
|
const recordId =
|
|
maybeName ??
|
|
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);
|
|
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>] [--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"]) ??
|
|
stringOption(args.options.prodCorp) ??
|
|
stringOption(args.options["prod-corp"]);
|
|
|
|
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 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 confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
|
|
|
const channel =
|
|
stringOption(args.options.channel) ??
|
|
(booleanOption(args.options["hose-outbound"]) || booleanOption(args.options.outbound) ? "hose-outbound" : undefined);
|
|
|
|
if (channel === "hose-outbound" || channel === "outbound") {
|
|
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
|
|
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
|
|
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
|
|
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
|
|
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
|
|
const targetSignKey =
|
|
stringOption(args.options.signKey) ??
|
|
stringOption(args.options["sign-key"]) ??
|
|
stringOption(args.options.webhook);
|
|
|
|
const result = await executeHoseOutboundReplay({
|
|
sourceCorp,
|
|
targetCorp,
|
|
sourceClient,
|
|
targetClient,
|
|
sn,
|
|
recordId,
|
|
flowId,
|
|
messageId,
|
|
nodeId,
|
|
corporationId,
|
|
rejectionNum,
|
|
targetSignKey,
|
|
dryRun,
|
|
confirm,
|
|
force
|
|
});
|
|
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
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,
|
|
dryRun,
|
|
confirm
|
|
});
|
|
|
|
if (dryRun) {
|
|
console.error(
|
|
`[webhook-replay] 预览模式:已成功从 ${sourceCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
|
|
);
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
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}`);
|
|
printJson(result, outputOptions(args.options));
|
|
if (!result.success) {
|
|
// The partial-failure signal must survive cli.ts overwriting process.exitCode with the
|
|
// dispatch result, so it is raised as a CliError instead of set on the process.
|
|
throw new CliError(
|
|
`Webhook replay finished with failures (success ${result.successCount}, failed ${result.failureCount}).`,
|
|
1,
|
|
`seal-use approval-runs list --corp ${targetCorp.id} --limit ${result.totalCount}`
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (
|
|
action === "resource-pack" ||
|
|
action === "pack" ||
|
|
action === "material-pack" ||
|
|
action === "material-pack-push" ||
|
|
action === "resource-pack-push"
|
|
) {
|
|
const operation = (action === "material-pack-push" || action === "resource-pack-push")
|
|
? "push"
|
|
: maybeName;
|
|
|
|
if (operation === "export" || operation === "pull") {
|
|
const recordId =
|
|
stringOption(args.options.recordId) ??
|
|
stringOption(args.options["record-id"]) ??
|
|
stringOption(args.options.id) ??
|
|
(args.command[3] && !args.command[3].endsWith(".zip") && !args.command[3].startsWith("-") ? args.command[3] : undefined);
|
|
|
|
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
|
|
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
|
|
|
|
const limit = numberOption(args.options.limit) ?? (recordId || recordIds ? undefined : 10);
|
|
const status = stringOption(args.options.status);
|
|
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
|
|
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
|
|
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
|
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
|
const includeAttachments =
|
|
booleanOption(args.options["no-attachments"]) === true
|
|
? false
|
|
: booleanOption(args.options.attachments) !== false;
|
|
const outputFile =
|
|
stringOption(args.options.output) ??
|
|
stringOption(args.options.outputFile) ??
|
|
stringOption(args.options["output-file"]) ??
|
|
stringOption(args.options.o) ??
|
|
stringOption(args.options.file) ??
|
|
(args.command[3]?.endsWith(".zip") ? args.command[3] : undefined);
|
|
const toDownloads =
|
|
booleanOption(args.options.toDownloads) ?? booleanOption(args.options["to-downloads"]) ?? false;
|
|
|
|
const result = await exportApprovalRunsToResourcePack(client, corp, {
|
|
recordId,
|
|
recordIds,
|
|
limit,
|
|
status,
|
|
startDate,
|
|
endDate,
|
|
docIdPrefix,
|
|
docIdSuffix,
|
|
includeAttachments,
|
|
outputFile,
|
|
toDownloads
|
|
});
|
|
|
|
console.error(
|
|
`🟢 成功导出 Webhook 资源包: ${result.filePath} (共 ${result.recordCount} 条单据,${result.attachmentCount} 个附件,${(result.fileSizeBytes / 1024).toFixed(1)} KB)`
|
|
);
|
|
console.error(`👉 Next action: ${result.nextAction}`);
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
|
|
const filePath = (action === "material-pack-push" || action === "resource-pack-push")
|
|
? stringOption(args.options.file) ?? stringOption(args.options.input)
|
|
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
|
|
|
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
|
|
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
|
const input = readMaterialPackFile(filePath);
|
|
if (operation === "preview") {
|
|
printJson(await previewMaterialPack(input.fileBuffer, input.fileName), outputOptions(args.options));
|
|
return;
|
|
}
|
|
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
|
|
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
|
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
|
let integration: WebhookIntegration;
|
|
if (selector) {
|
|
integration = findWebhookIntegration(integrations, selector);
|
|
} else if (integrations.length === 1) {
|
|
integration = integrations[0]!;
|
|
console.error(`👉 自动锁定唯一可用 Webhook 通道: ${integration.name} (${integration.id})`);
|
|
} else if (integrations.length > 1) {
|
|
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
|
throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
|
|
} else {
|
|
throw new CliError(
|
|
"当前租户未配置任何 Webhook 集成通道。",
|
|
1,
|
|
`seal-use webhook add --name <name> --result-url <url> --corp ${corp.id}`
|
|
);
|
|
}
|
|
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
|
|
webhookUrl: integration.incomingDocumentWebhook.url,
|
|
secret: integration.secret,
|
|
materialPackFilePolicy: integration.materialPackFilePolicy,
|
|
customHeaders: resolveSealCustomHeaders(corp.seal)
|
|
});
|
|
console.error(`🟢 Webhook 资源包推送完成 (成功 ${result.results.length} 条单据)`);
|
|
console.error(`👉 Next action: seal-use approval-runs list --corp ${corp.id} --limit ${result.results.length}`);
|
|
printJson(result, outputOptions(args.options));
|
|
return;
|
|
}
|
|
if (action === "list") {
|
|
await runCapability(
|
|
"sealWebhookList",
|
|
client,
|
|
corp,
|
|
{
|
|
query: stringOption(args.options.query) ?? stringOption(args.options.keyword),
|
|
includeSecret: webhookShowSecretOption(args.options)
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "get" || action === "find") {
|
|
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
|
|
if (!selector) throw new Error("Usage: seal-use webhook get <idOrName> [--show-secret]");
|
|
await runCapability(
|
|
"sealWebhookGet",
|
|
client,
|
|
corp,
|
|
{
|
|
selector,
|
|
includeSecret: webhookShowSecretOption(args.options)
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "add" || action === "create") {
|
|
const name = stringOption(args.options.name) ?? maybeName;
|
|
const outgoingResultWebhook =
|
|
stringOption(args.options.resultUrl) ??
|
|
stringOption(args.options["result-url"]) ??
|
|
stringOption(args.options.outgoingResultWebhook) ??
|
|
stringOption(args.options["outgoing-result-webhook"]);
|
|
if (!name || !outgoingResultWebhook) {
|
|
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
|
|
}
|
|
const autoApprovalRate = webhookRateOption(args.options);
|
|
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
|
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
|
await runCapability(
|
|
"sealWebhookAdd",
|
|
client,
|
|
corp,
|
|
{
|
|
name,
|
|
mode: parseWebhookMode(stringOption(args.options.mode)),
|
|
outgoingResultWebhook,
|
|
autoApprovalRate,
|
|
secret: stringOption(args.options.secret),
|
|
materialPackFilePolicy,
|
|
dryRun
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "update") {
|
|
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
|
|
if (!selector) throw new Error("Usage: seal-use webhook update <idOrName> [options]");
|
|
const secret = stringOption(args.options.secret);
|
|
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
|
|
if (secret !== undefined && rotateSecret) {
|
|
throw usageError("Use either --secret or --rotate-secret, not both");
|
|
}
|
|
const name = stringOption(args.options.name);
|
|
const mode = parseWebhookMode(stringOption(args.options.mode));
|
|
const outgoingResultWebhook =
|
|
stringOption(args.options.resultUrl) ??
|
|
stringOption(args.options["result-url"]) ??
|
|
stringOption(args.options.outgoingResultWebhook) ??
|
|
stringOption(args.options["outgoing-result-webhook"]);
|
|
const autoApprovalRate = webhookRateOption(args.options);
|
|
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
|
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
|
if (
|
|
name === undefined &&
|
|
mode === undefined &&
|
|
outgoingResultWebhook === undefined &&
|
|
autoApprovalRate === undefined &&
|
|
secret === undefined &&
|
|
!rotateSecret &&
|
|
materialPackFilePolicy === undefined &&
|
|
!dryRun
|
|
) {
|
|
throw usageError("Webhook update requires at least one field option");
|
|
}
|
|
await runCapability(
|
|
"sealWebhookUpdate",
|
|
client,
|
|
corp,
|
|
{
|
|
selector,
|
|
name,
|
|
mode,
|
|
outgoingResultWebhook,
|
|
autoApprovalRate,
|
|
secret,
|
|
rotateSecret,
|
|
materialPackFilePolicy,
|
|
dryRun
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (action === "delete") {
|
|
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
|
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
|
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
|
|
if (booleanOption(args.options.yes) !== true && !dryRun) {
|
|
throw confirmationRequired(
|
|
"Refusing to delete Webhook integration without --yes",
|
|
`seal-use webhook delete ${selector} --corp ${corp.id} --yes`
|
|
);
|
|
}
|
|
await runCapability(
|
|
"sealWebhookDelete",
|
|
client,
|
|
corp,
|
|
{
|
|
selector,
|
|
confirm: true,
|
|
dryRun
|
|
},
|
|
outputOptions(args.options)
|
|
);
|
|
return;
|
|
}
|
|
|
|
throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
|
}
|