import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { existsSync } from "node:fs"; import { runTool } 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 { checkWebhookReadiness, previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "../../domains/seal/material-pack/index.js"; import { booleanOption, materialPackFilePolicyOptions, parseWebhookMode, stringOption, webhookRateOption, webhookShowSecretOption } from "../parser.js"; import { outputOptions } from "../printer.js"; import type { ParsedArgs } from "../types.js"; import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js"; import { CliError, confirmationRequired, usageError } from "../errors.js"; export async function handleWebhookMaterialPackPreview( filePath: string, filePolicy?: MaterialPackFilePolicyPatch ) { if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`); const input = readMaterialPackFile(filePath); console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2)); } export async function handleWebhookCommand( action: string | undefined, maybeName: string | undefined, client: Awaited>, 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}`); } console.log(JSON.stringify(result, null, 2)); return; } if (action === "material-pack" || action === "material-pack-push") { const operation = action === "material-pack-push" ? "push" : maybeName; const filePath = action === "material-pack-push" ? stringOption(args.options.file) ?? stringOption(args.options.input) : args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input); if (!filePath) throw new Error("Usage: seal-use webhook material-pack <材料包.zip>"); if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`); const input = readMaterialPackFile(filePath); if (operation === "preview") { console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2)); return; } if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <材料包.zip>"); 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 new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook 指定目标通道。`); } else { throw new CliError( "当前租户未配置任何 Webhook 集成通道。", 1, `seal-use webhook add --name --result-url --corp ${corp.id}` ); } const result = await pushMaterialPack(input.fileBuffer, input.fileName, { webhookUrl: integration.incomingDocumentWebhook.url, secret: integration.secret, materialPackFilePolicy: integration.materialPackFilePolicy }); console.log(JSON.stringify(result, null, 2)); return; } if (action === "list") { await runTool( "seal_webhook_list", 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 [--show-secret]"); await runTool( "seal_webhook_get", 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 --result-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 runTool( "seal_webhook_add", 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 [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 runTool( "seal_webhook_update", 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 [--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 runTool( "seal_webhook_delete", client, corp, { selector, confirm: true, dryRun }, outputOptions(args.options) ); return; } throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`); }