import { describeResponsible, type ProcessModel, type ProcessRow } from "./model.js"; import type { Schedule } from "./schedule.js"; import { esc, svgDoc, tooltip, truncate, wrap } from "./svg.js"; export interface ArisOptions { /** показывать объекты данных и информационные потоки */ data?: boolean; /** после каждого чек-поинта рисовать событие (шестиугольник) */ events?: boolean; stages?: string[] | null; } // Геометрия const LABEL_W = 170; const COL_W = 215; const FN_W = 176; const FN_H = 76; const EV_W = 150; const EV_H = 52; const SLOT = 92; // шаг функций по вертикали внутри дорожки const DATA_W = 118; const DATA_H = 30; const DATA_SLOT = 38; const PAD = 14; const TOP = 70; // Цвета ARIS: функция - зелёная, событие - розовое, оргединица - жёлтая, прикладная система - синяя, информационный объект - голубой const C = { fn: { fill: "#d6efb8", stroke: "#5a9a2e" }, fnCp: { fill: "#b9e08a", stroke: "#3d7a1a" }, ev: { fill: "#f8c6d4", stroke: "#c04a6a" }, org: { fill: "#fff0a3", stroke: "#b89b00" }, sys: { fill: "#a9cdf2", stroke: "#2f6db0" }, data: { fill: "#c8eef5", stroke: "#2b8aa0" }, }; type NodeKind = "F" | "E" | "D"; interface Node { key: string; kind: NodeKind; row?: ProcessRow; dataId?: string; lane: string; level: number; // для данных - полуцелое slot: number; x: number; y: number; w: number; h: number; } interface Edge { from: string; to: string; kind: "flow" | "data" } const isCp = (id: string) => /^CP-/.test(id); export function renderAris(model: ProcessModel, schedule: Schedule, opts: ArisOptions = {}): string { const showData = opts.data === true; const showEvents = opts.events !== false; const rows = model.rows.filter((r) => !opts.stages?.length || opts.stages.includes(r.stage ?? "(без этапа)")); const inSet = new Set(rows.map((r) => r.id)); const byId = new Map(rows.map((r) => [r.id, r])); const roleName = new Map(model.roles.map((r) => [r.id, r.person ?? r.id])); const sysName = new Map(model.systems.map((s) => [s.id, s.name ?? s.id])); const dataInfo = new Map(model.data.map((d) => [d.id, d])); // Граф управляющего потока: функция -> (событие) -> следующая функция const outKey = (id: string) => (showEvents && isCp(id) ? `E:${id}` : `F:${id}`); const edges: Edge[] = []; const preds = new Map(); const addPred = (to: string, from: string) => preds.set(to, [...(preds.get(to) ?? []), from]); for (const r of rows) { if (showEvents && isCp(r.id)) { edges.push({ from: `F:${r.id}`, to: `E:${r.id}`, kind: "flow" }); addPred(`E:${r.id}`, `F:${r.id}`); } for (const dep of r.dependsOn.filter((d) => inSet.has(d))) { edges.push({ from: outKey(dep), to: `F:${r.id}`, kind: "flow" }); addPred(`F:${r.id}`, outKey(dep)); } } // Уровень = самый длинный путь до узла const level = new Map(); const visiting = new Set(); const levelOf = (key: string): number => { const known = level.get(key); if (known !== undefined) return known; if (visiting.has(key)) return 0; // цикл: разрываем visiting.add(key); const l = Math.max(-1, ...(preds.get(key) ?? []).map(levelOf)) + 1; visiting.delete(key); level.set(key, l); return l; }; const nodes: Node[] = []; const startOf = (r: ProcessRow) => schedule.timings.get(r.id)?.start ?? 0; const ordered = [...rows].sort((a, b) => startOf(a) - startOf(b) || a.id.localeCompare(b.id, "ru", { numeric: true })); const laneOrder: string[] = []; const laneOf = (r: ProcessRow) => r.role ?? "_none"; for (const r of ordered) if (!laneOrder.includes(laneOf(r))) laneOrder.push(laneOf(r)); for (const r of ordered) { nodes.push({ key: `F:${r.id}`, kind: "F", row: r, lane: laneOf(r), level: levelOf(`F:${r.id}`), slot: 0, x: 0, y: 0, w: FN_W, h: FN_H }); if (showEvents && isCp(r.id)) nodes.push({ key: `E:${r.id}`, kind: "E", row: r, lane: laneOf(r), level: levelOf(`E:${r.id}`), slot: 0, x: 0, y: 0, w: EV_W, h: EV_H }); } // Объекты данных: рядом с создателем (половина колонки правее), у входов без создателя - левее первого потребителя if (showData) { const producer = new Map(); for (const r of ordered) for (const d of r.dataOut) if (!producer.has(d)) producer.set(d, r); const consumers = new Map(); for (const r of ordered) for (const d of r.dataIn) consumers.set(d, [...(consumers.get(d) ?? []), r]); const ids = new Set([...producer.keys(), ...consumers.keys()]); for (const id of ids) { const p = producer.get(id); const first = consumers.get(id)?.[0]; const anchor = p ?? first; if (!anchor) continue; const lv = p ? levelOf(`F:${p.id}`) + 0.5 : levelOf(`F:${anchor.id}`) - 0.5; nodes.push({ key: `D:${id}`, kind: "D", dataId: id, lane: laneOf(anchor), level: lv, slot: 0, x: 0, y: 0, w: DATA_W, h: DATA_H }); if (p) edges.push({ from: `F:${p.id}`, to: `D:${id}`, kind: "data" }); for (const c of consumers.get(id) ?? []) edges.push({ from: `D:${id}`, to: `F:${c.id}`, kind: "data" }); } } // Размещение: слоты внутри (дорожка, уровень) const used = new Map(); const stackF = new Map(); // lane -> максимум слотов функций const stackD = new Map(); // lane -> максимум слотов данных for (const n of nodes) { const k = `${n.kind === "D" ? "D" : "F"}|${n.lane}|${n.level}`; n.slot = used.get(k) ?? 0; used.set(k, n.slot + 1); const m = n.kind === "D" ? stackD : stackF; m.set(n.lane, Math.max(m.get(n.lane) ?? 0, n.slot + 1)); } const laneY = new Map(); let cursor = TOP; for (const lane of laneOrder) { const fs = Math.max(1, stackF.get(lane) ?? 1); const ds = showData ? stackD.get(lane) ?? 0 : 0; const h = PAD * 2 + fs * SLOT + (ds ? ds * DATA_SLOT + 6 : 0); laneY.set(lane, { y: cursor, h }); cursor += h; } const minLevel = Math.min(0, ...nodes.map((n) => n.level)); const maxLevel = Math.max(0, ...nodes.map((n) => n.level)); for (const n of nodes) { const ly = laneY.get(n.lane)!; const fs = Math.max(1, stackF.get(n.lane) ?? 1); n.x = LABEL_W + 20 + (n.level - minLevel) * COL_W; if (n.kind === "D") n.y = ly.y + PAD + fs * SLOT + 6 + n.slot * DATA_SLOT; else n.y = ly.y + PAD + n.slot * SLOT + (SLOT - n.h) / 2 - 4; } const width = LABEL_W + 40 + (maxLevel - minLevel + 1) * COL_W + 20; const height = cursor + 70; const byKey = new Map(nodes.map((n) => [n.key, n])); const out: string[] = []; out.push(`ARIS eEPC процесса (${esc(model.set)}): дорожки - роли, функции - шаги, события - чек-поинты`); out.push(legend(showData, showEvents)); // Дорожки laneOrder.forEach((lane, i) => { const ly = laneY.get(lane)!; out.push(``); const label = lane === "_none" ? "Не назначено" : roleName.get(lane) ?? lane; const roleId = lane === "_none" ? "" : lane; const cy = ly.y + ly.h / 2; out.push(`${tooltip([`Роль: ${roleId || "не назначена"}`, model.roles.find((r) => r.id === lane)?.comment])}`); const lines = wrap(label, 18, 2); lines.forEach((t, j) => out.push(`${esc(t)}`)); out.push(""); }); // Рёбра под узлами const anchorRight = (n: Node) => ({ x: n.x + n.w, y: n.y + n.h / 2 }); const anchorLeft = (n: Node) => ({ x: n.x, y: n.y + n.h / 2 }); const edgeSvg = edges.flatMap((e) => { const a = byKey.get(e.from); const b = byKey.get(e.to); if (!a || !b) return []; const p1 = anchorRight(a); const p2 = anchorLeft(b); const xm = Math.max(p1.x + 8, Math.min(p2.x - 8, (p1.x + p2.x) / 2)); const style = e.kind === "data" ? `stroke="#2b8aa0" stroke-dasharray="4 3" stroke-width="1"` : `stroke="#555" stroke-width="1.3"`; const marker = e.kind === "data" ? "arrD" : "arrF"; return [``]; }); out.push(`${edgeSvg.join("")}`); // Узлы for (const n of nodes) { if (n.kind === "F" && n.row) out.push(fnSvg(n, n.row, roleName, sysName, model)); else if (n.kind === "E" && n.row) out.push(evSvg(n, n.row, schedule)); else if (n.kind === "D" && n.dataId) out.push(dataSvg(n, dataInfo.get(n.dataId), n.dataId, roleName)); } void byId; const defs = `` + ``; return svgDoc(width, height, defs, out.join("\n")); } function fnSvg(n: Node, r: ProcessRow, roleName: Map, sysName: Map, model: ProcessModel): string { const cp = isCp(r.id); const c = cp ? C.fnCp : C.fn; const title = wrap(r.actionName ?? r.description ?? "", 23, 2); const tip = tooltip([ `${r.id} - ${r.actionName ?? ""}`, r.description, `Ответственный: ${describeResponsible(r, model)}`, r.dateConstraint ? `Срок: ${r.dateConstraint}` : null, r.duration ? `Длительность: ${r.duration}` : null, r.dataIn.length ? `Вход: ${r.dataIn.join(", ")}` : null, r.dataOut.length ? `Выход: ${r.dataOut.join(", ")}` : null, r.questions ? `Вопрос: ${r.questions}` : null, ]); const parts = [`${tip}`]; parts.push(`${esc(r.id)}${r.dateConstraint ? ` · ${esc(truncate(r.dateConstraint, 17))}` : ""}`); title.forEach((t, i) => parts.push(`${esc(t)}`)); if (r.systemToBe) { const label = truncate(sysName.get(r.systemToBe) ?? r.systemToBe, 24); const w = Math.min(n.w - 16, 12 + label.length * 6.2); parts.push(`${esc(label)}`); } if (r.duration) parts.push(`${esc(r.duration)}`); if (r.questions) parts.push(``); parts.push(""); return parts.join(""); } function evSvg(n: Node, r: ProcessRow, schedule: Schedule): string { const t = schedule.timings.get(r.id); const { x, y, w, h } = n; const k = 14; const pts = `${x + k},${y} ${x + w - k},${y} ${x + w},${y + h / 2} ${x + w - k},${y + h} ${x + k},${y + h} ${x},${y + h / 2}`; const lines = wrap(`${r.actionName ?? ""}`, 22, 2); const out = [`${tooltip([`Событие: ${r.id} достигнут`, r.actionName, t ? `План: день ${t.end}` : null])}`]; out.push(`${esc(r.id)}${t ? ` · день ${t.end}` : ""}`); lines.forEach((l, i) => out.push(`${esc(l)}`)); out.push(""); return out.join(""); } function dataSvg(n: Node, d: { description: string | null; comment: string | null } | undefined, id: string, _roleName: Map): string { const label = truncate(id, 18); return `${tooltip([id, d?.description, d?.comment ? `Вопрос: ${d.comment}` : null])}${esc(label)}${d?.comment ? `` : ""}`; } function legend(data: boolean, events: boolean): string { const items: string[] = []; let x = 12; const y = 40; const add = (svg: string, text: string, w: number) => { items.push(`${svg}${esc(text)}`); x += w + 12 + text.length * 6.2; }; add(``, "функция (шаг)", 26); add(``, "функция-чек-поинт", 26); if (events) add(``, "событие (CP достигнут)", 26); add(``, "роль (дорожка)", 26); add(``, "система", 26); if (data) add(``, "объект данных", 22); add(``, "есть открытый вопрос", 16); return items.join(""); }