359 lines
14 KiB
TypeScript
359 lines
14 KiB
TypeScript
import { z } from "zod";
|
||
import type { KyInstance } from "ky";
|
||
import * as api from "../api.js";
|
||
import { validationError, confirmationRequired } from "../../../core/errors.js";
|
||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
|
||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||
import { createSealClient } from "../../../core/http/factory.js";
|
||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../replay/webhook.js";
|
||
import {
|
||
checkWebhookReadiness,
|
||
previewMaterialPack,
|
||
pushMaterialPack,
|
||
readMaterialPackFile
|
||
} from "../material-pack/index.js";
|
||
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
|
||
import {
|
||
type WebhookIntegration,
|
||
type WebhookMode
|
||
} from "../types.js";
|
||
import type {
|
||
CapabilityContext
|
||
} from "./helpers.js";
|
||
import * as helpers from "./helpers.js";
|
||
|
||
const {
|
||
presentWebhookIntegration,
|
||
getConfiguredSealBaseUrl,
|
||
mutationPreview
|
||
} = helpers;
|
||
|
||
export const webhookCapabilities = [
|
||
{
|
||
name: "sealWebhookList",
|
||
description: "列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",
|
||
parameters: z.object({
|
||
query: z.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),
|
||
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { query?: string; includeSecret?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
const integrations = api.filterWebhookIntegrations(
|
||
await api.listWebhookIntegrations(
|
||
client,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
),
|
||
params.query
|
||
);
|
||
return {
|
||
count: integrations.length,
|
||
integrations: integrations.map((integration) => presentWebhookIntegration(integration, params.includeSecret === true))
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookGet",
|
||
description: "按 Webhook 集成 ID 或名称精确查找一条集成",
|
||
parameters: z.object({
|
||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { selector: string; includeSecret?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
const integration = api.findWebhookIntegration(
|
||
await api.listWebhookIntegrations(
|
||
client,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
),
|
||
params.selector
|
||
);
|
||
return presentWebhookIntegration(integration, params.includeSecret === true);
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookAdd",
|
||
description: "新增 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||
parameters: z.object({
|
||
name: z.string().min(1).describe("集成名称"),
|
||
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
|
||
outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),
|
||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"),
|
||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
|
||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
name: string;
|
||
mode?: WebhookMode;
|
||
outgoingResultWebhook: string;
|
||
autoApprovalRate?: number;
|
||
secret?: string;
|
||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||
dryRun?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
const baseUrl = getConfiguredSealBaseUrl(context.corp);
|
||
const preview = params.dryRun
|
||
? await api.previewAddWebhookIntegration(client, baseUrl, params, context.corp.seal.endpoints.approvalStylePreferences)
|
||
: undefined;
|
||
const integration = preview?.integration ?? await api.addWebhookIntegration(
|
||
client,
|
||
baseUrl,
|
||
params,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
);
|
||
if (params.dryRun) {
|
||
return mutationPreview(
|
||
context,
|
||
context.corp.seal.endpoints.approvalStylePreferences,
|
||
preview!.before,
|
||
preview!.after,
|
||
1
|
||
);
|
||
}
|
||
return {
|
||
saved: true,
|
||
integration: presentWebhookIntegration(integration, true)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookUpdate",
|
||
description: "更新现有 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||
parameters: z.object({
|
||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||
name: z.string().min(1).optional(),
|
||
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
|
||
outgoingResultWebhook: z.string().url().optional(),
|
||
autoApprovalRate: z.number().int().min(0).max(100).optional(),
|
||
secret: z.string().min(1).optional(),
|
||
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一"),
|
||
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
|
||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: {
|
||
selector: string;
|
||
name?: string;
|
||
mode?: WebhookMode;
|
||
outgoingResultWebhook?: string;
|
||
autoApprovalRate?: number;
|
||
secret?: string;
|
||
rotateSecret?: boolean;
|
||
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
|
||
dryRun?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
if (params.secret !== undefined && params.rotateSecret) {
|
||
throw new Error("Webhook secret and rotateSecret cannot be used together");
|
||
}
|
||
const preview = params.dryRun
|
||
? await api.previewUpdateWebhookIntegration(client, params.selector, params, context.corp.seal.endpoints.approvalStylePreferences)
|
||
: undefined;
|
||
const integration = preview?.integration ?? await api.updateWebhookIntegration(
|
||
client,
|
||
params.selector,
|
||
params,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
);
|
||
if (params.dryRun) {
|
||
return mutationPreview(
|
||
context,
|
||
context.corp.seal.endpoints.approvalStylePreferences,
|
||
preview!.before,
|
||
preview!.after,
|
||
1
|
||
);
|
||
}
|
||
return {
|
||
saved: true,
|
||
integration: presentWebhookIntegration(
|
||
integration,
|
||
params.secret !== undefined || params.rotateSecret === true
|
||
)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookDelete",
|
||
description: "删除指定 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
|
||
parameters: z.object({
|
||
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
|
||
confirm: z.boolean().optional().describe("执行删除时必须明确传 true;dryRun 可省略"),
|
||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行删除")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { selector: string; confirm?: boolean; dryRun?: boolean },
|
||
context: CapabilityContext
|
||
) => {
|
||
if (!params.confirm && !params.dryRun) {
|
||
throw confirmationRequired("Refusing to delete Webhook integration without confirm=true", "seal-use webhook delete <id> --yes");
|
||
}
|
||
const preview = params.dryRun
|
||
? await api.previewDeleteWebhookIntegration(client, params.selector, context.corp.seal.endpoints.approvalStylePreferences)
|
||
: undefined;
|
||
const integration = preview?.integration ?? await api.deleteWebhookIntegration(
|
||
client,
|
||
params.selector,
|
||
context.corp.seal.endpoints.approvalStylePreferences
|
||
);
|
||
if (params.dryRun) {
|
||
return mutationPreview(
|
||
context,
|
||
context.corp.seal.endpoints.approvalStylePreferences,
|
||
preview!.before,
|
||
preview!.after,
|
||
1
|
||
);
|
||
}
|
||
return {
|
||
deleted: true,
|
||
integration: presentWebhookIntegration(integration, false)
|
||
};
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookReplay",
|
||
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)"),
|
||
confirm: z.boolean().optional().describe("明确确认实际重放;CLI 使用 --yes 或 --confirm"),
|
||
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;
|
||
confirm?: boolean;
|
||
force?: boolean;
|
||
},
|
||
context: CapabilityContext
|
||
) => {
|
||
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,
|
||
confirm: params.confirm
|
||
});
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookReady",
|
||
description: "检查当前企业的 Webhook 就绪状态看板(包括企业环境、租户身份、凭证连通性、已激活 Webhook 通道及材料包预检)",
|
||
parameters: z.object({
|
||
filePath: z.string().optional().describe("可选的材料包路径(ZIP 或 信息表.xlsx),用于同步做本地预检")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { filePath?: string },
|
||
context: CapabilityContext
|
||
) => {
|
||
return checkWebhookReadiness(client, context.corp, { filePath: params.filePath });
|
||
}
|
||
},
|
||
{
|
||
name: "sealWebhookMaterialPack",
|
||
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网,push 模式单通道自动选择",
|
||
parameters: z.object({
|
||
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
|
||
mode: z.enum(["preview", "push"]).default("preview"),
|
||
webhook: z.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")
|
||
}),
|
||
handler: async (
|
||
client: KyInstance,
|
||
params: { filePath: string; mode?: "preview" | "push"; webhook?: string },
|
||
context: CapabilityContext
|
||
) => {
|
||
const input = readMaterialPackFile(params.filePath);
|
||
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
|
||
const integrations = await api.listWebhookIntegrations(client);
|
||
let integration: WebhookIntegration;
|
||
if (params.webhook) {
|
||
integration = api.findWebhookIntegration(integrations, params.webhook);
|
||
} else if (integrations.length === 1) {
|
||
integration = integrations[0]!;
|
||
} else if (integrations.length > 1) {
|
||
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
|
||
throw validationError(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
|
||
} else {
|
||
throw new Error("当前租户未配置任何 Webhook 集成通道。");
|
||
}
|
||
return pushMaterialPack(input.fileBuffer, input.fileName, {
|
||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||
secret: integration.secret,
|
||
materialPackFilePolicy: integration.materialPackFilePolicy,
|
||
customHeaders: resolveSealCustomHeaders(context.corp.seal)
|
||
});
|
||
}
|
||
}
|
||
];
|