229 lines
11 KiB
TypeScript
229 lines
11 KiB
TypeScript
import type { WorkflowTaskExecution } from "../types.js";
|
|
import { indexExecutionContexts } from "../execution/context.js";
|
|
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
|
|
|
|
export const OP_MAP: Record<string, string> = {
|
|
eq: "等于",
|
|
neq: "不等于",
|
|
include: "包含",
|
|
not_include: "不包含",
|
|
in: "在列表中",
|
|
not_in: "不在列表中",
|
|
gt: "大于",
|
|
gte: "大于等于",
|
|
lt: "小于",
|
|
lte: "小于等于",
|
|
empty: "为空",
|
|
not_empty: "不为空",
|
|
};
|
|
|
|
/**
|
|
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
|
|
*/
|
|
export function parseChooseTag(tag: string): {
|
|
upstreamNode: string;
|
|
upstreamProp: string;
|
|
label: string;
|
|
} | null {
|
|
if (typeof tag !== "string") return null;
|
|
const match = tag.match(/@\{choose\('(.*)'\)\}/);
|
|
if (!match) return null;
|
|
try {
|
|
const parsed = JSON.parse(match[1]);
|
|
const upstreamNode = parsed.key || "";
|
|
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
|
|
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
|
|
return { upstreamNode, upstreamProp, label };
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 尝试从 @{value('...')} 中提取人类可读值
|
|
*/
|
|
export function parseValueTag(val: any): any {
|
|
if (Array.isArray(val)) {
|
|
return val.map((v) => parseValueTag(v));
|
|
}
|
|
if (typeof val === "string") {
|
|
const match = val.match(/@\{value\('(.*)'\)\}/);
|
|
if (match) {
|
|
try {
|
|
const parsed = JSON.parse(match[1]);
|
|
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
|
|
} catch {
|
|
return val;
|
|
}
|
|
}
|
|
}
|
|
return val;
|
|
}
|
|
|
|
/**
|
|
* 比较两个值是否匹配
|
|
*/
|
|
export function cleanRuleValue(value: any): any {
|
|
if (Array.isArray(value)) return value.map(cleanRuleValue);
|
|
if (typeof value === "string") {
|
|
const match = value.match(/@\{value\('(.*)'\)\}/);
|
|
if (match) {
|
|
try { const parsed = JSON.parse(match[1]); return parsed.key ?? parsed.value; }
|
|
catch { return value; }
|
|
}
|
|
}
|
|
if (value && typeof value === "object" && "id" in value) return value.id;
|
|
return value;
|
|
}
|
|
|
|
export function evaluateRule(actual: any, expected: any, compare: string): boolean | null {
|
|
const empty = actual === undefined || actual === null || actual === "" || (Array.isArray(actual) && actual.length === 0);
|
|
if (compare === "empty") return empty;
|
|
if (compare === "not_empty") return !empty;
|
|
if (!Object.hasOwn(OP_MAP, compare)) return null;
|
|
if (actual === undefined) return false;
|
|
actual = cleanRuleValue(actual);
|
|
expected = cleanRuleValue(expected);
|
|
if (actual === null) return compare === "eq" ? expected === null : compare === "neq" ? expected !== null : false;
|
|
if ([actual, expected].some(value => value !== null && typeof value === "object" && !Array.isArray(value))) return null;
|
|
const equal = (a: any, b: any): boolean => {
|
|
if (Array.isArray(a) && !Array.isArray(b)) return a.length === 1 && equal(a[0], b);
|
|
if (!Array.isArray(a) && Array.isArray(b)) return b.length === 1 && equal(a, b[0]);
|
|
return typeof a === "object" || typeof b === "object" ? JSON.stringify(a) === JSON.stringify(b) : String(a) === String(b);
|
|
};
|
|
switch (compare) {
|
|
case "eq": return equal(actual, expected);
|
|
case "neq": return !equal(actual, expected);
|
|
case "in":
|
|
case "not_in": {
|
|
if (!Array.isArray(expected) || Array.isArray(actual)) return null;
|
|
const matches = expected.some(item => equal(actual, item));
|
|
return compare === "in" ? matches : !matches;
|
|
}
|
|
case "include":
|
|
case "not_include": {
|
|
if (!Array.isArray(actual) && typeof actual !== "string") return null;
|
|
const values = Array.isArray(expected) ? expected : [expected];
|
|
const matches = Array.isArray(actual)
|
|
? values.every(value => actual.some(item => equal(item, value)))
|
|
: typeof actual === "string" && values.every(value => actual.includes(String(value)));
|
|
return compare === "include" ? matches : !matches;
|
|
}
|
|
default: {
|
|
const numeric = (value: unknown) => typeof value === "number" || (typeof value === "string" && value.trim() !== "") ? Number(value) : NaN;
|
|
const a = numeric(actual), b = numeric(expected);
|
|
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
|
return compare === "gt" ? a > b : compare === "gte" ? a >= b : compare === "lt" ? a < b : a <= b;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
|
|
*/
|
|
export function explainConditionBranches(
|
|
tree: WorkflowTaskExecution[]
|
|
): ConditionBranchExplanation[] {
|
|
const contexts = indexExecutionContexts(tree);
|
|
const explanations: ConditionBranchExplanation[] = [];
|
|
|
|
for (const [position, context] of contexts.entries()) {
|
|
const node = context.node;
|
|
const rawNode = node as Record<string, any>;
|
|
if (rawNode.type !== "condition") continue;
|
|
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
|
|
if (childTasks.length === 0) continue;
|
|
|
|
// 检查子任务是否执行过
|
|
const childNames = childTasks.map((task: any) => task.name || task.id).filter(Boolean);
|
|
const childContexts = contexts.filter((child, index) => {
|
|
if (child.loopPath !== context.loopPath || !childNames.includes(child.node.name || child.node.id)) return false;
|
|
if (child.node.parentId) return child.node.parentId === node.id;
|
|
const nestedScope = [...context.scope, JSON.stringify([node.name || node.type || "unnamed", context.loopPath])];
|
|
return JSON.stringify(child.scope) === JSON.stringify(nestedScope) ||
|
|
(index > position && JSON.stringify(child.scope) === JSON.stringify(context.scope));
|
|
});
|
|
const anyExecuted = childContexts.some(child => child.node.status && !["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase()));
|
|
if (anyExecuted) {
|
|
// 子分支正常执行,无需诊断跳过
|
|
continue;
|
|
}
|
|
const skippedTaskNames = childTasks.map((task: any) => `${task.name || task.id} (${task.label || task.displayName || task.type})`);
|
|
const rules: ConditionRuleExplanation[] = [];
|
|
|
|
// 解析 combineFilters;保留 AND/OR 和嵌套分组语义。
|
|
const explainFilter = (filter: any): boolean | null => {
|
|
if (!filter || typeof filter !== "object") return null;
|
|
if (Array.isArray(filter.filters)) {
|
|
const values = filter.filters.map(explainFilter) as Array<boolean | null>;
|
|
if (!values.length) return null;
|
|
const condition = String(filter.condition ?? "AND").toUpperCase();
|
|
if (condition === "AND") return values.includes(false) ? false : values.includes(null) ? null : true;
|
|
if (condition === "OR") return values.includes(true) ? true : values.includes(null) ? null : false;
|
|
return null;
|
|
}
|
|
const chooseInfo = parseChooseTag(filter.key);
|
|
const rawExpected = filter.value;
|
|
const parsedExpected = parseValueTag(rawExpected);
|
|
const op = filter.compare || "eq";
|
|
const upstreamNode = chooseInfo?.upstreamNode || "";
|
|
const upstreamProp = chooseInfo?.upstreamProp || (typeof filter.key === "string" ? filter.key : "");
|
|
const leftLabel = chooseInfo?.label || String(filter.key);
|
|
|
|
// 从上游节点提取真实 outputs;只使用同一次循环或祖先作用域中的执行实例。
|
|
const candidates = contexts.slice(0, position).filter(candidate =>
|
|
(candidate.node.name === upstreamNode || candidate.node.id === upstreamNode) &&
|
|
(!candidate.loopPath || candidate.loopPath === context.loopPath) &&
|
|
candidate.scope.every((part, i) => context.scope[i] === part)
|
|
);
|
|
candidates.sort((a, b) => a.scope.length - b.scope.length);
|
|
const upstreamExecution = candidates.at(-1)?.node;
|
|
const upstreamOutputs = upstreamExecution?.output ?? upstreamExecution?.outputs;
|
|
let actualVal: any = upstreamOutputs;
|
|
let isMissing = false;
|
|
for (const part of upstreamProp.split(".")) {
|
|
if (actualVal && typeof actualVal === "object" && Object.hasOwn(actualVal, part)) actualVal = actualVal[part];
|
|
else { actualVal = undefined; isMissing = Boolean(upstreamExecution); break; }
|
|
}
|
|
// 提取纯净 ID 比对
|
|
const cleanExpected = cleanRuleValue(rawExpected);
|
|
const matched = upstreamExecution ? evaluateRule(actualVal, cleanExpected, op) : null;
|
|
let detail: string;
|
|
if (isMissing) {
|
|
const availableKeys = upstreamOutputs && typeof upstreamOutputs === "object" ? Object.keys(upstreamOutputs).join(", ") : "无出参";
|
|
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
|
|
} else if (matched === null) {
|
|
detail = `无法确定:缺少上游执行证据,或操作符/值类型不支持 (${op})`;
|
|
} else {
|
|
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
|
|
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
|
|
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
|
|
}
|
|
rules.push({ leftLabel, upstreamNode, upstreamProp, operator: op, operatorLabel: OP_MAP[op] || op, expectedValue: parsedExpected, actualValue: actualVal, isMissing, matched, detail });
|
|
return matched;
|
|
};
|
|
const calculated = explainFilter(rawNode.combineFilters);
|
|
const evaluation = node.status.toUpperCase() === "COMPLETED" ? calculated : null;
|
|
let summary = evaluation === false
|
|
? `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`
|
|
: evaluation === true
|
|
? "条件比对为 True,但未见子任务执行记录;请核对执行树是否完整"
|
|
: "执行证据不足或条件尚未完成,无法确定子任务是否被跳过";
|
|
const missingRule = rules.find(rule => rule.isMissing);
|
|
if (evaluation === false && missingRule) {
|
|
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
|
|
}
|
|
explanations.push({
|
|
conditionNodeId: node.id,
|
|
conditionNodeName: node.name || "-",
|
|
conditionNodeLabel: node.label || rawNode.displayName || "条件节点",
|
|
hasSkippedTasks: evaluation === false || childContexts.some(child => ["SKIP", "SKIPPED"].includes(child.node.status.toUpperCase())),
|
|
evaluation,
|
|
skippedTaskNames,
|
|
rules,
|
|
summary,
|
|
});
|
|
}
|
|
return explanations;
|
|
}
|