Merge pull request #113 from yunyingk/feat/workflow-node-declarative-edit
feat(workflow): implement declarative node editing commands
This commit is contained in:
9 files changed
+1415
-6
No files matched your search
@@ -205,6 +205,11 @@ hose-use workflow publish wf_01k83y... --yes # 将保存后的工
|
||||
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
|
||||
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
|
||||
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
|
||||
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
||||
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
|
||||
# 6. OpenAPI 密钥与应用中心
|
||||
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
|
||||
|
||||
@@ -266,7 +266,43 @@ hose-use workflow rm <pipelineId> --yes
|
||||
|
||||
---
|
||||
|
||||
## 15. 工作流排障与创单排错三大黄金法则(必读)
|
||||
## 15. 工作流节点级声明式编排与编辑 (`workflow node`)
|
||||
|
||||
针对合思 EASO/Piper 任务流水线内部的复杂节点树(支持 `every` 循环、`condition` 分支多层深度嵌套),提供直接按节点标识(如 `action_xxx`)或层级序号(如 `1`, `2.1`, `2.2.1`)定向查看、追加、修改与移除的能力,避免手动拼接庞大 JSON 报文的低效与格式错误:
|
||||
|
||||
```bash
|
||||
# 1. 树形层级索引查看工作流中所有任务节点与配置摘要 (别名: ls)
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node list <pipelineId> --json
|
||||
|
||||
# 2. 定向查看指定节点的完整属性与映射详情 (别名: show, info)
|
||||
# 支持传节点 name (如 action_dx9cci) 或序号 (如 2 或 2.1)
|
||||
hose-use workflow node get <pipelineId> action_dx9cci
|
||||
hose-use workflow node get <pipelineId> 2 --json
|
||||
|
||||
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
||||
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes
|
||||
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
||||
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
||||
|
||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
|
||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
|
||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||
# 自动标准化重排同层 index 与 levelIndex;内置首节点触发器保护,严禁误删流程唯一的触发源
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --yes
|
||||
hose-use workflow node rm <pipelineId> 3 --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
|
||||
@@ -1460,4 +1460,227 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
|
||||
await (await import("fs/promises")).unlink(tmpFile).catch(() => {});
|
||||
});
|
||||
|
||||
it("handles workflow node list, get, add, edit, and rm commands with dry-run and safety checks", async () => {
|
||||
// 1. Missing pipelineId -> usage
|
||||
const noArgRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["workflow", "node"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(noArgRes.exitCode).toBe(1);
|
||||
expect(noArgRes.stderr).toContain("用法: hose-use workflow node");
|
||||
|
||||
let savedWorkflowPayload: any = null;
|
||||
const testTasks = [
|
||||
{
|
||||
name: "trigger_webhook_1",
|
||||
type: "webhook",
|
||||
label: "发票数据接入",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: "test-uuid-1",
|
||||
params: [],
|
||||
},
|
||||
{
|
||||
name: "action_js_1",
|
||||
type: "code-js2",
|
||||
label: "数据清洗",
|
||||
groupName: "action",
|
||||
orderIndex: 1,
|
||||
levelIndex: [1],
|
||||
status: "active",
|
||||
code: "return items.filter(x => x.amount > 0);",
|
||||
},
|
||||
];
|
||||
|
||||
const mockDetail = {
|
||||
id: "pipe_node_test",
|
||||
label: "节点编排测试流程",
|
||||
state: 0,
|
||||
tasks: testTasks,
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/easo/pipelines/pipe_node_test")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: mockDetail,
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
put: (url: string, opts: any) => {
|
||||
if (url.includes("api/easo/pipelines/pipe_node_test")) {
|
||||
savedWorkflowPayload = opts.json;
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
...mockDetail,
|
||||
...opts.json,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
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)
|
||||
);
|
||||
|
||||
// 2. node list
|
||||
const listRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["list", "pipe_node_test"],
|
||||
options: {},
|
||||
raw: ["workflow", "node", "list", "pipe_node_test"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(listRes.exitCode).toBe(0);
|
||||
expect(listRes.stdout).toContain("任务节点树 (共 2 个节点)");
|
||||
expect(listRes.stdout).toContain("trigger_webhook_1");
|
||||
expect(listRes.stdout).toContain("action_js_1");
|
||||
|
||||
// 2.1 node list in json mode
|
||||
const listJsonRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["ls", "pipe_node_test"],
|
||||
options: {},
|
||||
raw: ["workflow", "node", "ls", "pipe_node_test"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
expect(listJsonRes.exitCode).toBe(0);
|
||||
const parsedList = JSON.parse(listJsonRes.stdout);
|
||||
expect(parsedList.totalNodes).toBe(2);
|
||||
|
||||
// 3. node get
|
||||
const getRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["get", "pipe_node_test", "action_js_1"],
|
||||
options: {},
|
||||
raw: ["workflow", "node", "get", "pipe_node_test", "action_js_1"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(getRes.exitCode).toBe(0);
|
||||
expect(getRes.stdout).toContain("节点详情 [action_js_1]");
|
||||
expect(getRes.stdout).toContain("return items.filter");
|
||||
|
||||
// 4. node add (requires confirmation)
|
||||
await expect(
|
||||
handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["add", "pipe_node_test"],
|
||||
options: { type: "stop", label: "终止超额" },
|
||||
raw: ["workflow", "node", "add", "pipe_node_test", "--type=stop"],
|
||||
},
|
||||
mockRuntime
|
||||
)
|
||||
).rejects.toThrow("请先使用 --dry-run");
|
||||
|
||||
// 4.1 node add dry-run
|
||||
const addDryRunRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["add", "pipe_node_test"],
|
||||
options: { type: "stop", label: "终止超额", "dry-run": true },
|
||||
raw: ["workflow", "node", "add", "pipe_node_test", "--type=stop", "--label=终止超额", "--dry-run"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(addDryRunRes.exitCode).toBe(0);
|
||||
expect(addDryRunRes.stdout).toContain("[DRY-RUN]");
|
||||
expect(addDryRunRes.stdout).toContain("终止超额");
|
||||
expect(savedWorkflowPayload).toBeNull();
|
||||
|
||||
// 4.2 node add confirmed execution
|
||||
const addRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["add", "pipe_node_test"],
|
||||
options: { type: "stop", label: "终止超额", yes: true },
|
||||
raw: ["workflow", "node", "add", "pipe_node_test", "--type=stop", "--label=终止超额", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(addRes.exitCode).toBe(0);
|
||||
expect(addRes.stdout).toContain("已成功添加至工作流");
|
||||
expect(addRes.stdout).toContain("终止超额");
|
||||
expect(savedWorkflowPayload).not.toBeNull();
|
||||
expect(savedWorkflowPayload.tasks).toHaveLength(3);
|
||||
|
||||
// 5. node edit
|
||||
const editRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["edit", "pipe_node_test", "action_js_1"],
|
||||
options: { label: "数据清洗升级版", code: "return true;", yes: true },
|
||||
raw: ["workflow", "node", "edit", "pipe_node_test", "action_js_1", "--label=数据清洗升级版", "--code=return true;", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(editRes.exitCode).toBe(0);
|
||||
expect(editRes.stdout).toContain("修改已保存至工作流");
|
||||
|
||||
// 6. node rm
|
||||
const rmRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["rm", "pipe_node_test", "action_js_1"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "node", "rm", "pipe_node_test", "action_js_1", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(rmRes.exitCode).toBe(0);
|
||||
expect(rmRes.stdout).toContain("已从工作流 [pipe_node_test] 中安全移除");
|
||||
|
||||
// 6.1 node rm trigger guard
|
||||
await expect(
|
||||
handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["rm", "pipe_node_test", "trigger_webhook_1"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "node", "rm", "pipe_node_test", "trigger_webhook_1", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
)
|
||||
).rejects.toThrow("触发源节点");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { handleWorkflowTest } from "./test.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { handleNodeCommand } from "./node.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -89,10 +90,13 @@ export async function handleWorkflowCommand(
|
||||
case "new":
|
||||
case "add":
|
||||
return handleCreate(parsed, runtime);
|
||||
case "node":
|
||||
case "nodes":
|
||||
return handleNodeCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
import {
|
||||
getWorkflowDetail,
|
||||
updateWorkflow,
|
||||
flattenWorkflowTaskTree,
|
||||
findWorkflowTask,
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
let subAction = "list";
|
||||
let pipelineId = "";
|
||||
let nodeTarget = "";
|
||||
|
||||
if (firstArg && SUB_ACTIONS.has(firstArg)) {
|
||||
subAction = firstArg;
|
||||
pipelineId = parsed.args[1] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||||
nodeTarget = parsed.args[2] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
} else if (firstArg) {
|
||||
// 允许缩写直接跟 pipelineId: hose-use workflow node <pipelineId>
|
||||
pipelineId = firstArg;
|
||||
nodeTarget = parsed.args[1] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
} else {
|
||||
pipelineId = stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||||
nodeTarget = stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||||
}
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
|
||||
"",
|
||||
"子命令:",
|
||||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow node list 896398895352487950",
|
||||
" hose-use workflow node get 896398895352487950 action_dx9cci",
|
||||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code='return items;' --yes",
|
||||
" hose-use workflow node edit 896398895352487950 action_dx9cci --label='新清洗逻辑' --yes",
|
||||
" hose-use workflow node rm 896398895352487950 action_dx9cci --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
switch (subAction) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleListNodes(pipelineId, parsed, runtime);
|
||||
case "get":
|
||||
case "show":
|
||||
case "info":
|
||||
return handleGetNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "add":
|
||||
case "append":
|
||||
case "insert":
|
||||
return handleAddNode(pipelineId, parsed, runtime);
|
||||
case "edit":
|
||||
case "update":
|
||||
case "set":
|
||||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "rm":
|
||||
case "remove":
|
||||
case "delete":
|
||||
case "del":
|
||||
return handleRemoveNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow node 子命令: ${subAction}。支持: list, get, add, edit, rm\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleListNodes(
|
||||
pipelineId: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const tasks = detail.tasks || [];
|
||||
const flattened = flattenWorkflowTaskTree(tasks);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ pipelineId, label: detail.label, totalNodes: flattened.length, nodes: flattened }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (flattened.length === 0) {
|
||||
return {
|
||||
stdout: `工作流 [${detail.label || pipelineId}] 暂无任何任务节点。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = flattened.map((item) => [
|
||||
item.hierarchicalIndex,
|
||||
item.task.name,
|
||||
item.task.type,
|
||||
item.task.label || "-",
|
||||
item.task.groupName || "-",
|
||||
item.summary,
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "节点标识 (name)", "类型 (type)", "标题 (label)", "分组", "配置摘要"],
|
||||
rows
|
||||
);
|
||||
|
||||
const out = [
|
||||
`====== 工作流 [${detail.label || pipelineId}] 任务节点树 (共 ${flattened.length} 个节点) ======`,
|
||||
table,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGetNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node get <pipelineId> <nodeNameOrIndex>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||||
|
||||
if (!located) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ pipelineId, ...located }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const { task, hierarchicalIndex, path, parentName } = located;
|
||||
const kv: Record<string, string> = {
|
||||
"工作流 ID": pipelineId,
|
||||
"节点标识 (name)": task.name,
|
||||
"层级编号 (#)": hierarchicalIndex,
|
||||
"JSON 路径": path,
|
||||
"父容器节点": parentName || "顶级节点 (root)",
|
||||
"节点类型 (type)": task.type,
|
||||
"节点标题 (label)": task.label || "-",
|
||||
"节点分组 (group)": task.groupName || "-",
|
||||
"状态 (status)": task.status || "active",
|
||||
};
|
||||
|
||||
if ((task as any).code !== undefined) {
|
||||
kv["代码行数"] = String((task as any).code.split("\n").length);
|
||||
}
|
||||
|
||||
const outLines = [
|
||||
`====== 节点详情 [${task.name}] (${task.label || task.type}) ======`,
|
||||
printKeyValue(kv),
|
||||
];
|
||||
|
||||
if ((task as any).code) {
|
||||
outLines.push("\n--- 脚本内容 ---");
|
||||
outLines.push((task as any).code);
|
||||
}
|
||||
|
||||
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAddNode(
|
||||
pipelineId: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const type = stringOption(parsed.options, ["type", "t"]);
|
||||
if (!type) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const label = stringOption(parsed.options, ["label", "name", "l"]);
|
||||
const parent = stringOption(parsed.options, ["parent", "container", "p"]);
|
||||
const after = stringOption(parsed.options, ["after", "insert-after"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||||
let code = stringOption(parsed.options, ["code", "c"]);
|
||||
|
||||
if (codeFile) {
|
||||
const fs = await import("fs/promises");
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"追加工作流节点",
|
||||
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, {
|
||||
type,
|
||||
label,
|
||||
desc,
|
||||
code,
|
||||
parent,
|
||||
after,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
newNodeName: newTask.name,
|
||||
type: newTask.type,
|
||||
label: newTask.label,
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
totalTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const out = [
|
||||
`✨ 节点 [${newTask.name}] (${newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
|
||||
printKeyValue({
|
||||
"节点标识 (name)": newTask.name,
|
||||
"节点类型 (type)": newTask.type,
|
||||
"节点标题 (label)": newTask.label || "-",
|
||||
"所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾",
|
||||
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
|
||||
}),
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEditNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const label = stringOption(parsed.options, ["label", "l"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||||
let code = stringOption(parsed.options, ["code", "c"]);
|
||||
|
||||
if (codeFile) {
|
||||
const fs = await import("fs/promises");
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const customSet: Record<string, any> = {};
|
||||
if (rawSet) {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"修改工作流节点",
|
||||
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, {
|
||||
label,
|
||||
desc,
|
||||
code,
|
||||
set: Object.keys(customSet).length > 0 ? customSet : undefined,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRemoveNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供待删除节点标识 (name 或层级序号): hose-use workflow node rm <pipelineId> <nodeNameOrIndex>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"移除工作流节点",
|
||||
`hose-use workflow node rm ${pipelineId} ${nodeTarget} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, removedTask } = removeWorkflowTask(detail, nodeTarget);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "移除工作流节点", `${pipelineId}:${removedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: removedTask.name,
|
||||
type: removedTask.type,
|
||||
label: removedTask.label || "-",
|
||||
remainingTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, removedTask, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -6,10 +6,11 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
@@ -27,6 +28,11 @@ hose-use workflow debug <pipelineId> --flow=<单号> --yes
|
||||
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
|
||||
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
|
||||
hose-use workflow delete <pipelineId> [--dry-run|--yes]
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node get <pipelineId> <节点name或#序号>
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
|
||||
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
|
||||
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
|
||||
```
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
@@ -940,4 +940,7 @@ export async function getWorkflowSampleData(
|
||||
return api.getWorkflowSampleData(client, pipelineId, type);
|
||||
}
|
||||
|
||||
export * from "./workflow-nodes.js";
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
flattenWorkflowTaskTree,
|
||||
findWorkflowTask,
|
||||
reindexTasks,
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
buildWorkflowTask,
|
||||
summarizeTask,
|
||||
} from "./workflow-nodes.js";
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
const mockWorkflow: WorkflowDetail = {
|
||||
id: "wf_test_100",
|
||||
label: "发票风险处理流水线",
|
||||
state: 0,
|
||||
debugState: 0,
|
||||
runTimes: 0,
|
||||
errorTimes: 0,
|
||||
updateTime: "2026-10-15",
|
||||
version: "26.10.1",
|
||||
dataLimit: 20,
|
||||
source: 0,
|
||||
queueJobs: false,
|
||||
tasksVersion: 0,
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_webhook_1",
|
||||
type: "webhook",
|
||||
label: "发票数据接入",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: "test-uuid-1",
|
||||
params: [],
|
||||
},
|
||||
{
|
||||
name: "control_every_1",
|
||||
type: "every",
|
||||
label: "循环发票明细",
|
||||
desc: "依次遍历每张发票",
|
||||
groupName: "control",
|
||||
mode: "sequence",
|
||||
batch: false,
|
||||
list: "@{choose('body.invoices')}",
|
||||
filters: [],
|
||||
tasksMaxLevel: 1,
|
||||
orderIndex: 1,
|
||||
levelIndex: [1],
|
||||
status: "active",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_js_1",
|
||||
type: "code-js2",
|
||||
label: "数据清洗",
|
||||
groupName: "action",
|
||||
orderIndex: 2,
|
||||
levelIndex: [1, 0],
|
||||
status: "active",
|
||||
code: "return item.amount > 0;",
|
||||
},
|
||||
{
|
||||
name: "control_cond_1",
|
||||
type: "condition",
|
||||
label: "超额判定",
|
||||
groupName: "control",
|
||||
combineFilters: { condition: "or", filters: [] },
|
||||
tasksMaxLevel: 1,
|
||||
orderIndex: 3,
|
||||
levelIndex: [1, 1],
|
||||
status: "active",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_stop_1",
|
||||
type: "stop",
|
||||
label: "阻断超额",
|
||||
groupName: "control",
|
||||
orderIndex: 4,
|
||||
levelIndex: [1, 1, 0],
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "action_http_1",
|
||||
type: "http",
|
||||
label: "通知外部系统",
|
||||
groupName: "action",
|
||||
method: "POST",
|
||||
url: "https://api.example.com/notify",
|
||||
orderIndex: 5,
|
||||
levelIndex: [2],
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("workflow-nodes - 任务节点声明式编排纯函数", () => {
|
||||
it("flattenWorkflowTaskTree correctly flattens nested tree with depth and summary", () => {
|
||||
const flattened = flattenWorkflowTaskTree(mockWorkflow.tasks);
|
||||
expect(flattened).toHaveLength(6);
|
||||
|
||||
// 1. Webhook trigger
|
||||
expect(flattened[0].hierarchicalIndex).toBe("1");
|
||||
expect(flattened[0].task.name).toBe("trigger_webhook_1");
|
||||
expect(flattened[0].depth).toBe(0);
|
||||
expect(flattened[0].summary).toContain("urlPath: test-uuid-1");
|
||||
|
||||
// 2. Every container
|
||||
expect(flattened[1].hierarchicalIndex).toBe("2");
|
||||
expect(flattened[1].task.name).toBe("control_every_1");
|
||||
expect(flattened[1].depth).toBe(0);
|
||||
expect(flattened[1].summary).toContain("循环遍历");
|
||||
|
||||
// 3. Child in every container (code-js2)
|
||||
expect(flattened[2].hierarchicalIndex).toBe("2.1");
|
||||
expect(flattened[2].task.name).toBe("action_js_1");
|
||||
expect(flattened[2].depth).toBe(1);
|
||||
expect(flattened[2].parentName).toBe("control_every_1");
|
||||
expect(flattened[2].summary).toContain("脚本 (23 字符)");
|
||||
|
||||
// 4. Condition in every container
|
||||
expect(flattened[3].hierarchicalIndex).toBe("2.2");
|
||||
expect(flattened[3].task.name).toBe("control_cond_1");
|
||||
expect(flattened[3].depth).toBe(1);
|
||||
|
||||
// 5. Stop inside condition inside every
|
||||
expect(flattened[4].hierarchicalIndex).toBe("2.2.1");
|
||||
expect(flattened[4].task.name).toBe("action_stop_1");
|
||||
expect(flattened[4].depth).toBe(2);
|
||||
expect(flattened[4].summary).toBe("阻断终止流程");
|
||||
|
||||
// 6. Http top-level task
|
||||
expect(flattened[5].hierarchicalIndex).toBe("3");
|
||||
expect(flattened[5].task.name).toBe("action_http_1");
|
||||
expect(flattened[5].depth).toBe(0);
|
||||
expect(flattened[5].summary).toContain("POST https://api.example.com/notify");
|
||||
});
|
||||
|
||||
it("findWorkflowTask finds nodes by name, hierarchical index, or global number", () => {
|
||||
// By name
|
||||
const byName = findWorkflowTask(mockWorkflow.tasks, "action_js_1");
|
||||
expect(byName).not.toBeNull();
|
||||
expect(byName?.task.label).toBe("数据清洗");
|
||||
expect(byName?.hierarchicalIndex).toBe("2.1");
|
||||
expect(byName?.path).toBe("tasks.1.tasks.0");
|
||||
|
||||
// By hierarchical index
|
||||
const byHierarchical = findWorkflowTask(mockWorkflow.tasks, "2.2.1");
|
||||
expect(byHierarchical).not.toBeNull();
|
||||
expect(byHierarchical?.task.name).toBe("action_stop_1");
|
||||
|
||||
// By global sequential index number
|
||||
const byGlobalIndex = findWorkflowTask(mockWorkflow.tasks, 3);
|
||||
expect(byGlobalIndex).not.toBeNull();
|
||||
expect(byGlobalIndex?.task.name).toBe("action_js_1");
|
||||
|
||||
// Non-existent target
|
||||
const notFound = findWorkflowTask(mockWorkflow.tasks, "non_existent_node");
|
||||
expect(notFound).toBeNull();
|
||||
});
|
||||
|
||||
it("reindexTasks recalculates orderIndex and levelIndex consistently", () => {
|
||||
const clonedTasks: WorkflowTask[] = JSON.parse(JSON.stringify(mockWorkflow.tasks));
|
||||
// Mess up indices
|
||||
clonedTasks[0].orderIndex = 99;
|
||||
clonedTasks[1].levelIndex = [9, 9];
|
||||
|
||||
reindexTasks(clonedTasks);
|
||||
|
||||
expect(clonedTasks[0].orderIndex).toBe(0);
|
||||
expect(clonedTasks[0].levelIndex).toEqual([0]);
|
||||
|
||||
expect(clonedTasks[1].orderIndex).toBe(1);
|
||||
expect(clonedTasks[1].levelIndex).toEqual([1]);
|
||||
|
||||
expect(clonedTasks[1].tasks![0].orderIndex).toBe(2);
|
||||
expect(clonedTasks[1].tasks![0].levelIndex).toEqual([1, 0]);
|
||||
|
||||
expect(clonedTasks[1].tasks![1].tasks![0].orderIndex).toBe(4);
|
||||
expect(clonedTasks[1].tasks![1].tasks![0].levelIndex).toEqual([1, 1, 0]);
|
||||
});
|
||||
|
||||
it("addWorkflowTask appends to root, inserts after node, and inserts into parent container", () => {
|
||||
// 1. Append to root
|
||||
const { workflow: wfAppended, newTask: appendedTask } = addWorkflowTask(mockWorkflow, {
|
||||
type: "code-js2",
|
||||
label: "末尾数据汇总",
|
||||
code: "return { total: 100 };",
|
||||
});
|
||||
expect(wfAppended.tasks).toHaveLength(4);
|
||||
expect(appendedTask.label).toBe("末尾数据汇总");
|
||||
expect(wfAppended.tasks[3].name).toBe(appendedTask.name);
|
||||
expect(wfAppended.tasks[3].levelIndex).toEqual([3]);
|
||||
|
||||
// 2. Insert into parent container
|
||||
const { workflow: wfParent, newTask: parentTask } = addWorkflowTask(mockWorkflow, {
|
||||
type: "stop",
|
||||
label: "循环中终止",
|
||||
parent: "control_every_1",
|
||||
});
|
||||
const everyNode = wfParent.tasks[1];
|
||||
expect(everyNode.tasks).toHaveLength(3);
|
||||
expect(everyNode.tasks![2].name).toBe(parentTask.name);
|
||||
expect(everyNode.tasks![2].levelIndex).toEqual([1, 2]);
|
||||
|
||||
// 3. Insert after specific node
|
||||
const { workflow: wfAfter, newTask: afterTask } = addWorkflowTask(mockWorkflow, {
|
||||
type: "code",
|
||||
label: "MVEL计算节点",
|
||||
after: "action_js_1",
|
||||
code: "return 1 + 1;",
|
||||
});
|
||||
const everyTasks = wfAfter.tasks[1].tasks!;
|
||||
expect(everyTasks).toHaveLength(3);
|
||||
expect(everyTasks[0].name).toBe("action_js_1");
|
||||
expect(everyTasks[1].name).toBe(afterTask.name); // Inserted right after
|
||||
expect(everyTasks[1].label).toBe("MVEL计算节点");
|
||||
expect(everyTasks[1].levelIndex).toEqual([1, 1]);
|
||||
});
|
||||
|
||||
it("editWorkflowTask updates label, code, and custom properties", () => {
|
||||
const { workflow: wfEdited, editedTask } = editWorkflowTask(mockWorkflow, "action_js_1", {
|
||||
label: "数据清洗升级版",
|
||||
code: "return item.amount > 500;",
|
||||
desc: "只保留大于500的发票",
|
||||
set: { customTag: "finance-audit" },
|
||||
});
|
||||
|
||||
expect(editedTask.label).toBe("数据清洗升级版");
|
||||
expect((editedTask as any).code).toBe("return item.amount > 500;");
|
||||
expect(editedTask.desc).toBe("只保留大于500的发票");
|
||||
expect((editedTask as any).customTag).toBe("finance-audit");
|
||||
|
||||
// Original workflow must not be mutated
|
||||
expect(mockWorkflow.tasks[1].tasks![0].label).toBe("数据清洗");
|
||||
});
|
||||
|
||||
it("removeWorkflowTask safely removes task and guards trigger node", () => {
|
||||
// 1. Remove child task in container
|
||||
const { workflow: wfRemoved, removedTask } = removeWorkflowTask(mockWorkflow, "action_js_1");
|
||||
expect(removedTask.name).toBe("action_js_1");
|
||||
expect(wfRemoved.tasks[1].tasks).toHaveLength(1);
|
||||
expect(wfRemoved.tasks[1].tasks![0].name).toBe("control_cond_1");
|
||||
expect(wfRemoved.tasks[1].tasks![0].levelIndex).toEqual([1, 0]); // Re-indexed to 0
|
||||
|
||||
// 2. Trigger protection: removing primary trigger when other tasks exist throws ValidationError
|
||||
expect(() => {
|
||||
removeWorkflowTask(mockWorkflow, "trigger_webhook_1");
|
||||
}).toThrow("触发源节点");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,448 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
|
||||
export interface FlattenedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
index: number; // 1-based global sequential index
|
||||
hierarchicalIndex: string; // e.g. "1", "2.1", "2.1.3"
|
||||
depth: number;
|
||||
path: string;
|
||||
parentName?: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface LocatedWorkflowTask {
|
||||
task: WorkflowTask;
|
||||
path: string;
|
||||
parentTasks: WorkflowTask[];
|
||||
arrayIndex: number;
|
||||
hierarchicalIndex: string;
|
||||
globalIndex: number;
|
||||
parentName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归计算并生成节点的紧凑配置摘要
|
||||
*/
|
||||
export function summarizeTask(task: WorkflowTask): string {
|
||||
if (task.type === "webhook") {
|
||||
return task.urlPath ? `urlPath: ${task.urlPath}` : "未配置URL";
|
||||
}
|
||||
if (task.type === "clock") {
|
||||
return `cron: ${task.cron || "0 0 * * *"} (${task.timeZone || "Asia/Shanghai"})`;
|
||||
}
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
const rawCode: string = (task as any).code || "";
|
||||
const firstLine = rawCode.trim().split("\n")[0] || "";
|
||||
const len = rawCode.length;
|
||||
return `脚本 (${len} 字符): ${firstLine.slice(0, 40)}${firstLine.length > 40 ? "..." : ""}`;
|
||||
}
|
||||
if (task.type === "http") {
|
||||
return `${(task as any).method || "POST"} ${(task as any).url || ""}`;
|
||||
}
|
||||
if (task.type === "every") {
|
||||
return `循环遍历: ${(task as any).list || "$item"} (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "condition") {
|
||||
const filters = (task as any).combineFilters?.filters || [];
|
||||
return `分支条件: ${filters.length} 组规则 (含 ${task.tasks?.length || 0} 个子节点)`;
|
||||
}
|
||||
if (task.type === "stop") {
|
||||
return "阻断终止流程";
|
||||
}
|
||||
if (task.type === "ekuaibao-datalink-create-trigger") {
|
||||
return "业务对象台账新增触发";
|
||||
}
|
||||
if (task.type === "ekuaibao-flowform-trigger") {
|
||||
return "单据流转事件触发";
|
||||
}
|
||||
return task.desc || task.label || task.type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将整棵工作流任务树展平为有序列表,便于查看与索引
|
||||
*/
|
||||
export function flattenWorkflowTaskTree(tasks: WorkflowTask[]): FlattenedWorkflowTask[] {
|
||||
const result: FlattenedWorkflowTask[] = [];
|
||||
let globalCounter = 0;
|
||||
|
||||
function traverse(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
depth: number,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
) {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
result.push({
|
||||
task,
|
||||
index: globalCounter,
|
||||
hierarchicalIndex,
|
||||
depth,
|
||||
path,
|
||||
parentName,
|
||||
summary: summarizeTask(task),
|
||||
});
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks, hierarchicalIndex, depth + 1, `${path}.tasks`, task.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks, "", 0, "tasks");
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在任务树中按节点名称、层级编号 (如 "2.1") 或全局序号定位目标任务
|
||||
*/
|
||||
export function findWorkflowTask(
|
||||
tasks: WorkflowTask[],
|
||||
target: string | number
|
||||
): LocatedWorkflowTask | null {
|
||||
const targetStr = String(target).trim();
|
||||
const targetNum = Number(targetStr);
|
||||
const isNumeric = !Number.isNaN(targetNum) && Number.isInteger(targetNum) && targetNum > 0;
|
||||
|
||||
let globalCounter = 0;
|
||||
|
||||
function search(
|
||||
list: WorkflowTask[],
|
||||
prefix: string,
|
||||
basePath: string,
|
||||
parentName?: string
|
||||
): LocatedWorkflowTask | null {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const task = list[i];
|
||||
globalCounter += 1;
|
||||
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
|
||||
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
|
||||
|
||||
const matched =
|
||||
task.name === targetStr ||
|
||||
hierarchicalIndex === targetStr ||
|
||||
(isNumeric && globalCounter === targetNum);
|
||||
|
||||
if (matched) {
|
||||
return {
|
||||
task,
|
||||
path,
|
||||
parentTasks: list,
|
||||
arrayIndex: i,
|
||||
hierarchicalIndex,
|
||||
globalIndex: globalCounter,
|
||||
parentName,
|
||||
};
|
||||
}
|
||||
|
||||
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
const found = search(task.tasks, hierarchicalIndex, `${path}.tasks`, task.name);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return search(tasks, "", "tasks");
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归重算整棵树的 orderIndex 与 levelIndex
|
||||
*/
|
||||
export function reindexTasks(
|
||||
tasks: WorkflowTask[],
|
||||
parentLevel: number[] = [],
|
||||
startOrder = 0
|
||||
): number {
|
||||
let currentOrder = startOrder;
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
const task = tasks[i];
|
||||
task.orderIndex = currentOrder++;
|
||||
task.levelIndex = [...parentLevel, i];
|
||||
if (task.tasks && Array.isArray(task.tasks)) {
|
||||
currentOrder = reindexTasks(task.tasks, task.levelIndex, currentOrder);
|
||||
}
|
||||
}
|
||||
return currentOrder;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成规范唯一的合思节点 ID
|
||||
*/
|
||||
export function generateNodeName(type: string): string {
|
||||
const rand = Math.random().toString(36).substring(2, 8);
|
||||
if (type === "every" || type === "condition") {
|
||||
return `control_${rand}`;
|
||||
}
|
||||
if (type.includes("trigger") || type === "webhook" || type === "clock") {
|
||||
return `trigger_${rand}`;
|
||||
}
|
||||
return `action_${rand}`;
|
||||
}
|
||||
|
||||
export interface AddTaskOptions {
|
||||
type: string;
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
parent?: string | number;
|
||||
after?: string | number;
|
||||
extra?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建规范的新节点对象
|
||||
*/
|
||||
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
|
||||
const normType = type.trim();
|
||||
const name = generateNodeName(normType);
|
||||
|
||||
switch (normType) {
|
||||
case "code-js2":
|
||||
return {
|
||||
name,
|
||||
type: "code-js2",
|
||||
label: options.label || "JS节点(新)",
|
||||
desc: options.desc || "执行一段JavaScript代码",
|
||||
groupName: "action",
|
||||
code: options.code || "// 编写处理逻辑\nreturn items;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "code":
|
||||
return {
|
||||
name,
|
||||
type: "code",
|
||||
label: options.label || "代码节点",
|
||||
desc: options.desc || "执行一段MVEL代码",
|
||||
groupName: "action",
|
||||
code: options.code || "return true;",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "http":
|
||||
return {
|
||||
name,
|
||||
type: "http",
|
||||
label: options.label || "HTTP请求",
|
||||
groupName: "action",
|
||||
method: options.extra?.method || "POST",
|
||||
url: options.extra?.url || "",
|
||||
header: options.extra?.header || [],
|
||||
params: options.extra?.params || [],
|
||||
successCode: options.extra?.successCode || ["200"],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "stop":
|
||||
return {
|
||||
name,
|
||||
type: "stop",
|
||||
label: options.label || "终止流程",
|
||||
desc: options.desc || "如果满足条件终止流程",
|
||||
groupName: "control",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "every":
|
||||
return {
|
||||
name,
|
||||
type: "every",
|
||||
label: options.label || "依次执行",
|
||||
desc: options.desc || "依次遍历每个对象",
|
||||
groupName: "control",
|
||||
mode: "sequence",
|
||||
batch: false,
|
||||
list: options.extra?.list || "@{choose('...$item')}",
|
||||
filters: [],
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "condition":
|
||||
return {
|
||||
name,
|
||||
type: "condition",
|
||||
label: options.label || "条件分支",
|
||||
desc: options.desc || "如果满足条件则执行以下动作",
|
||||
groupName: "control",
|
||||
combineFilters: options.extra?.combineFilters || { condition: "or", filters: [] },
|
||||
tasksMaxLevel: 1,
|
||||
tasks: [],
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "webhook":
|
||||
return {
|
||||
name,
|
||||
type: "webhook",
|
||||
label: options.label || "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: crypto.randomUUID(),
|
||||
params: [],
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
case "clock":
|
||||
return {
|
||||
name,
|
||||
type: "clock",
|
||||
label: options.label || "定时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
cron: options.extra?.cron || "0 0 * * *",
|
||||
timeZone: options.extra?.timeZone || "Asia/Shanghai",
|
||||
...options.extra,
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
name,
|
||||
type: normType,
|
||||
label: options.label || `${normType}节点`,
|
||||
desc: options.desc || "",
|
||||
groupName: normType.startsWith("control") ? "control" : "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
...options.extra,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向工作流声明式追加或插入任务节点
|
||||
*/
|
||||
export function addWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
options: AddTaskOptions
|
||||
): { workflow: WorkflowDetail; newTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const newTask = buildWorkflowTask(options.type, options);
|
||||
|
||||
if (options.after !== undefined && options.after !== "") {
|
||||
const target = findWorkflowTask(cloned.tasks, options.after);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到插入基准节点 (--after): ${options.after}`);
|
||||
}
|
||||
// 插入在该节点的下一个位置
|
||||
target.parentTasks.splice(target.arrayIndex + 1, 0, newTask);
|
||||
} else if (options.parent !== undefined && options.parent !== "") {
|
||||
const parentTarget = findWorkflowTask(cloned.tasks, options.parent);
|
||||
if (!parentTarget) {
|
||||
throw new NotFoundError(`未找到父级容器节点 (--parent): ${options.parent}`);
|
||||
}
|
||||
if (!parentTarget.task.tasks) parentTarget.task.tasks = [];
|
||||
parentTarget.task.tasks.push(newTask);
|
||||
} else {
|
||||
// 默认追加到顶级 tasks 末尾
|
||||
cloned.tasks.push(newTask);
|
||||
}
|
||||
|
||||
// 重排索引
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, newTask };
|
||||
}
|
||||
|
||||
export interface EditTaskOptions {
|
||||
label?: string;
|
||||
code?: string;
|
||||
desc?: string;
|
||||
set?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定向修改工作流任务节点配置
|
||||
*/
|
||||
export function editWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number,
|
||||
updates: EditTaskOptions
|
||||
): { workflow: WorkflowDetail; editedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks) cloned.tasks = [];
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
const { task } = target;
|
||||
if (updates.label !== undefined) task.label = updates.label;
|
||||
if (updates.desc !== undefined) task.desc = updates.desc;
|
||||
if (updates.code !== undefined) (task as any).code = updates.code;
|
||||
|
||||
if (updates.set && typeof updates.set === "object") {
|
||||
for (const [k, v] of Object.entries(updates.set)) {
|
||||
(task as any)[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
return { workflow: cloned, editedTask: task };
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全剔除工作流任务节点
|
||||
*/
|
||||
export function removeWorkflowTask(
|
||||
workflow: WorkflowDetail,
|
||||
targetKey: string | number
|
||||
): { workflow: WorkflowDetail; removedTask: WorkflowTask } {
|
||||
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||
if (!cloned.tasks || cloned.tasks.length === 0) {
|
||||
throw new ValidationError("工作流中无任何任务节点,无法删除");
|
||||
}
|
||||
|
||||
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||
if (!target) {
|
||||
throw new NotFoundError(`未找到待删除的工作流任务节点: ${targetKey}`);
|
||||
}
|
||||
|
||||
// 触发器保护:如果工作流只有首节点且是触发器,或者删除首节点触发器
|
||||
if (
|
||||
target.parentTasks === cloned.tasks &&
|
||||
target.arrayIndex === 0 &&
|
||||
cloned.tasks.length > 1 &&
|
||||
(target.task.groupName === "trigger" || target.task.type.includes("trigger") || target.task.type === "webhook" || target.task.type === "clock")
|
||||
) {
|
||||
throw new ValidationError(
|
||||
`节点 [${target.task.name}] (${target.task.label || target.task.type}) 是工作流的触发源节点。直接移除会导致工作流缺少触发器,请使用 workflow save 或在设计器中调整触发器。`
|
||||
);
|
||||
}
|
||||
|
||||
const [removedTask] = target.parentTasks.splice(target.arrayIndex, 1);
|
||||
reindexTasks(cloned.tasks);
|
||||
return { workflow: cloned, removedTask };
|
||||
}
|
||||
Reference in new issue
Block a user