diff --git a/src/cli/commands/workflow-debug.test.ts b/src/cli/commands/workflow-debug.test.ts index b84a67f..539decb 100644 --- a/src/cli/commands/workflow-debug.test.ts +++ b/src/cli/commands/workflow-debug.test.ts @@ -35,6 +35,40 @@ describe("workflow debug mutation and result contract", () => { expect(client).not.toHaveBeenCalled(); expect(run).not.toHaveBeenCalled(); }); + for (const [triggerType, options] of [ + ["clock", {}], + ["webhook", { body: '{"event":"test"}' }], + ["webhook", { empty: true }], + ["webhook", { file: "/unused-in-dry-run.json" }], + ["ekuaibao-datalink-create-trigger", { record: "ID01-record" }], + ] as Array<[string, Record]>) { + it(`previews ${triggerType} without creating clients (${Object.keys(options).join(",")})`, async () => { + const { client, run } = setup(); + const result = await handleWorkflowTest({ ...args(), options: { ...options, "dry-run": true, yes: true } }, runtime); + expect(JSON.parse(result.stdout).dryRun).toBe(true); + expect(client).not.toHaveBeenCalled(); + expect(run).not.toHaveBeenCalled(); + }); + } + it("requires confirmation for a schedule trigger without --flow", async () => { + const { detail, run } = setup(); + detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any); + await expect(handleWorkflowTest({ ...args(), options: {} }, runtime)).rejects.toThrow("请先使用 --dry-run"); + expect(run).not.toHaveBeenCalled(); + }); + it("keeps confirmed schedule and webhook trigger routing", async () => { + const { detail, run } = setup(); + detail.mockResolvedValue({ state: 1, tasks: [{ type: "clock" }] } as any); + const scheduled = await handleWorkflowTest({ ...args(), options: { yes: true } }, runtime); + expect(scheduled.exitCode).toBe(0); + expect(run.mock.calls[0]?.[2]?.triggerCategory).toBe("SCHEDULE"); + expect(run.mock.calls[0]?.[2]?.flowCodeOrId).toBe(""); + detail.mockResolvedValue({ state: 1, tasks: [{ type: "webhook" }] } as any); + const webhook = await handleWorkflowTest({ ...args(), options: { body: '{"event":"test"}', yes: true } }, runtime); + expect(webhook.exitCode).toBe(0); + expect(run.mock.calls[1]?.[2]?.data).toEqual({ event: "test" }); + expect(run.mock.calls[1]?.[2]?.triggerCategory).toBe("WEBHOOK"); + }); it("allows confirmed enabled-workflow debug with machine-readable risk information", async () => { const { run } = setup(); const result = await handleWorkflowTest(args({ yes: true }), runtime); diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index f04eedf..528459d 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -753,4 +753,250 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(res.stdout).toContain("特权调测通道"); expect(res.stdout).toContain("job_prod_999"); }); + + it("handles workflow test for clock trigger without requiring --flow", async () => { + const mockClient = { + get: (url: string) => { + if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) }; + if (url.includes("api/easo/pipelines/")) { + return { + json: async () => ({ + code: 200, + data: { + id: "wf_clock_1", + label: "定时摊销工作流", + state: 0, + tasks: [ + { id: "t1", name: "trigger_1", label: "定时触发", type: "clock" }, + ], + }, + }), + }; + } + if (url.includes("execution")) { + return { + json: async () => ({ + code: 200, + data: [ + { + id: "e1", + name: "trigger_1", + label: "定时触发", + type: "clock", + status: "COMPLETED", + }, + ], + }), + }; + } + return { + json: async () => ({ + code: 200, + data: { + id: "job_clock_101", + pipelineId: "wf_clock_1", + status: "COMPLETED", + runType: "DEBUG", + }, + }), + }; + }, + post: () => ({ json: async () => ({ code: 200, data: "job_clock_101" }) }), + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: mockClient as any, + easoClient: mockClient as any, + corp: mockCorp, + } as any) + ); + spies.push( + spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) + ); + + // 未传 --flow,也无需报错,直接派发执行 + const res = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_clock_1"], + options: { platformId: "p1", yes: true }, + raw: ["workflow", "test", "wf_clock_1", "--platform-id=p1"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("[SCHEDULE]"); + expect(res.stdout).toContain("定时调度模拟触发"); + expect(res.stdout).toContain("job_clock_101"); + }); + + it("handles workflow test for webhook trigger requiring body or empty", async () => { + const mockClient = { + get: (url: string) => { + if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) }; + if (url.includes("api/easo/pipelines/")) { + return { + json: async () => ({ + code: 200, + data: { + id: "wf_webhook_1", + label: "外部回调工作流", + state: 0, + tasks: [ + { id: "t1", name: "trigger_1", label: "Webhook触发器", type: "webhook" }, + ], + }, + }), + }; + } + if (url.includes("execution")) { + return { + json: async () => ({ + code: 200, + data: [ + { + id: "e1", + name: "trigger_1", + label: "Webhook触发器", + type: "webhook", + status: "COMPLETED", + }, + ], + }), + }; + } + return { + json: async () => ({ + code: 200, + data: { + id: "job_webhook_202", + pipelineId: "wf_webhook_1", + status: "COMPLETED", + runType: "DEBUG", + }, + }), + }; + }, + post: () => ({ json: async () => ({ code: 200, data: "job_webhook_202" }) }), + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: mockClient as any, + easoClient: mockClient as any, + corp: mockCorp, + } as any) + ); + spies.push( + spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) + ); + + // 1. 未传 body 时提示参数说明 + const noBodyRes = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_webhook_1"], + options: { platformId: "p1" }, + raw: ["workflow", "test", "wf_webhook_1", "--platform-id=p1"], + }, + mockRuntime + ); + expect(noBodyRes.exitCode).toBe(1); + expect(noBodyRes.stdout).toContain("外部事件触发器"); + expect(noBodyRes.stdout).toContain("--body"); + + // 2. 传入 --body 成功派发 + const withBodyRes = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_webhook_1"], + options: { body: '{"code":"XM-001"}', platformId: "p1", yes: true }, + raw: ["workflow", "test", "wf_webhook_1", '--body={"code":"XM-001"}', "--platform-id=p1"], + }, + mockRuntime + ); + expect(withBodyRes.exitCode).toBe(0); + expect(withBodyRes.stdout).toContain("[WEBHOOK]"); + expect(withBodyRes.stdout).toContain("Webhook Payload"); + }); + + it("handles workflow test for datalink trigger displaying dynamic fields", async () => { + const mockClient = { + get: (url: string) => { + if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) }; + if (url.includes("api/easo/pipelines/")) { + return { + json: async () => ({ + code: 200, + data: { + id: "wf_datalink_1", + label: "合同台账生成单据", + state: 0, + tasks: [ + { id: "t1", name: "trigger_1", label: "新增业务对象数据时触发", type: "ekuaibao-datalink-create-trigger" }, + ], + }, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + post: (url: string) => { + if (url.includes("debugSource")) { + return { + json: async () => ({ + code: 200, + data: { + type: "dataLink", + total: 1, + label: "合同台账", + fields: [ + { key: "contractName", label: "合同名称" }, + { key: "owner", label: "负责人" }, + ], + items: [ + { id: "rec_123", contractName: "年度办公租赁合同", owner: "张三" }, + ], + }, + }), + }; + } + return { json: async () => ({ code: 200, data: null }) }; + }, + }; + + spies.push( + spyOn(helpers, "createClientsForCorp").mockResolvedValue({ + ekbClient: mockClient as any, + easoClient: mockClient as any, + corp: mockCorp, + } as any) + ); + spies.push( + spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) + ); + + const res = await handleWorkflowCommand( + { + area: "workflow", + action: "test", + args: ["wf_datalink_1"], + options: { platformId: "p1" }, + raw: ["workflow", "test", "wf_datalink_1", "--platform-id=p1"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(1); + expect(res.stdout).toContain("合同台账"); + expect(res.stdout).toContain("合同名称"); + expect(res.stdout).toContain("年度办公租赁合同"); + expect(res.stdout).toContain("张三"); + expect(res.stdout).toContain("--record="); + }); }); diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index 5da1c00..a8729b9 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -1,7 +1,10 @@ +import { existsSync, readFileSync } from "node:fs"; import { + classifyWorkflowTrigger, getWorkflowDebugSource, getWorkflowDetail, runWorkflowDebugTest, + type WorkflowTriggerCategory, } from "../../../domains/platform/services.js"; import { stringOption, booleanOption, numberOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; @@ -17,74 +20,232 @@ export async function handleWorkflowTest( if (!pipelineId) { return { stdout: "", - stderr: "用法: hose-use workflow test --flow=<单号|单据ID> [--auto-publish] [--timeout=] [--dry-run | --yes]\n别名: hose-use workflow debug --flow=<单号>\n", + stderr: [ + "用法: hose-use workflow test [选项]", + "", + "不同触发器的调试参数分支:", + " 1. 单据触发 (flowForm): --flow=<单号|ID> 指定单据", + " 2. 台账触发 (dataLink): --record=<记录ID|编码> 指定业务对象数据", + " 3. 定时触发 (clock): 无需业务参数,使用 --yes 确认执行", + " 4. 外部调用 (webhook): --body='{...}' 或 --file= 传入事件请求体", + "", + "通用选项:", + " --timeout= 设置轮询超时时间 (默认 15000ms)", + " --auto-publish 是否自动发布测试快照 (默认 false)", + " --dry-run 只预览,不发起调试", + " --yes/--confirm 确认执行真实工作流节点", + "", + "别名: hose-use workflow debug ", + ].join("\n") + "\n", exitCode: 1, }; } - const flowCodeOrId = stringOption(parsed.options, ["flow", "code", "flow-code", "flowCode", "bill", "entity", "id"]); + const flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]); const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]); const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000; + const rawBody = stringOption(parsed.options, ["body", "data", "payload"]); + const filePath = stringOption(parsed.options, ["file", "path"]); + const isEmpty = booleanOption(parsed.options, ["empty", "none"]); + const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"]; - if (flowCodeOrId) { - requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --flow=${flowCodeOrId} --yes`); - if (isDryRun(parsed, runtime)) { - return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, autoPublish, timeoutMs, warnings }); - } + const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`); + if (isDryRun(parsed, runtime)) { + return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings }); } + if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution(); const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); - // 获取工作流状态,检测是否处于生产启用中 + // 1. 获取工作流详情与触发器元数据 const detail = await getWorkflowDetail(client, pipelineId).catch(() => { warnings.push("未能读取工作流状态,启用状态未知。"); return null; }); const isEnabled = detail?.state === 1 || (detail as any)?.active === true; + const triggerNode = detail?.tasks?.[0]; + const triggerType = triggerNode?.type || "unknown"; + const triggerLabel = triggerNode?.label || triggerNode?.name || "触发器"; + const category: WorkflowTriggerCategory = classifyWorkflowTrigger(triggerType); - // 如果没有传入 --flow,先列出当前可用的调试数据源供用户参考 - if (!flowCodeOrId) { - try { - const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 }); - if (runtime.jsonMode) { + let targetId = flowCodeOrId; + let customPayload: Record | undefined; + + // 2. 根据触发器类型进行路径分支分发 (Path Branching) + switch (category) { + case "SCHEDULE": { + // 分支 A: 定时任务触发器 (clock) ── 无需单据/台账,直接派发执行 + targetId = ""; + break; + } + + case "WEBHOOK": { + // 分支 B: Webhook / 外部事件触发器 ── 接收模拟请求体 (Payload) + if (rawBody) { + try { + customPayload = JSON.parse(rawBody); + } catch (e: any) { + return { + stdout: "", + stderr: `❌ --body 参数不是合法的 JSON 字符串: ${e.message}\n`, + exitCode: 1, + }; + } + } else if (filePath) { + if (!existsSync(filePath)) { + return { + stdout: "", + stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`, + exitCode: 1, + }; + } + try { + customPayload = JSON.parse(readFileSync(filePath, "utf-8")); + } catch (e: any) { + return { + stdout: "", + stderr: `❌ 读取并解析文件 ${filePath} 失败: ${e.message}\n`, + exitCode: 1, + }; + } + } else if (isEmpty) { + customPayload = {}; + } else { + // 未提供 Payload 时给出交互式指引 return { - stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions), + stdout: [ + `📡 [外部事件触发器: ${triggerLabel} (${triggerType})]`, + `该工作流由 Webhook / 外部系统事件驱动,需提供模拟请求体 (Payload) 进行测试。`, + "", + "调试传参选项:", + ` --body='{"key": "value"}' 直接传入 JSON 请求体`, + ` --file= 从本地 JSON 文件读取请求体`, + ` --empty 使用空对象 {} 直接发起测试`, + "", + `示例: hose-use workflow test ${pipelineId} --body='{"code": "TEST-001"}'`, + ].join("\n") + "\n", stderr: "", - exitCode: 0, + exitCode: 1, }; } - const rows = source.items.map((it, idx) => [ - idx + 1, - it.id, - it.title || "-", - it.flowState || "-", - ]); - const out = [ - `⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`, - ...(isEnabled - ? [ - `💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`, - ` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`, - ] - : []), - "", - `── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "候选单据"}) ──`, - rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据", - "", - `示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`, - ].join("\n"); - return { stdout: `${out}\n`, stderr: "", exitCode: 1 }; - } catch (err: any) { - return { - stdout: "", - stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`, - exitCode: 1, - }; + break; + } + + case "DATALINK": { + // 分支 C: 业务对象台账变更触发器 ── 需要台账数据记录 ID (ID01...) + if (!targetId) { + try { + const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 }); + if (runtime.jsonMode) { + return { + stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + // 动态解析数据源列字段 (Fields) + const hasFields = Array.isArray(source.fields) && source.fields.length > 0; + const headers = hasFields + ? ["#", "记录 ID", ...source.fields.map((f) => f.label)] + : ["#", "记录 ID", "编码 (Code)", "名称 (Name)", "负责人 (Owner)"]; + + const rows = source.items.map((it, idx) => { + if (hasFields) { + return [ + idx + 1, + it.id, + ...source.fields.map((f) => (it as any)[f.key] || "-"), + ]; + } + return [ + idx + 1, + it.id, + (it as any).code || "-", + (it as any).name || it.title || "-", + (it as any).owner || "-", + ]; + }); + + const out = [ + `⚠️ 未指定台账记录,请通过 --record=<记录ID|编码> 传入测试台账。`, + ...(isEnabled + ? [ + `💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`, + ` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`, + ] + : []), + "", + `── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "业务对象台账"}) ──`, + rows.length ? printTable(headers, rows) : "暂无可用台账记录", + "", + `示例: hose-use workflow test ${pipelineId} --record=${source.items[0]?.id || "ID01..."}`, + ].join("\n"); + return { stdout: `${out}\n`, stderr: "", exitCode: 1 }; + } catch (err: any) { + return { + stdout: "", + stderr: `未指定台账记录 (--record=),且拉取候选台账失败: ${err.message || String(err)}\n`, + exitCode: 1, + }; + } + } + break; + } + + case "FLOW_FORM": + default: { + // 分支 D: 单据审批事件触发器 ── 需要单据编号 (ZJ-xxx / flowId) + if (!targetId) { + try { + const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 }); + if (runtime.jsonMode) { + return { + stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + const rows = source.items.map((it, idx) => [ + idx + 1, + it.id, + it.title || "-", + it.flowState || "-", + ]); + const out = [ + `⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`, + ...(isEnabled + ? [ + `💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`, + ` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`, + ] + : []), + "", + `── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "我的单据"}) ──`, + rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据", + "", + `示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`, + ].join("\n"); + return { stdout: `${out}\n`, stderr: "", exitCode: 1 }; + } catch (err: any) { + return { + stdout: "", + stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`, + exitCode: 1, + }; + } + } + break; } } - // 执行端到端调试测试 + // 3. 执行端到端调试测试 + confirmExecution(); const execution = await runWorkflowDebugTest(client, pipelineId, { - flowCodeOrId, + flowCodeOrId: targetId, + data: customPayload, + triggerCategory: category, + triggerType, + triggerLabel, autoPublish, timeoutMs, }); @@ -110,6 +271,13 @@ export async function handleWorkflowTest( node.error?.message || "-", ]); + const targetDescription = + category === "SCHEDULE" + ? "(定时调度模拟触发)" + : category === "WEBHOOK" + ? `(Webhook Payload: ${customPayload ? Object.keys(customPayload).join(", ") || "{}" : "-"})` + : report.targetEntityId || "-"; + const outLines = [ ...(isEnabled ? [ @@ -123,8 +291,9 @@ export async function handleWorkflowTest( `====== 工作流自动化调测报告 [${pipelineId}] ======`, printKeyValue({ "工作流 ID (pipelineId)": pipelineId, + "触发器类型": `[${category}] ${triggerLabel} (${triggerType})`, "生成 Job ID": report.jobId, - "测试目标单据": report.targetEntityId, + "测试目标对象": targetDescription, "执行结果状态": report.status, "测试结果": report.outcome, "是否超时": String(report.timedOut), @@ -143,6 +312,7 @@ export async function handleWorkflowTest( ) : "暂无顶层节点执行记录", ]; + outLines.push(...warnings.map(warning => `⚠️ ${warning}`)); outLines.push(...report.diagnosticsErrors.map(error => `诊断读取失败 [${error.source}]: ${error.message}`)); diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index 08eca8a..41afc1e 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -22,10 +22,22 @@ hose-use workflow logs [--has-error] [--state=FAILED] hose-use workflow job [--failed] [--node=] [--verbose] hose-use workflow diff [--pipelineId=] hose-use workflow diff-job [--json] -hose-use workflow test --flow=<单号|单据ID> [--auto-publish] [--dry-run|--yes] +hose-use workflow test [--flow=<单号>] [--record=] [--body='{...}'] [--dry-run|--yes] hose-use workflow debug --flow=<单号> --yes ``` +## 触发器分类与调测路径分支 (Path Branching) + +合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由: + +| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 | +|---|---|---|---| +| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,经 `--yes` 确认后派发并抓取执行树 | +| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task` | 服务端无 `debugSource`,`inputs: { data: { ... } }` | **Payload 注入**:支持 `--body='{...}'` / `--file=event.json` / `--empty` | +| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=` 或 `--flow=<编码>` | +| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 | + + ## 生产环境调试缺陷与安全防线(合思平台缺陷记录) > [!WARNING] **合思后端架构缺陷:前端置灰防御,后端裸奔无防** diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index 7dbd110..58c0d6f 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -346,13 +346,14 @@ export async function getWorkflowDebugSource( export async function triggerWorkflowDebug( client: KyInstance, pipelineId: string, - options: { entityId: string; autoPublish?: boolean; dataLimit?: number } + options: { entityId?: string; data?: Record; autoPublish?: boolean; dataLimit?: number } = {} ): Promise { const response = await client.post("api/easo/jobs", { json: { pipelineId, inputs: { - id: options.entityId, + id: options.entityId ?? "", + ...(options.data !== undefined ? { data: options.data } : {}), $autoPublish: options.autoPublish ?? false, }, dataLimit: options.dataLimit ?? 20, diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index 01e22bb..8d90510 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -662,26 +662,31 @@ export async function runWorkflowDebugTest( client: import("ky").KyInstance, pipelineId: string, options: { - flowCodeOrId: string; + flowCodeOrId?: string; + data?: Record; + triggerCategory?: import("./types.js").WorkflowTriggerCategory; + triggerType?: string; + triggerLabel?: string; autoPublish?: boolean; timeoutMs?: number; pollIntervalMs?: number; - } + } = {} ): Promise { if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) { throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数"); } - let targetEntityId = options.flowCodeOrId; - const isDirectCode = options.flowCodeOrId.includes("-") || options.flowCodeOrId.startsWith("ID01"); - if (!isDirectCode) { + let targetEntityId = options.flowCodeOrId ?? ""; + const code = options.flowCodeOrId; + const isDirectCode = !code || code.includes("-") || code.startsWith("ID01"); + if (code && !isDirectCode) { try { const source = await api.getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 10, - keywords: options.flowCodeOrId, + keywords: code, }); const matched = source.items.find( - (item) => item.id === options.flowCodeOrId || item.title.includes(options.flowCodeOrId) + (item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code) ); if (matched) { targetEntityId = matched.id; @@ -692,7 +697,8 @@ export async function runWorkflowDebugTest( } const jobId = await api.triggerWorkflowDebug(client, pipelineId, { - entityId: targetEntityId, + entityId: targetEntityId || undefined, + data: options.data, autoPublish: options.autoPublish ?? false, }); @@ -759,6 +765,9 @@ export async function runWorkflowDebugTest( runType: finalJob?.runType || "DEBUG", durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined, targetEntityId, + triggerCategory: options.triggerCategory, + triggerType: options.triggerType, + triggerLabel: options.triggerLabel, executionTree: tree, failedExecutions: rawFailed, conditionDiagnoses, @@ -771,3 +780,8 @@ export { type ConditionRuleExplanation, } from "./workflow-branch.js"; +export { + classifyWorkflowTrigger, + type WorkflowTriggerCategory, +} from "./types.js"; + diff --git a/src/domains/platform/types.ts b/src/domains/platform/types.ts index 944c546..01a9708 100644 --- a/src/domains/platform/types.ts +++ b/src/domains/platform/types.ts @@ -191,14 +191,14 @@ export const FlowCreateTaskSchema = BaseTaskSchema.extend({ // 兜底节点:遇到未收录类型时仍保留全部字段 export const UnknownTaskSchema = z .object({ - name: z.string(), + name: z.string().default("task"), type: z.string(), label: z.string().optional(), desc: z.string().optional(), - groupName: z.string(), - orderIndex: z.number(), - levelIndex: z.array(z.number()), - status: z.string(), + groupName: z.string().default("trigger"), + orderIndex: z.number().default(0), + levelIndex: z.array(z.number()).default([0]), + status: z.string().default("active"), displayName: z.string().optional(), }) .passthrough(); @@ -640,9 +640,40 @@ export interface WorkflowTestReport { runType: string; durationTime?: number; targetEntityId: string; + triggerCategory?: WorkflowTriggerCategory; + triggerType?: string; + triggerLabel?: string; executionTree: WorkflowTaskExecution[]; failedExecutions: WorkflowTaskExecution[]; conditionDiagnoses: import("./workflow-branch.js").ConditionBranchExplanation[]; } +// ── 触发器元类型分类与智能路径路由 ─────────────────────────────────────────────── + +export type WorkflowTriggerCategory = + | "FLOW_FORM" // 单据审批流转类 (ekuaibao-flowform-trigger, ekuaibao-ebot-trigger, other-event-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"; // 其他自定义触发器 + +export function classifyWorkflowTrigger(triggerType?: string): WorkflowTriggerCategory { + if (!triggerType) return "CUSTOM"; + const t = triggerType.toLowerCase(); + 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") { + return "FLOW_FORM"; + } + if (t.includes("datalink") || t.includes("entity")) { + return "DATALINK"; + } + if (t.includes("webhook") || t.includes("hab-trigger")) { + return "WEBHOOK"; + } + return "CUSTOM"; +} + +