Merge pull request #112 from yunyingk/feat/workflow-create-pure
feat(workflow): implement workflow create command from scratch with draft state defense
This commit is contained in:
7 files changed
+390
-7
No files matched your search
@@ -202,6 +202,7 @@ hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
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 预览)
|
||||
|
||||
|
||||
@@ -234,19 +234,29 @@ hose-use workflow publish <pipelineId>
|
||||
|
||||
---
|
||||
|
||||
## 14. 复制与删除工作流 (`workflow copy` / `workflow delete`)
|
||||
## 14. 从零创建、复制与删除工作流 (`workflow create` / `copy` / `delete`)
|
||||
|
||||
对标合思 EASO/Piper 网页端“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁:
|
||||
对标合思 EASO/Piper 网页端“新建工作流”、“复制流水线”与“删除”功能,严格遵循 `--dry-run` 预览与 `--yes` 安全确认门禁,且新流程初始状态**强制锁定为草稿未启用(`state = 0`)**:
|
||||
|
||||
```bash
|
||||
# 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本)
|
||||
# 1. 从零新建工作流(支持自动初始化 Webhook、定时 Clock、业务对象 DataLink 或单据 Flowform 首节点)
|
||||
hose-use workflow create --name="外部风险推送" --trigger=webhook --yes
|
||||
hose-use workflow create --name="每日发票对账" --trigger=clock --platform-id=ID01uzxB4x07fh --yes
|
||||
|
||||
# 2. 从本地 JSON 模板文件一键新建
|
||||
hose-use workflow create --file=workflow-template.json --name="生产流程-A" --yes
|
||||
|
||||
# 别名支持 new, add
|
||||
hose-use workflow new --name="合同归档触发" --trigger=datalink --yes
|
||||
|
||||
# 3. 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本)
|
||||
hose-use workflow copy <pipelineId> --dry-run
|
||||
hose-use workflow copy <pipelineId> --name="发票监控克隆版" --yes
|
||||
|
||||
# 别名支持 cp, clone
|
||||
hose-use workflow cp <pipelineId> --yes
|
||||
|
||||
# 删除指定工作流(不可逆,必须确认)
|
||||
# 4. 删除指定工作流(不可逆,必须确认)
|
||||
hose-use workflow delete <pipelineId> --dry-run
|
||||
hose-use workflow delete <pipelineId> --yes
|
||||
|
||||
|
||||
@@ -1297,4 +1297,167 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
expect(parsedJson.success).toBe(true);
|
||||
expect(parsedJson.pipelineId).toBe("pipe_del_999");
|
||||
});
|
||||
|
||||
it("handles workflow create: requires confirmation, dry-run, execution, triggers, and json mode", async () => {
|
||||
// 1. Missing mutation confirmation
|
||||
await expect(
|
||||
handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "create",
|
||||
args: ["新风险拦截流程"],
|
||||
options: {},
|
||||
raw: ["workflow", "create", "新风险拦截流程"],
|
||||
},
|
||||
mockRuntime
|
||||
)
|
||||
).rejects.toThrow("请先使用 --dry-run");
|
||||
|
||||
// 2. Dry-run preview
|
||||
const dryRunRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "create",
|
||||
args: ["新风险拦截流程"],
|
||||
options: { trigger: "webhook", "dry-run": true },
|
||||
raw: ["workflow", "create", "新风险拦截流程", "--trigger=webhook", "--dry-run"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(dryRunRes.exitCode).toBe(0);
|
||||
expect(dryRunRes.stdout).toContain("[DRY-RUN]");
|
||||
expect(dryRunRes.stdout).toContain("新风险拦截流程");
|
||||
expect(dryRunRes.stdout).toContain("webhook");
|
||||
|
||||
let createdPayload: any = null;
|
||||
const mockClient = {
|
||||
post: (url: string, opts: any) => {
|
||||
if (url.includes("api/easo/pipelines")) {
|
||||
createdPayload = opts.json;
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "pipe_new_777",
|
||||
label: opts.json.label,
|
||||
platformId: opts.json.platformId || "app_default",
|
||||
state: opts.json.state ?? 0,
|
||||
version: "26.10.1",
|
||||
tasks: opts.json.tasks || [],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ code: 200, data: null }) };
|
||||
},
|
||||
get: () => ({ 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)
|
||||
);
|
||||
|
||||
// 3. Confirmed execution with webhook trigger
|
||||
const createRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "create",
|
||||
args: ["外部发票接入"],
|
||||
options: { trigger: "webhook", yes: true },
|
||||
raw: ["workflow", "create", "外部发票接入", "--trigger=webhook", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(createRes.exitCode).toBe(0);
|
||||
expect(createRes.stdout).toContain("工作流创建成功");
|
||||
expect(createRes.stdout).toContain("pipe_new_777");
|
||||
expect(createRes.stdout).toContain("外部发票接入");
|
||||
expect(createRes.stdout).toContain("https://piper.ekuaibao.com/api/webhook/");
|
||||
expect(createRes.stdout).toContain("草稿未发布");
|
||||
|
||||
expect(createdPayload).not.toBeNull();
|
||||
expect(createdPayload.label).toBe("外部发票接入");
|
||||
expect(createdPayload.state).toBe(0);
|
||||
expect(createdPayload.tasks).toHaveLength(1);
|
||||
expect(createdPayload.tasks[0].type).toBe("webhook");
|
||||
expect(createdPayload.tasks[0].urlPath).toBeDefined();
|
||||
|
||||
// 4. Create with clock trigger via alias "new"
|
||||
const clockRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "new",
|
||||
args: ["每日定时同步"],
|
||||
options: { trigger: "clock", yes: true },
|
||||
raw: ["workflow", "new", "每日定时同步", "--trigger=clock", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(clockRes.exitCode).toBe(0);
|
||||
expect(createdPayload.tasks[0].type).toBe("clock");
|
||||
expect(createdPayload.tasks[0].cron).toBe("0 0 * * *");
|
||||
|
||||
// 5. JSON mode via alias "add"
|
||||
const jsonRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "add",
|
||||
args: ["API创建流程"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "add", "API创建流程", "--yes"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
expect(jsonRes.exitCode).toBe(0);
|
||||
const parsedJson = JSON.parse(jsonRes.stdout);
|
||||
expect(parsedJson.id).toBe("pipe_new_777");
|
||||
expect(parsedJson.state).toBe(0);
|
||||
|
||||
// 6. Create from template file
|
||||
const tmpFile = `/tmp/test_wf_${Date.now()}.json`;
|
||||
await (await import("fs/promises")).writeFile(
|
||||
tmpFile,
|
||||
JSON.stringify({
|
||||
label: "文件模板流程",
|
||||
state: 1,
|
||||
desc: "来自模板文件",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_webhook",
|
||||
type: "webhook",
|
||||
label: "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
const fileRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "create",
|
||||
args: [],
|
||||
options: { file: tmpFile, yes: true },
|
||||
raw: ["workflow", "create", `--file=${tmpFile}`, "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(fileRes.exitCode).toBe(0);
|
||||
expect(createdPayload.label).toBe("文件模板流程");
|
||||
expect(createdPayload.state).toBe(0);
|
||||
expect(createdPayload.desc).toBe("来自模板文件");
|
||||
expect(createdPayload.tasks[0].urlPath).toBeDefined();
|
||||
|
||||
await (await import("fs/promises")).unlink(tmpFile).catch(() => {});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createWorkflow } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleCreate(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const name = parsed.args[0] || stringOption(parsed.options, ["name", "label", "n"]);
|
||||
const trigger = stringOption(parsed.options, ["trigger", "t"]);
|
||||
const platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]);
|
||||
const file = stringOption(parsed.options, ["file", "f"]);
|
||||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"创建工作流",
|
||||
`hose-use workflow create${name ? ` --name="${name}"` : ""}${trigger ? ` --trigger=${trigger}` : ""}${platformId ? ` --platform-id=${platformId}` : ""}${file ? ` --file=${file}` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "创建工作流", name || "未命名流程", {
|
||||
name: name || "未命名流程",
|
||||
trigger: trigger || (file ? "from-file" : "none"),
|
||||
platformId: platformId || "-",
|
||||
fromFile: file || "-",
|
||||
initialState: 0,
|
||||
});
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, "");
|
||||
|
||||
const result = await createWorkflow(client, {
|
||||
label: name,
|
||||
trigger,
|
||||
platformId,
|
||||
file,
|
||||
desc,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const triggerNode = result.tasks?.[0];
|
||||
const triggerSummary = triggerNode ? `${triggerNode.label || triggerNode.name} (${triggerNode.type})` : "无首节点 (需在设计器配置)";
|
||||
const webhookUrl = triggerNode?.type === "webhook" && (triggerNode as any).urlPath
|
||||
? `https://piper.ekuaibao.com/api/webhook/${(triggerNode as any).urlPath}`
|
||||
: undefined;
|
||||
|
||||
const kvData: Record<string, string> = {
|
||||
"新工作流 ID (pipelineId)": result.id,
|
||||
"工作流名称": result.label,
|
||||
"自建应用 ID (platformId)": String((result as any).platformId || "-"),
|
||||
"首节点触发器": triggerSummary,
|
||||
};
|
||||
|
||||
if (webhookUrl) {
|
||||
kvData["Webhook 调用地址"] = webhookUrl;
|
||||
}
|
||||
|
||||
kvData["节点总数"] = String(result.tasks?.length || 0);
|
||||
kvData["版本号"] = result.version || "26.10.1";
|
||||
kvData["当前状态"] = "⚪ 草稿未发布 (停用中)";
|
||||
|
||||
const out = [
|
||||
`✨ 工作流创建成功!新工作流已生成为草稿状态 (state = 0):`,
|
||||
printKeyValue(kvData),
|
||||
"",
|
||||
"下一步操作建议:",
|
||||
` 查看明细: hose-use workflow get ${result.id}`,
|
||||
` 测试执行: hose-use workflow test ${result.id}`,
|
||||
` 发布上线: hose-use workflow publish ${result.id} --yes`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: `${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js";
|
||||
import { handleWorkflowTest } from "./test.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -84,10 +85,14 @@ export async function handleWorkflowCommand(
|
||||
case "rm":
|
||||
case "remove":
|
||||
return handleDelete(parsed, runtime);
|
||||
case "create":
|
||||
case "new":
|
||||
case "add":
|
||||
return handleCreate(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, delete\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
|
||||
hose-use workflow diff-job <jobId1> <jobId2> [--json]
|
||||
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
|
||||
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]
|
||||
```
|
||||
|
||||
@@ -73,8 +73,122 @@ export async function copyWorkflow(
|
||||
return api.copyWorkflow(client, pipelineId, cloned);
|
||||
}
|
||||
|
||||
export function createWorkflow(...args: Parameters<typeof api.createWorkflow>) {
|
||||
return api.createWorkflow(...args);
|
||||
export interface CreateWorkflowOptions {
|
||||
label?: string;
|
||||
platformId?: string;
|
||||
trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string;
|
||||
file?: string;
|
||||
workflow?: Record<string, any>;
|
||||
state?: number;
|
||||
desc?: string;
|
||||
}
|
||||
|
||||
export function buildInitialTriggerTask(triggerType: string): WorkflowTask {
|
||||
const norm = triggerType.toLowerCase().trim();
|
||||
switch (norm) {
|
||||
case "webhook":
|
||||
return {
|
||||
name: "trigger_webhook",
|
||||
type: "webhook",
|
||||
label: "Webhook触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
urlPath: crypto.randomUUID(),
|
||||
params: [],
|
||||
};
|
||||
case "clock":
|
||||
case "schedule":
|
||||
case "timer":
|
||||
return {
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
label: "定时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
cron: "0 0 * * *",
|
||||
timeZone: "Asia/Shanghai",
|
||||
};
|
||||
case "datalink":
|
||||
case "data-link":
|
||||
case "entity":
|
||||
return {
|
||||
name: "trigger_datalink_create",
|
||||
type: "ekuaibao-datalink-create-trigger",
|
||||
label: "业务对象新增时触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
case "flowform":
|
||||
case "flow":
|
||||
case "bill":
|
||||
return {
|
||||
name: "trigger_flowform",
|
||||
type: "ekuaibao-flowform-trigger",
|
||||
label: "单据审批事件触发",
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
name: `trigger_${norm.replace(/-/g, "_")}`,
|
||||
type: norm,
|
||||
label: `${norm}触发`,
|
||||
groupName: "trigger",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWorkflow(
|
||||
client: import("ky").KyInstance,
|
||||
options: CreateWorkflowOptions = {}
|
||||
): Promise<import("./types.js").WorkflowDetail> {
|
||||
let base: Record<string, any> = {};
|
||||
if (options.file) {
|
||||
const fs = await import("fs/promises");
|
||||
const raw = await fs.readFile(options.file, "utf-8");
|
||||
base = JSON.parse(raw);
|
||||
} else if (options.workflow) {
|
||||
base = JSON.parse(JSON.stringify(options.workflow));
|
||||
}
|
||||
|
||||
const payload: Record<string, any> = {
|
||||
...base,
|
||||
label: options.label || base.label || "未命名流程",
|
||||
state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承
|
||||
};
|
||||
|
||||
if (options.platformId || base.platformId) {
|
||||
payload.platformId = options.platformId || base.platformId;
|
||||
}
|
||||
if (options.desc || base.desc) {
|
||||
payload.desc = options.desc || base.desc;
|
||||
}
|
||||
|
||||
// 触发器节点初始化
|
||||
if (!payload.tasks || payload.tasks.length === 0) {
|
||||
if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") {
|
||||
payload.tasks = [buildInitialTriggerTask(options.trigger)];
|
||||
} else {
|
||||
payload.tasks = [];
|
||||
}
|
||||
} else if (payload.tasks[0]?.type === "webhook") {
|
||||
if (!payload.tasks[0].urlPath) {
|
||||
payload.tasks[0].urlPath = crypto.randomUUID();
|
||||
}
|
||||
}
|
||||
|
||||
return api.createWorkflow(client, payload);
|
||||
}
|
||||
|
||||
export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
|
||||
|
||||
Reference in new issue
Block a user