From c56460716ffac386ecb1326056375269f585ebad Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 15 Oct 2026 15:01:20 +0800 Subject: [PATCH] feat(workflow): support webhook sample records, params preview and expand trigger catalog --- src/cli/commands/workflow.test.ts | 44 +++++++++++-- src/cli/commands/workflow/test.ts | 82 +++++++++++++++++++++++-- src/domains/platform/README.platform.md | 4 +- src/domains/platform/api.ts | 14 +++++ src/domains/platform/services.ts | 11 ++++ src/domains/platform/types.ts | 35 +++++++++-- 6 files changed, 175 insertions(+), 15 deletions(-) diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 528459d..1bce82f 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -880,7 +880,26 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { }), }; }, - post: () => ({ json: async () => ({ code: 200, data: "job_webhook_202" }) }), + post: (url: string) => { + if (url && url.includes("sampleData")) { + return { + json: async () => ({ + code: 200, + data: { + records: [ + { + id: "sample_001", + pipelineId: "wf_webhook_1", + dataJson: JSON.stringify({ code: "SAMPLE-PAYLOAD-001" }), + createTime: 1792047100000, + }, + ], + }, + }), + }; + } + return { json: async () => ({ code: 200, data: "job_webhook_202" }) }; + }, }; spies.push( @@ -894,7 +913,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) ); - // 1. 未传 body 时提示参数说明 + // 1. 未传 body 时提示参数说明与服务器历史样本 const noBodyRes = await handleWorkflowCommand( { area: "workflow", @@ -907,9 +926,26 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { ); expect(noBodyRes.exitCode).toBe(1); expect(noBodyRes.stdout).toContain("外部事件触发器"); - expect(noBodyRes.stdout).toContain("--body"); + expect(noBodyRes.stdout).toContain("服务器最近接收的数据样本"); + expect(noBodyRes.stdout).toContain("sample_001"); + expect(noBodyRes.stdout).toContain("--sample"); - // 2. 传入 --body 成功派发 + // 2. 传入 --sample=1 成功提取样本发起测试 + const withSampleRes = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_webhook_1"], + options: { sample: "1", platformId: "p1", yes: true }, + raw: ["workflow", "test", "wf_webhook_1", "--sample=1", "--platform-id=p1", "--yes"], + }, + mockRuntime + ); + expect(withSampleRes.exitCode).toBe(0); + expect(withSampleRes.stdout).toContain("[WEBHOOK]"); + expect(withSampleRes.stdout).toContain("Webhook Payload: code"); + + // 3. 传入 --body 成功派发 const withBodyRes = await handleWorkflowCommand( { area: "workflow", diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index a8729b9..5ed94e2 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -3,6 +3,7 @@ import { classifyWorkflowTrigger, getWorkflowDebugSource, getWorkflowDetail, + getWorkflowSampleData, runWorkflowDebugTest, type WorkflowTriggerCategory, } from "../../../domains/platform/services.js"; @@ -47,6 +48,7 @@ export async function handleWorkflowTest( const rawBody = stringOption(parsed.options, ["body", "data", "payload"]); const filePath = stringOption(parsed.options, ["file", "path"]); const isEmpty = booleanOption(parsed.options, ["empty", "none"]); + const sampleOption = stringOption(parsed.options, ["sample", "sample-id", "sampleId"]); const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"]; const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`); @@ -79,7 +81,8 @@ export async function handleWorkflowTest( } case "WEBHOOK": { - // 分支 B: Webhook / 外部事件触发器 ── 接收模拟请求体 (Payload) + // 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty + targetId = ""; if (rawBody) { try { customPayload = JSON.parse(rawBody); @@ -107,21 +110,92 @@ export async function handleWorkflowTest( exitCode: 1, }; } + } else if (sampleOption) { + // 从服务器获取历史接收样本发起测试 + try { + const sampleResult = await getWorkflowSampleData(client, pipelineId); + const records = sampleResult.records || []; + let matched = records.find((r) => r.id === sampleOption); + if (!matched) { + const num = parseInt(sampleOption, 10); + if (!isNaN(num) && num >= 1 && num <= records.length) { + matched = records[num - 1]; + } + } + if (!matched) { + return { + stdout: "", + stderr: `❌ 未找到指定的数据样本 [${sampleOption}]。当前服务器保存了 ${records.length} 条样本。\n`, + exitCode: 1, + }; + } + customPayload = JSON.parse(matched.dataJson); + } catch (e: any) { + return { + stdout: "", + stderr: `❌ 获取或解析数据样本失败: ${e.message}\n`, + exitCode: 1, + }; + } } else if (isEmpty) { customPayload = {}; } else { - // 未提供 Payload 时给出交互式指引 + // 未提供 Payload 时,展示参数定义与服务器最近接收的数据样本 + let sampleLines: string[] = []; + try { + const sampleResult = await getWorkflowSampleData(client, pipelineId); + const records = sampleResult.records || []; + if (records.length > 0) { + const rows = records.map((r, idx) => { + const timeStr = r.createTime + ? new Date(r.createTime).toLocaleString("zh-CN", { hour12: false }) + : "-"; + let preview = r.dataJson || ""; + if (preview.length > 55) preview = preview.slice(0, 52) + "..."; + return [idx + 1, r.id, timeStr, preview]; + }); + sampleLines = [ + "", + `── 服务器最近接收的数据样本 (最近 ${records.length} 条) ──`, + printTable(["#", "样本 ID", "接收时间", "数据摘要 (Payload Preview)"], rows), + ]; + } + } catch {} + + // 解析触发器定义的请求参数与中文昵称映射 + const triggerParams = Array.isArray((triggerNode as any)?.params) + ? ((triggerNode as any).params as Array<{ key: string; value: string }>) + : []; + let paramLines: string[] = []; + if (triggerParams.length > 0) { + paramLines = [ + "", + "── 接收的请求参数定义 (Params) ──", + printTable( + ["参数名 (Key)", "中文昵称 (Label)"], + triggerParams.map((p) => [p.key, p.value]) + ), + ]; + } + return { stdout: [ `📡 [外部事件触发器: ${triggerLabel} (${triggerType})]`, `该工作流由 Webhook / 外部系统事件驱动,需提供模拟请求体 (Payload) 进行测试。`, + ...paramLines, + ...sampleLines, "", "调试传参选项:", - ` --body='{"key": "value"}' 直接传入 JSON 请求体`, + ...(sampleLines.length > 0 + ? [` --sample=<1|2|3> 直接选用上述服务器最近接收的数据样本发起测试`] + : []), + ` --body='{"key": "value"}' 直接传入自定义 JSON 请求体`, ` --file= 从本地 JSON 文件读取请求体`, ` --empty 使用空对象 {} 直接发起测试`, "", - `示例: hose-use workflow test ${pipelineId} --body='{"code": "TEST-001"}'`, + `示例: hose-use workflow test ${pipelineId} ${ + sampleLines.length > 0 ? "--sample=1" : `--body='{"code": "TEST-001"}'` + }`, ].join("\n") + "\n", stderr: "", exitCode: 1, diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 41afc1e..72ec63c 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -32,8 +32,8 @@ hose-use workflow debug --flow=<单号> --yes | 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 | |---|---|---|---| -| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,经 `--yes` 确认后派发并抓取执行树 | -| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task` | 服务端无 `debugSource`,`inputs: { data: { ... } }` | **Payload 注入**:支持 `--body='{...}'` / `--file=event.json` / `--empty` | +| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 | +| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task`, `xrxs-trigger`, `fxiaoke-trigger` | 服务端维护最近 3 条 Sample 样本 (`/sampleData`),`inputs: { data: { ... } }` | **样本复用与 Payload 注入**:展示参数定义映射 (Key->Label),支持 `--sample=<1\|2\|3>` 直接使用历史真实样本,或 `--body='{...}'` / `--empty` | | **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=` 或 `--flow=<编码>` | | **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 | diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index 58c0d6f..7b6ee0d 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -19,6 +19,8 @@ import { StaffSchema, WebhookInfoSchema, WorkflowSampleDataSchema, + WorkflowSampleDataResultSchema, + type WorkflowSampleDataResult, WorkflowDebugSourceResultSchema, } from "./types.js"; import type { WorkflowState } from "./types.js"; @@ -367,3 +369,15 @@ export async function triggerWorkflowDebug( return String(data); } +export async function getWorkflowSampleData( + client: KyInstance, + pipelineId: string, + type = "webhook" +): Promise { + const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`, { + json: { type }, + }); + return unwrap(response, WorkflowSampleDataResultSchema); +} + + diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index 8d90510..a67e480 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -783,5 +783,16 @@ export { export { classifyWorkflowTrigger, type WorkflowTriggerCategory, + type WorkflowSampleRecord, + type WorkflowSampleDataResult, } from "./types.js"; +export async function getWorkflowSampleData( + client: import("ky").KyInstance, + pipelineId: string, + type = "webhook" +): Promise { + return api.getWorkflowSampleData(client, pipelineId, type); +} + + diff --git a/src/domains/platform/types.ts b/src/domains/platform/types.ts index 01a9708..7504638 100644 --- a/src/domains/platform/types.ts +++ b/src/domains/platform/types.ts @@ -651,11 +651,11 @@ export interface WorkflowTestReport { // ── 触发器元类型分类与智能路径路由 ─────────────────────────────────────────────── export type WorkflowTriggerCategory = - | "FLOW_FORM" // 单据审批流转类 (ekuaibao-flowform-trigger, ekuaibao-ebot-trigger, other-event-trigger) + | "FLOW_FORM" // 单据审批流转类 (ekuaibao-flowform-trigger, ekuaibao-ebot-trigger, other-event-trigger, flow-change-trigger) | "DATALINK" // 业务对象/台账变更类 (ekuaibao-datalink-create-trigger, ekuaibao-datalink-change-trigger, ekuaibao-datalink-time-trigger, datalink-button-trigger, ekuaibao-tmc-datalink-change-trigger) | "SCHEDULE" // 定时调度类 (clock) - | "WEBHOOK" // 外部调用/网关集成类 (webhook, hab-trigger-task) - | "CUSTOM"; // 其他自定义触发器 + | "WEBHOOK" // 外部调用/网关集成类 (webhook, hab-trigger-task, xrxs-trigger, fxiaoke-trigger) + | "CUSTOM"; // 其他自定义触发器 (pipeline-running-trigger, pipeline-save-trigger 等) export function classifyWorkflowTrigger(triggerType?: string): WorkflowTriggerCategory { if (!triggerType) return "CUSTOM"; @@ -663,17 +663,42 @@ export function classifyWorkflowTrigger(triggerType?: string): WorkflowTriggerCa if (t === "clock" || t.includes("timer") || t.includes("schedule")) { return "SCHEDULE"; } - if (t.includes("flowform") || t.includes("ebot") || t.includes("flow-") || t === "other-event-trigger") { + if (t.includes("flowform") || t.includes("ebot") || t.includes("flow-") || t === "other-event-trigger" || t.includes("requisition")) { return "FLOW_FORM"; } if (t.includes("datalink") || t.includes("entity")) { return "DATALINK"; } - if (t.includes("webhook") || t.includes("hab-trigger")) { + if (t.includes("webhook") || t.includes("hab-trigger") || t.includes("xrxs") || t.includes("fxiaoke")) { return "WEBHOOK"; } return "CUSTOM"; } +// ── Webhook 数据样本 (Sample Data) ───────────────────────────────────────────── + +export const WorkflowSampleRecordSchema = z.object({ + id: z.string(), + corporationId: z.string().optional(), + pipelineId: z.string().optional(), + taskName: z.string().optional(), + actived: z.number().optional(), + dataJson: z.string(), + createTime: z.number(), + updateTime: z.number().optional(), +}); + +export type WorkflowSampleRecord = z.infer; + +export const WorkflowSampleDataResultSchema = z.object({ + records: z.array(WorkflowSampleRecordSchema).default([]), + total: z.number().optional(), + size: z.number().optional(), + current: z.number().optional(), +}); + +export type WorkflowSampleDataResult = z.infer; + +