import type { KyInstance } from "ky"; import { existsSync } from "node:fs"; import type { CorpConfig } from "../../../core/config/types.js"; import { loadGlobalConfig } from "../../../core/config/loader.js"; import * as api from "../api.js"; import type { WebhookIntegration } from "../types.js"; import { previewMaterialPack, readMaterialPackFile } from "./service.js"; import type { WebhookReadyResult } from "./types.js"; export async function checkWebhookReadiness( client: KyInstance, corp: CorpConfig, options: { filePath?: string; webhook?: string } = {} ): Promise { const globalConfig = loadGlobalConfig(); const stateMode = globalConfig.stateful ? "stateful" : "stateless"; let authStatus: "ok" | "error" = "ok"; let authError: string | undefined; let tenantInfo: WebhookReadyResult["corp"]["tenant"]; let userInfo: WebhookReadyResult["corp"]["user"]; try { const me = await api.getMe(client); userInfo = { id: me.user.id, name: me.user.name, isAdmin: me.user.isAdmin }; tenantInfo = { id: me.tenant.id, name: me.tenant.name, tenantSlug: me.tenant.tenantSlug, corporationName: me.tenant.hoseCorpConfig?.corporationName }; } catch (err) { authStatus = "error"; authError = err instanceof Error ? err.message : String(err); } let rawWebhooks: WebhookIntegration[] = []; if (authStatus === "ok") { try { rawWebhooks = await api.listWebhookIntegrations( client, corp.seal.endpoints.approvalStylePreferences ); } catch (err) { authStatus = "error"; authError = `读取 Webhook 配置失败: ${err instanceof Error ? err.message : String(err)}`; } } const isSingle = rawWebhooks.length === 1; const activeWebhooks = rawWebhooks.map((w) => ({ id: w.id, name: w.name, mode: w.mode, incomingDocumentWebhookUrl: w.incomingDocumentWebhook.url, outgoingResultWebhookUrl: w.outgoingResultWebhook, autoApprovalRate: w.autoApprovalRate, ...(isSingle ? { isDefault: true } : {}) })); const defaultWebhook = isSingle ? { id: rawWebhooks[0]!.id, name: rawWebhooks[0]!.name, mode: rawWebhooks[0]!.mode } : null; const materialPackWebhook = options.webhook ? api.findWebhookIntegration(rawWebhooks, options.webhook) : isSingle ? rawWebhooks[0] : undefined; let materialPack: WebhookReadyResult["materialPack"]; if (options.filePath) { if (!existsSync(options.filePath)) { materialPack = { valid: false, filePath: options.filePath, fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath, documentCount: 0, errors: [`文件不存在: ${options.filePath}`] }; } else { try { const input = readMaterialPackFile(options.filePath); const preview = await previewMaterialPack( input.fileBuffer, input.fileName, materialPackWebhook?.materialPackFilePolicy ); materialPack = { valid: true, filePath: options.filePath, fileName: input.fileName, documentCount: preview.documents.length, warnings: preview.warnings }; } catch (err) { materialPack = { valid: false, filePath: options.filePath, fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath, documentCount: 0, errors: [err instanceof Error ? err.message : String(err)] }; } } } const materialPackOk = materialPack ? materialPack.valid : true; const ready = authStatus === "ok" && activeWebhooks.length > 0 && materialPackOk; const corpFlag = stateMode === "stateful" ? "" : ` --corp ${corp.id}`; let nextAction = ""; let statusMessage = ""; if (authStatus !== "ok") { statusMessage = `凭证鉴权异常: ${authError}`; nextAction = `seal-use auth diagnose${corpFlag}`; } else if (activeWebhooks.length === 0) { statusMessage = "当前企业尚未配置任何 Webhook 集成通道"; nextAction = `seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${corpFlag}`; } else if (materialPack && !materialPack.valid) { statusMessage = `材料包预检失败: ${materialPack.errors?.join("; ")}`; nextAction = `seal-use webhook material-pack preview ${materialPack.filePath}${corpFlag}`; } else { statusMessage = isSingle ? "所有通道正常,已自动锁定唯一 Webhook 通道,等待载入" : `所有通道正常,检测到 ${activeWebhooks.length} 个 Webhook 通道,等待载入`; const targetFile = materialPack?.filePath ?? "<材料包.zip>"; const webhookOption = isSingle ? "" : ` --webhook ${defaultWebhook ? defaultWebhook.id : ""}`; nextAction = `seal-use webhook material-pack push ${targetFile}${webhookOption}${corpFlag}`; } return { ready, corp: { id: corp.id, name: corp.name, sourceType: corp.source.type, tenant: tenantInfo, user: userInfo }, stateMode, authStatus, authError, activeWebhooks, defaultWebhook, materialPack, statusMessage, nextAction }; }