Модель читает khbuild_responsible (колонки responsible, responsible2/3 = ключ «роль - Имя»); если справочника нет (архив khnata) - прежние responsible_role/responsible_name и khnata_roles. Длительность: 5d - календарные дни, 5wd - рабочие, суффикс ? игнорируется при расчёте и выводится в Ганте и ARIS. Тесты на обе схемы и откат на прежний справочник. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
269 lines
14 KiB
TypeScript
269 lines
14 KiB
TypeScript
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<string, string[]>();
|
||
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<string, number>();
|
||
const visiting = new Set<string>();
|
||
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<string, ProcessRow>();
|
||
for (const r of ordered) for (const d of r.dataOut) if (!producer.has(d)) producer.set(d, r);
|
||
const consumers = new Map<string, ProcessRow[]>();
|
||
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<string, number>();
|
||
const stackF = new Map<string, number>(); // lane -> максимум слотов функций
|
||
const stackD = new Map<string, number>(); // 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<string, { y: number; h: number }>();
|
||
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(`<text x="12" y="24" font-size="16" font-weight="600" fill="#222">ARIS eEPC процесса (${esc(model.set)}): дорожки - роли, функции - шаги, события - чек-поинты</text>`);
|
||
out.push(legend(showData, showEvents));
|
||
|
||
// Дорожки
|
||
laneOrder.forEach((lane, i) => {
|
||
const ly = laneY.get(lane)!;
|
||
out.push(`<rect x="0" y="${ly.y}" width="${width}" height="${ly.h}" fill="${i % 2 ? "#fafafa" : "#f3f6fa"}" stroke="#d5dbe3"/>`);
|
||
const label = lane === "_none" ? "Не назначено" : roleName.get(lane) ?? lane;
|
||
const roleId = lane === "_none" ? "" : lane;
|
||
const cy = ly.y + ly.h / 2;
|
||
out.push(`<g>${tooltip([`Роль: ${roleId || "не назначена"}`, model.roles.find((r) => r.id === lane)?.comment])}<ellipse cx="${LABEL_W / 2}" cy="${cy}" rx="${LABEL_W / 2 - 10}" ry="26" fill="${C.org.fill}" stroke="${C.org.stroke}" stroke-width="1.4"/>`);
|
||
const lines = wrap(label, 18, 2);
|
||
lines.forEach((t, j) => out.push(`<text x="${LABEL_W / 2}" y="${cy + 4 + (j - (lines.length - 1) / 2) * 14}" text-anchor="middle" font-weight="600" fill="#5a4a00">${esc(t)}</text>`));
|
||
out.push("</g>");
|
||
});
|
||
|
||
// Рёбра под узлами
|
||
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 [`<path d="M${p1.x} ${p1.y} H${xm} V${p2.y} H${p2.x}" fill="none" ${style} marker-end="url(#${marker})"/>`];
|
||
});
|
||
out.push(`<g opacity="0.85">${edgeSvg.join("")}</g>`);
|
||
|
||
// Узлы
|
||
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 =
|
||
`<marker id="arrF" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L8 4 L0 8 z" fill="#555"/></marker>` +
|
||
`<marker id="arrD" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L8 4 L0 8 z" fill="#2b8aa0"/></marker>`;
|
||
return svgDoc(width, height, defs, out.join("\n"));
|
||
}
|
||
|
||
function fnSvg(n: Node, r: ProcessRow, roleName: Map<string, string>, sysName: Map<string, string>, 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 = [`<g>${tip}<rect x="${n.x}" y="${n.y}" width="${n.w}" height="${n.h}" rx="12" fill="${c.fill}" stroke="${c.stroke}" stroke-width="${cp ? 2.4 : 1.4}"/>`];
|
||
parts.push(`<text x="${n.x + 10}" y="${n.y + 16}" font-weight="700" fill="${c.stroke}" font-size="11">${esc(r.id)}${r.dateConstraint ? ` · ${esc(truncate(r.dateConstraint, 17))}` : ""}</text>`);
|
||
title.forEach((t, i) => parts.push(`<text x="${n.x + 10}" y="${n.y + 32 + i * 14}" fill="#1c2b0f" font-weight="${cp ? 600 : 500}">${esc(t)}</text>`));
|
||
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(`<rect x="${n.x + 8}" y="${n.y + n.h - 19}" width="${w}" height="14" rx="4" fill="${C.sys.fill}" stroke="${C.sys.stroke}"/><text x="${n.x + 14}" y="${n.y + n.h - 8}" font-size="10" fill="#10335a">${esc(label)}</text>`);
|
||
}
|
||
if (r.duration) parts.push(`<text x="${n.x + n.w - 8}" y="${n.y + n.h - 8}" text-anchor="end" font-size="10" font-weight="600" fill="#3d5a1f">${esc(r.duration)}</text>`);
|
||
if (r.questions) parts.push(`<circle cx="${n.x + n.w - 10}" cy="${n.y + 10}" r="5" fill="#e6a100"/>`);
|
||
parts.push("</g>");
|
||
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 = [`<g>${tooltip([`Событие: ${r.id} достигнут`, r.actionName, t ? `План: день ${t.end}` : null])}<polygon points="${pts}" fill="${C.ev.fill}" stroke="${C.ev.stroke}" stroke-width="1.6"/>`];
|
||
out.push(`<text x="${x + w / 2}" y="${y + 15}" text-anchor="middle" font-size="10" font-weight="700" fill="${C.ev.stroke}">${esc(r.id)}${t ? ` · день ${t.end}` : ""}</text>`);
|
||
lines.forEach((l, i) => out.push(`<text x="${x + w / 2}" y="${y + 29 + i * 12}" text-anchor="middle" font-size="11" fill="#4a1226">${esc(l)}</text>`));
|
||
out.push("</g>");
|
||
return out.join("");
|
||
}
|
||
|
||
function dataSvg(n: Node, d: { description: string | null; comment: string | null } | undefined, id: string, _roleName: Map<string, string>): string {
|
||
const label = truncate(id, 18);
|
||
return `<g>${tooltip([id, d?.description, d?.comment ? `Вопрос: ${d.comment}` : null])}<path d="M${n.x} ${n.y} H${n.x + n.w - 10} L${n.x + n.w} ${n.y + 10} V${n.y + n.h} H${n.x} Z" fill="${C.data.fill}" stroke="${C.data.stroke}"/><text x="${n.x + 6}" y="${n.y + 19}" font-size="10" fill="#0d3a47">${esc(label)}</text>${d?.comment ? `<circle cx="${n.x + n.w - 8}" cy="${n.y + n.h - 8}" r="3.5" fill="#e6a100"/>` : ""}</g>`;
|
||
}
|
||
|
||
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(`<g transform="translate(${x},${y})">${svg}<text x="${w + 6}" y="12" font-size="11" fill="#444">${esc(text)}</text></g>`);
|
||
x += w + 12 + text.length * 6.2;
|
||
};
|
||
add(`<rect width="26" height="16" rx="6" fill="${C.fn.fill}" stroke="${C.fn.stroke}"/>`, "функция (шаг)", 26);
|
||
add(`<rect width="26" height="16" rx="6" fill="${C.fnCp.fill}" stroke="${C.fnCp.stroke}" stroke-width="2.2"/>`, "функция-чек-поинт", 26);
|
||
if (events) add(`<polygon points="5,0 21,0 26,8 21,16 5,16 0,8" fill="${C.ev.fill}" stroke="${C.ev.stroke}"/>`, "событие (CP достигнут)", 26);
|
||
add(`<ellipse cx="13" cy="8" rx="13" ry="8" fill="${C.org.fill}" stroke="${C.org.stroke}"/>`, "роль (дорожка)", 26);
|
||
add(`<rect width="26" height="12" y="2" rx="4" fill="${C.sys.fill}" stroke="${C.sys.stroke}"/>`, "система", 26);
|
||
if (data) add(`<path d="M0 0 H16 L22 6 V16 H0 Z" fill="${C.data.fill}" stroke="${C.data.stroke}"/>`, "объект данных", 22);
|
||
add(`<circle cx="8" cy="8" r="5" fill="#e6a100"/>`, "есть открытый вопрос", 16);
|
||
return items.join("");
|
||
}
|