model.ts
21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
* 流程图的纯函数:节点长什么样、怎么连线、自动排版、在某一步能引用哪些上游数据。
* 画布上的所有改动都经这里(不改原对象,返回新的定义),方便单测。
*
* 一张流程卡 = 顶层的一串步骤(spec.steps);循环节点里还有一段自己的步骤(step.body.steps)。
* 两者叫「容器」:root 或某个循环的 id。连线只在同一个容器里。
*/
import type { CondGroup, CondItem, DataSchema, FlowCond, FlowOutput, SopSpec, SopStep, StepType } from "@/lib/onto";
export const NODE_W = 248;
export const NODE_H = 76;
const GAP_X = 56;
const GAP_Y = 64;
export const PAD = 28; // 循环容器内边距
export const HEAD = 44; // 循环容器标题栏高度
export interface NodeMeta { label: string; tone: string; dot: string }
export const NODE_META: Record<StepType, NodeMeta> = {
query: { label: "查数据", tone: "text-[#2563eb] bg-[#2563eb]/10", dot: "#2563eb" },
function: { label: "调用函数", tone: "text-[#7c3aed] bg-[#7c3aed]/10", dot: "#7c3aed" },
compute: { label: "计算", tone: "text-[#0891b2] bg-[#0891b2]/10", dot: "#0891b2" },
skill: { label: "AI", tone: "text-[#db2777] bg-[#db2777]/10", dot: "#db2777" },
decision: { label: "条件", tone: "text-[#d97706] bg-[#d97706]/10", dot: "#d97706" },
foreach: { label: "循环", tone: "text-[#d97706] bg-[#d97706]/10", dot: "#d97706" },
human_task: { label: "人工任务", tone: "text-[#16a34a] bg-[#16a34a]/10", dot: "#16a34a" },
notify: { label: "通知", tone: "text-[#16a34a] bg-[#16a34a]/10", dot: "#16a34a" },
action: { label: "执行动作", tone: "text-[#dc2626] bg-[#dc2626]/10", dot: "#dc2626" },
write: { label: "写数据", tone: "text-[#dc2626] bg-[#dc2626]/10", dot: "#dc2626" },
subprocess: { label: "子流程", tone: "text-muted bg-ink/5", dot: "#64748b" },
end: { label: "结束", tone: "text-muted bg-ink/5", dot: "#64748b" },
};
export function nodeLabel(s: SopStep): string {
if (s.type === "function") {
if (s.function === "metric.query") return "查指标";
if (s.function === "function.eval") return "调用函数";
return "系统函数";
}
return NODE_META[s.type]?.label || s.type;
}
const PRODUCES: StepType[] = ["query", "function", "compute", "skill", "human_task", "action", "write", "foreach", "subprocess"];
export const produces = (t: StepType) => PRODUCES.includes(t);
// ---------------------------------------------------------------- 容器
export const ROOT = "root";
/** 容器里的步骤:root = 顶层,否则是那个循环的循环体。 */
export function stepsOf(spec: SopSpec, container: string): SopStep[] {
if (container === ROOT) return spec.steps;
const loop = findStep(spec, container);
return loop?.body?.steps || [];
}
export function startOf(spec: SopSpec, container: string): string {
if (container === ROOT) return spec.start;
return findStep(spec, container)?.body?.start || "";
}
export function allSteps(steps: SopStep[]): SopStep[] {
const out: SopStep[] = [];
for (const s of steps) {
out.push(s);
if (s.type === "foreach") out.push(...allSteps(s.body?.steps || []));
}
return out;
}
export const findStep = (spec: SopSpec, id: string) => allSteps(spec.steps).find((s) => s.id === id);
/** 这一步在哪个容器里。 */
export function containerOf(spec: SopSpec, id: string): string {
const scan = (steps: SopStep[], c: string): string | null => {
for (const s of steps) {
if (s.id === id) return c;
if (s.type === "foreach") {
const hit = scan(s.body?.steps || [], s.id);
if (hit) return hit;
}
}
return null;
};
return scan(spec.steps, ROOT) || ROOT;
}
/** 改某个容器里的步骤列表(不改原对象)。 */
function mapContainer(spec: SopSpec, container: string, fn: (steps: SopStep[], start: string) => { steps: SopStep[]; start: string }): SopSpec {
if (container === ROOT) {
const r = fn(spec.steps, spec.start);
return { ...spec, steps: r.steps, start: r.start };
}
const walk = (steps: SopStep[]): SopStep[] => steps.map((s) => {
if (s.id === container && s.type === "foreach") {
const r = fn(s.body?.steps || [], s.body?.start || "");
return { ...s, body: { steps: r.steps, start: r.start } };
}
if (s.type === "foreach") return { ...s, body: { ...s.body, steps: walk(s.body?.steps || []) } };
return s;
});
return { ...spec, steps: walk(spec.steps) };
}
export function updateStep(spec: SopSpec, id: string, patch: Partial<SopStep>): SopSpec {
const walk = (steps: SopStep[]): SopStep[] => steps.map((s) => {
if (s.id === id) return { ...s, ...patch };
if (s.type === "foreach") return { ...s, body: { ...s.body, steps: walk(s.body?.steps || []) } };
return s;
});
return { ...spec, steps: walk(spec.steps) };
}
/** 去掉所有指向 id 的连线。 */
function unlink(s: SopStep, id: string): SopStep {
const out: SopStep = { ...s };
if (out.next === id) out.next = "";
if (out.default === id) out.default = "";
if (out.on_reject === id) out.on_reject = "";
if (out.branches) out.branches = out.branches.map((b: any) => (b.next === id ? { ...b, next: "" } : b));
if (out.error?.next === id) out.error = { ...out.error, next: "" };
return out;
}
export function removeStep(spec: SopSpec, id: string): SopSpec {
const c = containerOf(spec, id);
return mapContainer(spec, c, (steps, start) => ({
steps: steps.filter((s) => s.id !== id).map((s) => unlink(s, id)),
start: start === id ? "" : start,
}));
}
function usedIds(spec: SopSpec): Set<string> {
return new Set(allSteps(spec.steps).map((s) => s.id));
}
const ID_BASE: Record<StepType, string> = {
query: "q", function: "fn", compute: "calc", skill: "ai", decision: "if", foreach: "each", human_task: "task",
notify: "notice", action: "act", write: "w", subprocess: "sub", end: "end",
};
export function newId(spec: SopSpec, type: StepType): string {
const used = usedIds(spec);
let i = 1;
while (used.has(`${ID_BASE[type]}${i}`)) i += 1;
return `${ID_BASE[type]}${i}`;
}
/** 新建一个节点(带默认值)。 */
export function newStep(spec: SopSpec, type: StepType, preset = "", title = ""): SopStep {
const id = newId(spec, type);
const base: SopStep = { id, type, title: title || (type === "function" && preset === "metric.query" ? "查指标" : NODE_META[type].label), next: "" };
if (produces(type)) base.output = id;
switch (type) {
case "query": return { ...base, object_type: "", mode: "list", where: null, fields: [], include: [], sort: [], limit: 50 };
case "function": return { ...base, function: preset, args: preset === "function.eval" ? { name: "", args: {} } : {}, filter: null };
case "compute": return { ...base, assign: [{ name: "x", label: "", type: "number", expr: "" }] };
case "skill": return { ...base, instruction: "", inputs: {}, outputs: [], confirm_below: 0, confirm_role: "" };
case "decision": return { ...base, branches: [{ label: "情况 1", cond: null, next: "" }], default: "" };
case "foreach": {
const endId = `${id}_end`;
return { ...base, items: "", filter: null, limit: 20, collect: "", on_item_error: "continue",
body: { start: endId, steps: [{ id: endId, type: "end", title: "本条处理完", outcome: "", ui: { x: 0, y: 0 } }] } };
}
case "human_task": return { ...base, role: "", assignee: "", instructions: "", form: [], checklist: [], sla_hours: 0 };
case "notify": return { ...base, role: "", assignee: "", subject: "", body: "" };
case "action": return { ...base, action: "", params: {}, object_key: "", on_reject: "" };
case "write": return { ...base, ops: [], approval: { mode: "manual", approver_roles: [], auto_when: "" }, on_reject: "" };
case "subprocess": return { ...base, sop: "", params: {} };
default: return { id, type: "end", title: title || "结束", outcome: "", outputs: [] };
}
}
export function addStep(spec: SopSpec, container: string, step: SopStep): SopSpec {
return mapContainer(spec, container, (steps, start) => ({ steps: [...steps, step], start: start || step.id }));
}
// ---------------------------------------------------------------- 连线
/** 一个节点的出口:next / 条件的每个分支 / 否则 / 被驳回 / 失败。 */
export interface Port { id: string; label: string; tone?: "warn" | "bad" | "muted" }
export function portsOf(s: SopStep): Port[] {
if (s.type === "end") return [];
if (s.type === "decision") {
return [...(s.branches || []).map((b: any, i: number) => ({ id: `b${i}`, label: b.label || `情况 ${i + 1}`, tone: "warn" as const })),
{ id: "default", label: "否则", tone: "muted" as const }];
}
const out: Port[] = [{ id: "next", label: "" }];
// 动作 / 写数据被驳回:不连线就是流程到此结束;连了就走那一步
if (s.type === "action" || s.type === "write") out.push({ id: "reject", label: "被驳回", tone: "bad" });
if (s.error?.mode === "branch") out.push({ id: "error", label: "出错", tone: "bad" });
return out;
}
/** 某个出口现在连到哪。 */
export function targetOf(s: SopStep, port: string): string {
if (port === "next") return s.next || "";
if (port === "default") return s.default || "";
if (port === "reject") return s.on_reject || "";
if (port === "error") return s.error?.next || "";
if (port.startsWith("b")) return s.branches?.[Number(port.slice(1))]?.next || "";
return "";
}
/** 把 source 的 port 连到 target(target 为空就是断开)。source 为 "__start" 表示容器的开始。 */
export function connect(spec: SopSpec, container: string, source: string, port: string, target: string): SopSpec {
if (source === "__start") return mapContainer(spec, container, (steps) => ({ steps, start: target }));
const s = findStep(spec, source);
if (!s) return spec;
if (port === "next") return updateStep(spec, source, { next: target });
if (port === "default") return updateStep(spec, source, { default: target });
if (port === "reject") return updateStep(spec, source, { on_reject: target });
if (port === "error") return updateStep(spec, source, { error: { ...(s.error || { mode: "branch" }), mode: "branch", next: target } });
if (port.startsWith("b")) {
const i = Number(port.slice(1));
return updateStep(spec, source, { branches: (s.branches || []).map((b: any, j: number) => (j === i ? { ...b, next: target } : b)) });
}
return spec;
}
export interface FlowEdge { source: string; port: string; target: string; label: string; tone?: string }
export function edgesOf(spec: SopSpec, container: string): FlowEdge[] {
const steps = stepsOf(spec, container);
const ids = new Set(steps.map((s) => s.id));
const out: FlowEdge[] = [];
const st = startOf(spec, container);
if (st && ids.has(st)) out.push({ source: "__start", port: "next", target: st, label: "" });
for (const s of steps) {
for (const p of portsOf(s)) {
const t = targetOf(s, p.id);
if (t && ids.has(t)) out.push({ source: s.id, port: p.id, target: t, label: p.label, tone: p.tone });
}
}
return out;
}
function successors(s: SopStep): string[] {
return portsOf(s).map((p) => targetOf(s, p.id)).filter(Boolean);
}
// ---------------------------------------------------------------- 排版
export interface Size { w: number; h: number }
/** 一个节点占多大:普通节点固定大小;循环是容器,按里面的步骤排出来的大小。 */
export function sizeOf(spec: SopSpec, s: SopStep): Size {
if (s.type !== "foreach") return { w: NODE_W, h: s.type === "decision" ? NODE_H + 10 : NODE_H };
const inner = s.body?.steps || [];
let maxX = NODE_W;
let maxY = NODE_H;
for (const b of inner) {
const sz = sizeOf(spec, b);
maxX = Math.max(maxX, (b.ui?.x ?? 0) + sz.w);
maxY = Math.max(maxY, (b.ui?.y ?? 0) + sz.h);
}
// 循环体的「开始」小节点在最上面
return { w: maxX + PAD * 2, h: maxY + HEAD + PAD + 36 };
}
/**
* 自动排版(从上往下):按「离开始最远的路径」分层,同一层从左往右摆;分支多时自然展开成几列。
* 返回新的定义(每个节点的 ui 位置都重算,循环体递归排)。
*/
export function autoLayout(spec: SopSpec, container = ROOT): SopSpec {
let out = spec;
for (const s of stepsOf(out, container)) if (s.type === "foreach") out = autoLayout(out, s.id);
const steps = stepsOf(out, container);
const byId = new Map(steps.map((s) => [s.id, s]));
const start = startOf(out, container);
const layer = new Map<string, number>();
// 拓扑序上的最长路径分层(流程是无环图;万一有环,访问过的不再走)
const order: string[] = [];
const seen = new Set<string>();
const visit = (id: string) => {
if (seen.has(id) || !byId.has(id)) return;
seen.add(id);
for (const n of successors(byId.get(id)!)) visit(n);
order.unshift(id);
};
if (start) visit(start);
for (const s of steps) visit(s.id);
for (const id of order) if (!layer.has(id)) layer.set(id, 0);
layer.set(start, 0);
for (const id of order) {
const s = byId.get(id)!;
for (const n of successors(s)) {
if (byId.has(n) && order.indexOf(n) > order.indexOf(id)) layer.set(n, Math.max(layer.get(n) ?? 0, (layer.get(id) ?? 0) + 1));
}
}
const rows: string[][] = [];
for (const id of order) {
const l = layer.get(id) ?? 0;
(rows[l] ||= []).push(id);
}
const pos = new Map<string, { x: number; y: number }>();
let y = container === ROOT ? 110 : 44;
for (const row of rows) {
if (!row) continue;
const sizes = row.map((id) => sizeOf(out, byId.get(id)!));
const total = sizes.reduce((a, b) => a + b.w, 0) + GAP_X * (row.length - 1);
let x = -total / 2;
row.forEach((id, i) => {
pos.set(id, { x: Math.round(x), y });
x += sizes[i].w + GAP_X;
});
y += Math.max(...sizes.map((z) => z.h)) + GAP_Y;
}
// 容器里坐标从 0 开始
const minX = Math.min(0, ...[...pos.values()].map((p) => p.x));
const shift = container === ROOT ? -NODE_W / 2 : -minX;
const placed = (s: SopStep): SopStep => {
const p = pos.get(s.id);
return p ? { ...s, ui: { x: p.x + shift + (container === ROOT ? NODE_W / 2 : 0), y: p.y } } : s;
};
out = mapContainer(out, container, (st, sta) => ({ steps: st.map(placed), start: sta }));
if (container === ROOT) out = { ...out, ui: { start: { x: 0, y: 0 } } };
return out;
}
/** 有没有节点还没摆位置(AI 起草、配方生成的流程)。 */
export const needsLayout = (spec: SopSpec) => allSteps(spec.steps).some((s) => !s.ui);
// ---------------------------------------------------------------- 能引用哪些数据
function preds(steps: SopStep[]): Map<string, string[]> {
const m = new Map<string, string[]>();
for (const s of steps) for (const n of successors(s)) m.set(n, [...(m.get(n) || []), s.id]);
return m;
}
/** 在 stepId 这一步能引用的数据:参数、上游步骤(沿连线往回能走到的)的结果,在循环体里还有当前这一条 / 外层的上游。 */
export function visibleOutputs(spec: SopSpec, stepId: string, outputs: FlowOutput[]): FlowOutput[] {
const ids = new Set<string>();
const loops: string[] = [];
let cur = stepId;
let container = containerOf(spec, cur);
for (;;) {
const p = preds(stepsOf(spec, container));
const stack = [...(p.get(cur) || [])];
while (stack.length) {
const n = stack.pop()!;
if (ids.has(n)) continue;
ids.add(n);
stack.push(...(p.get(n) || []));
}
if (container === ROOT) break;
loops.push(container);
cur = container;
container = containerOf(spec, container);
}
return outputs.filter((o) => o.kind === "param" || (o.kind === "item" ? loops.includes(o.scope) : ids.has(o.id)));
}
// ---------------------------------------------------------------- 引用的显示
const STEP_RE = /\.|(\[\d+\])/;
export function pathParts(path: string): (string | number)[] {
return path.split(STEP_RE).filter(Boolean).map((t) => (t.startsWith("[") ? Number(t.slice(1, -1)) : t));
}
/** 沿路径走进结构。 */
export function resolveSchema(schema: DataSchema | undefined, parts: (string | number)[]): DataSchema | undefined {
let cur = schema;
for (const p of parts) {
if (!cur) return undefined;
if (cur.type === "any") return cur;
if (typeof p === "number") { cur = cur.items; continue; }
if (cur.type === "array") { cur = cur.items?.fields?.find((f) => f.name === p); continue; }
cur = cur.fields?.find((f) => f.name === p);
}
return cur;
}
/** `$var.path` → 给人看的名字(「查工单 · 用料行 · 第 1 条 · 数量」)。认不出来的原样返回。 */
export function refLabel(ref: string, outputs: FlowOutput[]): string {
const raw = String(ref || "").replace(/^\$/, "");
const parts = pathParts(raw);
const head = String(parts[0] ?? "");
if (head === "ops") return `本次写入 · ${parts.slice(1).join(" · ")}`;
if (head === "row") return `这一行 · ${parts.slice(1).join(" · ")}`;
const o = outputs.find((x) => x.var === head);
if (!o) return ref;
const names: string[] = [o.title];
let cur: DataSchema | undefined = o.schema;
for (const p of parts.slice(1)) {
if (typeof p === "number") { names.push(`第 ${p + 1} 条`); cur = cur?.items; continue; }
const f = cur?.type === "array" ? cur.items?.fields?.find((x) => x.name === p) : cur?.fields?.find((x) => x.name === p);
names.push(f?.label || String(p));
cur = f;
}
return names.join(" · ");
}
export function refType(ref: string, outputs: FlowOutput[]): string {
const parts = pathParts(String(ref || "").replace(/^\$/, ""));
const o = outputs.find((x) => x.var === parts[0]);
return resolveSchema(o?.schema, parts.slice(1))?.type || "any";
}
const REF = /\$[A-Za-z_一-鿿][\w一-鿿]*(?:\[\d+\]|\.[\w一-鿿]+)*/g;
export const refsIn = (text: string): string[] => String(text || "").match(REF) || [];
export const humanize = (text: string, outputs: FlowOutput[]) =>
String(text || "").replace(REF, (m) => `「${refLabel(m, outputs)}」`);
export const OP_LABEL: Record<string, string> = {
eq: "等于", ne: "不等于", gt: "大于", ge: "大于等于", lt: "小于", le: "小于等于", contains: "包含", not_contains: "不包含",
startswith: "开头是", in: "属于", not_in: "不属于", empty: "为空", not_empty: "不为空", len_gt: "条数大于", len_eq: "条数等于",
is_true: "为是", is_false: "为否",
};
export const UNARY = ["empty", "not_empty", "is_true", "is_false"];
export const isGroup = (x: CondItem | CondGroup): x is CondGroup => (x as CondGroup).items !== undefined;
export function condText(cond: FlowCond | undefined, label: (r: string) => string = (r) => r): string {
if (!cond) return "";
if ("expr" in cond) return cond.expr;
const parts = cond.items.map((i) => {
if (isGroup(i)) { const t = condText(i, label); return t ? `(${t})` : ""; }
if (!i.left) return "";
const left = label(i.left);
if (UNARY.includes(i.op)) return `${left}${OP_LABEL[i.op]}`;
const r = i.right;
const right = typeof r === "string" && r.startsWith("$") ? label(r) : r === true ? "是" : r === false ? "否" : String(r ?? "");
return `${left} ${OP_LABEL[i.op] || i.op} ${right}`;
}).filter(Boolean);
return parts.join(cond.mode === "any" ? " 或 " : " 且 ");
}
/** 把一步说成一句业务话,显示在节点卡片上。 */
export function summarize(s: SopStep, outputs: FlowOutput[]): string {
const lab = (r: string) => refLabel(r, outputs);
const who = s.assignee || s.role;
switch (s.type) {
case "query": {
if (!s.object_type) return "还没选查哪类对象";
const inc = (s.include || []).map((i: any) => i.as || i.link).join("、");
return `${s.mode === "one" ? "查一个" : "查一批"}${s.object_type}${s.where ? `,${condText(s.where, lab)}` : ""}${inc ? `,带出 ${inc}` : ""}`;
}
case "function":
if (s.function === "metric.query") return s.args?.metric ? `取 ${s.args.metric}${s.args.dimensions?.length ? `,按 ${s.args.dimensions.join("、")}` : ""}` : "还没选指标";
if (s.function === "function.eval") return s.args?.name ? `调用 ${s.args.name}` : "还没选函数";
return s.function ? `调用 ${s.function}` : "还没选函数";
case "compute": return (s.assign || []).filter((a: any) => a.name).map((a: any) => a.label || a.name).join("、") || "还没写要算什么";
case "skill": return s.instruction ? String(s.instruction).slice(0, 40) : s.skill ? `用「${s.skill}」分析` : "还没写要 AI 判断什么";
case "decision": return `${(s.branches || []).length} 种情况 + 否则`;
case "foreach": return s.items ? `对 ${lab(s.items)} 的每一条(最多 ${s.limit} 条)` : "还没选对哪份数据循环";
case "human_task": return who ? `交给 ${who}${s.form?.length ? `,填 ${s.form.map((f: any) => f.label).join("、")}` : ""}` : "还没选交给谁";
case "notify": return who ? `通知 ${who}:${humanize(s.subject || "", outputs) || "(还没写标题)"}` : "还没选通知谁";
case "action": return s.action ? `执行「${s.action}」` : "还没选动作";
case "write": {
const ops = (s.ops || []) as any[];
if (!ops.length) return "还没有要写的内容";
const W: Record<string, string> = { create: "新建", update: "修改", create_rows: "按行新建" };
return ops.map((o) => `${W[o.op] || o.op}${o.object_type || "?"}`).join("、");
}
case "subprocess": return s.sop ? "调用另一张流程卡" : "还没选流程卡";
default: return s.outcome || ((s.outputs || []).length ? `输出 ${(s.outputs || []).map((o: any) => o.label || o.name).join("、")}` : "流程到此结束");
}
}
/** 定义的可比较指纹:判断「有没有未保存的修改」。 */
export const fingerprint = (spec: SopSpec) => JSON.stringify(spec);