feat(platform,datalink,bill): add workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11)
This commit is contained in:
1 parent
2ec08033e0
commit
a0ec7f95a7
37 files changed
+3958
-674
No files matched your search
@@ -6,9 +6,20 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]
|
||||
```
|
||||
|
||||
## 详细文档
|
||||
|
||||
@@ -13,8 +13,102 @@ describe("Workflow static analysis", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
it("reports empty scripts, branches, and disabled workflow state", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
|
||||
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
|
||||
const wf = {
|
||||
id: "886351399301758976",
|
||||
label: "【生产】每30分钟创建采购申请单",
|
||||
state: 1,
|
||||
version: "10",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "循环每条支付计划",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建预付申请单",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
inputs: {
|
||||
specificationId: "ID01TxgE3fhD6n",
|
||||
form: {
|
||||
u_关联合同流程: "{{every_0.item.E_contract}}",
|
||||
u_我方签约主体: "{{every_0.item.E_company}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ekuaibao_datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新支付计划状态为创建成功",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
inputs: {
|
||||
dataLinkId: "{{every_0.item.id}}",
|
||||
form: {
|
||||
状态: "创建成功",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const specifications = {
|
||||
ID01TxgE3fhD6n: {
|
||||
id: "ID01TxgE3fhD6n",
|
||||
name: "预付申请单",
|
||||
form: [
|
||||
{
|
||||
id: "f1",
|
||||
name: "u_关联合同流程",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: false,
|
||||
entityId: "e23d0d5451b1ccabfd7a",
|
||||
assignmentRule: "ID01TRWvYFAulh",
|
||||
isLinkageAssignment: false,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "f2",
|
||||
name: "u_我方签约主体",
|
||||
label: "我方签约主体",
|
||||
type: "dimension",
|
||||
optional: false,
|
||||
isLinkageAssignment: true,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,400 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
+113
-5
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
@@ -9,6 +10,10 @@ import {
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowJobDetailSchema,
|
||||
WorkflowTaskExecutionSchema,
|
||||
WorkflowExecutionPageSchema,
|
||||
WorkflowExecutionLogSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
@@ -16,10 +21,35 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = (await response.json()) as { data: unknown };
|
||||
return schema.parse(json.data);
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
@@ -146,7 +176,7 @@ export async function toggleWorkflow(
|
||||
return ok(response);
|
||||
}
|
||||
|
||||
// ── 运行中的任务(Piper)──────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情(Piper)────────────────────────────────────
|
||||
|
||||
export async function listRunningJobs(
|
||||
client: KyInstance,
|
||||
@@ -159,6 +189,83 @@ export async function listRunningJobs(
|
||||
return unwrap(response, z.array(WorkflowJobSchema));
|
||||
}
|
||||
|
||||
export async function getJob(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowJobDetail> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}`);
|
||||
return unwrap(response, WorkflowJobDetailSchema);
|
||||
}
|
||||
|
||||
export async function getJobExecutionTree(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { page?: number; pageSize?: number } = {}
|
||||
): Promise<import("./types.js").WorkflowTaskExecution[]> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution`, {
|
||||
searchParams: {
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 100),
|
||||
},
|
||||
});
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([z.array(WorkflowTaskExecutionSchema), WorkflowExecutionPageSchema])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
export async function getJobFailedExecutions(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level/failed`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([WorkflowExecutionPageSchema, z.array(WorkflowTaskExecutionSchema)])
|
||||
);
|
||||
if (Array.isArray(parsed)) {
|
||||
return {
|
||||
number: 1,
|
||||
size: parsed.length,
|
||||
totalPages: 1,
|
||||
totalItems: parsed.length,
|
||||
items: parsed,
|
||||
};
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function getJobExecutionLevel(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { parentId: string; page?: number; pageSize?: number }
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level`, {
|
||||
searchParams: {
|
||||
parentId: options.parentId,
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 20),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowExecutionPageSchema);
|
||||
}
|
||||
|
||||
export async function getExecutionLogs(
|
||||
client: KyInstance,
|
||||
executionId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionLog[]> {
|
||||
const response = await client.get(`api/easo/executions/${executionId}/logs`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([
|
||||
z.array(WorkflowExecutionLogSchema),
|
||||
z.object({ items: z.array(WorkflowExecutionLogSchema).default([]) }).passthrough(),
|
||||
])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
|
||||
|
||||
export async function listDsl(
|
||||
@@ -199,3 +306,4 @@ export async function sampleWorkflowData(
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`);
|
||||
return WorkflowSampleDataSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
@@ -338,17 +338,87 @@ export const WorkflowChargeSchema = z.object({
|
||||
remaining: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 运行中的任务 ──────────────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
||||
|
||||
export const WorkflowJobSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
status: z.string().default(""),
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
startTime: z.union([z.string(), z.number()]).optional(),
|
||||
endTime: z.union([z.string(), z.number()]).optional(),
|
||||
triggerType: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowJobDetailSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
runType: z.string().default(""),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
inputs: z.any().optional(),
|
||||
outputs: z.any().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionErrorSchema = z
|
||||
.object({
|
||||
message: z.string().default(""),
|
||||
stackTrace: z.array(z.string()).nullish().transform((v) => v ?? []),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionLogSchema = z
|
||||
.object({
|
||||
id: z.union([z.string(), z.number()]).optional(),
|
||||
level: z.string().default("INFO"),
|
||||
message: z.string().default(""),
|
||||
createAt: z.union([z.string(), z.number()]).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowTaskExecutionSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
parentId: z.string().nullable().optional(),
|
||||
jobId: z.string().optional(),
|
||||
pipelineId: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
displayName: z.string().nullable().optional(),
|
||||
label: z.string().nullable().optional(),
|
||||
type: z.string().default(""),
|
||||
orderIndex: z.number().optional(),
|
||||
levelIndex: z.array(z.number()).optional(),
|
||||
status: z.string().default(""),
|
||||
executionTime: z.number().optional(),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
currentLoopPath: z.string().nullable().optional(),
|
||||
error: WorkflowExecutionErrorSchema.nullable().optional(),
|
||||
output: z.any().optional(),
|
||||
form: z.record(z.string(), z.any()).nullable().optional(),
|
||||
details: z.record(z.string(), z.any()).nullable().optional(),
|
||||
executionLogs: z.array(z.any()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionPageSchema = z
|
||||
.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(20),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z
|
||||
.array(z.union([WorkflowTaskExecutionSchema, z.array(WorkflowTaskExecutionSchema)]))
|
||||
.default([])
|
||||
.transform((arr) => arr.flat()),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDslSchema = z.object({
|
||||
@@ -423,6 +493,11 @@ export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowJobDetail = z.infer<typeof WorkflowJobDetailSchema>;
|
||||
export type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;
|
||||
export type WorkflowExecutionLog = z.infer<typeof WorkflowExecutionLogSchema>;
|
||||
export type WorkflowTaskExecution = z.infer<typeof WorkflowTaskExecutionSchema>;
|
||||
export type WorkflowExecutionPage = z.infer<typeof WorkflowExecutionPageSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
export type Staff = z.infer<typeof StaffSchema>;
|
||||
export type WebhookInfo = z.infer<typeof WebhookInfoSchema>;
|
||||
@@ -431,3 +506,4 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
|
||||
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
|
||||
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
|
||||
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
|
||||
|
||||
@@ -10,7 +10,19 @@ import {
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
updateWorkflow,
|
||||
} from "./api.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -150,4 +162,144 @@ describe("workflow draft state machine", () => {
|
||||
expect(failed.status).toBe("failed");
|
||||
expect(failed.error).toBe("网络错误");
|
||||
});
|
||||
|
||||
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
|
||||
const unauthorizedClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
|
||||
|
||||
const nullDataClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
|
||||
});
|
||||
|
||||
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options?: any) => {
|
||||
if (url === "api/easo/jobs/892809886382563347") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "892809886382563347",
|
||||
pipelineId: "886351399301758976",
|
||||
label: "每30分钟创建采购申请单",
|
||||
state: "COMPLETED",
|
||||
successTaskCount: 5,
|
||||
errorTaskCount: 1,
|
||||
hasError: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809893789696012",
|
||||
jobId: "892809886382563347",
|
||||
name: "every_0",
|
||||
label: "循环",
|
||||
type: "every",
|
||||
state: "COMPLETED",
|
||||
levelIndex: [0],
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809900000000001",
|
||||
jobId: "892809886382563347",
|
||||
parentId: "892809893789696012",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
label: "创建预付申请单",
|
||||
type: "flow-create-task",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level") {
|
||||
expect(options?.searchParams).toEqual({
|
||||
parentId: "892809893789696012",
|
||||
number: "1",
|
||||
pageSize: "20",
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
number: 1,
|
||||
size: 20,
|
||||
totalPages: 1,
|
||||
totalItems: 1,
|
||||
items: [
|
||||
[
|
||||
{
|
||||
id: "892809900000000001",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/executions/892809893789696012/logs") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
total: 1,
|
||||
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
},
|
||||
} as any;
|
||||
|
||||
const job = await getJob(client, "892809886382563347");
|
||||
expect(job.hasError).toBe(true);
|
||||
expect(job.errorTaskCount).toBe(1);
|
||||
|
||||
const tree = await getJobExecutionTree(client, "892809886382563347");
|
||||
expect(tree).toHaveLength(1);
|
||||
expect(tree[0]?.name).toBe("every_0");
|
||||
|
||||
const failed = await getJobFailedExecutions(client, "892809886382563347");
|
||||
expect(failed.items).toHaveLength(1);
|
||||
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
|
||||
|
||||
const level = await getJobExecutionLevel(client, "892809886382563347", {
|
||||
parentId: "892809893789696012",
|
||||
});
|
||||
expect(level.items).toHaveLength(1);
|
||||
|
||||
const logs = await getExecutionLogs(client, "892809893789696012");
|
||||
expect(logs[0]?.message).toBe("MVEL script executed");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user