Files
khb_microservices/packages/khbuild_process_viz/src/gantt.ts
2026-10-14 20:15:28 +03:00

397 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describeResponsible, type ProcessModel, type ProcessRow } from "./model.js";
import type { Schedule, Timing } from "./schedule.js";
import { esc, svgDoc, tooltip, truncate } from "./svg.js";
export interface GanttOptions {
/** дата kick-off (YYYY-MM-DD) - если задана, на оси подписываются календарные даты */
kickoff?: string | null;
/** рисовать стрелки зависимостей */
deps?: boolean;
/** показывать только эти этапы */
stages?: string[] | null;
/** масштаб времени: пикселей на день. Меняет только ось времени, шрифты и интервалы строк остаются прежними */
px?: number;
/** свёрнутые группы (этапы): от них остаётся только сводная полоса */
collapsed?: string[] | null;
}
/** Ширина левой колонки с названиями; не зависит от масштаба времени. */
export const GANTT_LEFT = 420;
export const GANTT_DEFAULT_PX = 5;
export const GANTT_MIN_PX = 0.5;
export const GANTT_MAX_PX = 40;
const ROW = 36; // строка шага: подпись над полосой, полоса, id справа снизу
const BAR_CY = 21; // центр полосы от верха строки
const BAR_H = 14;
const HEAD = 76;
const GROUP_BAR_H = 14; // высота сводной полосы
const GROUP_HEAD_MIN = 40; // в шапке группы помещаются название и роли
const GROUP_PAD = 8; // отступ сверху и снизу в строке группы
const LABEL_STEP = 13; // шаг подписей вех по вертикали
const MAX_LABEL_LEVELS = 4;
const CHAR_W = 6.1; // ширина символа подписи (шрифт 11px)
const NO_STAGE = "(без этапа)";
const addDays = (iso: string, days: number): string | null => {
const d = new Date(`${iso}T00:00:00Z`);
if (Number.isNaN(d.getTime())) return null;
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
};
export const clampPx = (px: number | undefined): number => {
const v = typeof px === "number" && Number.isFinite(px) ? px : GANTT_DEFAULT_PX;
return Math.min(GANTT_MAX_PX, Math.max(GANTT_MIN_PX, v));
};
/** Группы презентации «Pre-construction»: порядок сверху вниз и цвета (сплошная полоса / светлый тон для примерных сроков). */
export const STAGE_STYLES: ReadonlyArray<{ stage: string; fill: string; stroke: string }> = [
{ stage: "Договоры", stroke: "#7a808f", fill: "#dde0e6" },
{ stage: "Архитектура", stroke: "#3f9a78", fill: "#d4ece3" },
{ stage: "Спецификации", stroke: "#3f7ea6", fill: "#d3e4ef" },
{ stage: "Пермит", stroke: "#d8622f", fill: "#f7d9cc" },
{ stage: "Финансы", stroke: "#d4982f", fill: "#f5e6c8" },
{ stage: "Закупки", stroke: "#6f93ab", fill: "#dbe6ee" },
{ stage: "Стройка", stroke: "#1f7a52", fill: "#cfe6da" },
];
const OTHER_STYLES: ReadonlyArray<{ fill: string; stroke: string }> = [
{ stroke: "#8a6bb5", fill: "#e5dcf1" },
{ stroke: "#b44b7c", fill: "#f5cfe0" },
{ stroke: "#2f9a8f", fill: "#c9f0ec" },
{ stroke: "#a39a1c", fill: "#f3efb0" },
];
/** Порядок этапов: сначала группы презентации в её порядке, остальные - по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
const key = new Map<string, number>();
for (const r of rows) {
const s = r.stage ?? NO_STAGE;
const t = schedule.timings.get(r.id);
if (!t || t.kind === "recurring") {
if (!key.has(s)) key.set(s, Infinity);
continue;
}
const v = t.fromConstraint ? t.end : t.end + 0.5; // выведенные сроки чуть слабее заданных
key.set(s, Math.min(key.get(s) ?? Infinity, v));
}
const known = (s: string) => STAGE_STYLES.findIndex((x) => x.stage === s);
return [...key.entries()]
.sort((a, b) => {
const ka = known(a[0]);
const kb = known(b[0]);
if (ka >= 0 || kb >= 0) return (ka >= 0 ? ka : Infinity) - (kb >= 0 ? kb : Infinity) || a[1] - b[1];
return a[1] - b[1];
})
.map(([s]) => s);
}
export interface GroupSummary {
stage: string;
/** границы сводной полосы (дни) */
start: number;
end: number;
/** вехи группы: строки с признаком is_milestone, по дате завершения */
milestones: Array<{ row: ProcessRow; day: number }>;
/** отрезки, где в группе идут активности (объединение интервалов работ); между ними полоса прерывается */
segments: Array<[number, number]>;
}
/**
* Границы группы считаются по шагам с реальным сроком: повторяющиеся шаги (они тянутся на весь проект) и шаги без срока
* (выведенные нули без зависимостей) границы не растягивают. Если таких шагов нет, берутся все.
*/
export function summarizeGroup(stage: string, rows: Array<{ row: ProcessRow; t: Timing }>): GroupSummary {
const real = rows.filter(({ t }) => t.kind !== "recurring" && (t.fromConstraint || t.end > t.start));
const base = real.length ? real : rows;
const start = Math.min(...base.map(({ t }) => t.start));
const end = Math.max(...base.map(({ t }) => t.end));
const milestones = rows
.filter(({ row, t }) => row.isMilestone && t.kind !== "recurring")
.map(({ row, t }) => ({ row, day: t.end }))
.sort((a, b) => a.day - b.day || a.row.id.localeCompare(b.row.id, "ru", { numeric: true }));
// Сводная полоса показывает занятость: отрезки работ объединяются, там где активностей нет - разрыв, дальше полоса продолжается.
// Если в группе нет ни одной работы с длительностью (только вехи), рисуется один сплошной отрезок от начала до конца.
const tasks = rows
.filter(({ t }) => t.kind === "task")
.map(({ t }) => [t.start, t.end] as [number, number])
.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const segments: Array<[number, number]> = [];
for (const [a, b] of tasks) {
const last = segments.at(-1);
if (last && a <= last[1]) last[1] = Math.max(last[1], b);
else segments.push([a, b]);
}
const s0 = Number.isFinite(start) ? start : 0;
const e0 = Number.isFinite(end) ? end : 0;
return { stage, start: s0, end: e0, milestones, segments: segments.length ? segments : [[s0, e0]] };
}
interface PlacedLabel { x: number; level: number; text: string; row: ProcessRow }
/** Раскладывает подписи вех над полосой: сначала длинная подпись (id и название), потом короткая (id), на минимально возможном уровне. */
export function placeLabels(items: Array<{ x: number; row: ProcessRow }>): { labels: PlacedLabel[]; levels: number } {
const taken: Array<Array<[number, number]>> = [];
const labels: PlacedLabel[] = [];
const fits = (level: number, a: number, b: number) => (taken[level] ?? []).every(([l, r]) => b + 6 <= l || a - 6 >= r);
for (const it of items) {
const long = `${it.row.id} · ${truncate(it.row.actionName ?? "", 24)}`;
const candidates = [long, it.row.id];
let placed = false;
for (let level = 0; level < MAX_LABEL_LEVELS && !placed; level++) {
for (const text of candidates) {
const w = text.length * CHAR_W;
if (!fits(level, it.x - w / 2, it.x + w / 2)) continue;
(taken[level] ??= []).push([it.x - w / 2, it.x + w / 2]);
labels.push({ x: it.x, level, text, row: it.row });
placed = true;
break;
}
}
if (!placed) {
// места нет даже на верхнем уровне: коротко на верхнем уровне поверх остальных
const level = MAX_LABEL_LEVELS - 1;
(taken[level] ??= []).push([it.x - 15, it.x + 15]);
labels.push({ x: it.x, level, text: it.row.id, row: it.row });
}
}
return { labels, levels: labels.length ? Math.max(...labels.map((l) => l.level)) + 1 : 0 };
}
export function renderGantt(model: ProcessModel, schedule: Schedule, opts: GanttOptions = {}): string {
const px = clampPx(opts.px);
const collapsedSet = new Set(opts.collapsed ?? []);
const stages = stageOrder(model.rows, schedule).filter((s) => !opts.stages?.length || opts.stages.includes(s));
const others = stages.filter((s) => !STAGE_STYLES.some((x) => x.stage === s));
const color = (stage: string): { fill: string; stroke: string } =>
STAGE_STYLES.find((x) => x.stage === stage) ?? OTHER_STYLES[Math.max(0, others.indexOf(stage)) % OTHER_STYLES.length]!;
const roleName = new Map(model.roles.map((r) => [r.id, r.person ?? r.id]));
const conflicts = new Map<string, string[]>();
for (const w of schedule.warnings) conflicts.set(w.id, [...(conflicts.get(w.id) ?? []), w.message]);
const x = (d: number) => GANTT_LEFT + d * px;
// Группы: строки этапа по началу
interface Group { stage: string; rows: Array<{ row: ProcessRow; t: Timing }>; summary: GroupSummary; collapsed: boolean; labels: PlacedLabel[]; levels: number; headH: number; top: number; bottom: number }
const groups: Group[] = stages.map((stage) => {
const rows = model.rows
.filter((r) => (r.stage ?? NO_STAGE) === stage)
.map((r) => ({ row: r, t: schedule.timings.get(r.id)! }))
.sort((a, b) => a.t.start - b.t.start || a.t.end - b.t.end || a.row.id.localeCompare(b.row.id, "ru", { numeric: true }));
const summary = summarizeGroup(stage, rows);
const { labels, levels } = placeLabels(summary.milestones.map((m) => ({ x: x(m.day), row: m.row })));
const headH = Math.max(GROUP_HEAD_MIN, GROUP_PAD + levels * LABEL_STEP + GROUP_BAR_H + GROUP_PAD);
return { stage, rows, summary, collapsed: collapsedSet.has(stage), labels, levels, headH, top: 0, bottom: 0 };
});
// Вертикальная раскладка
const yOf = new Map<string, number>();
const rowTop = new Map<string, number>();
let y = HEAD;
for (const g of groups) {
g.top = y;
y += g.headH;
if (!g.collapsed) {
for (const { row } of g.rows) {
rowTop.set(row.id, y);
yOf.set(row.id, y + BAR_CY);
y += ROW;
}
}
g.bottom = y;
}
const height = y + 40;
const days = Math.ceil((schedule.maxDay + 10) / 10) * 10;
// подписи вех могут выступать за правый край оси
const labelRight = Math.max(
0,
...groups.flatMap((g) => g.labels.map((l) => l.x + (l.text.length * CHAR_W) / 2)),
...groups.flatMap((g) => (g.collapsed ? [] : g.rows.map(({ row, t }) => x(Math.max(t.start, t.end)) + 14 + (row.actionName ?? row.description ?? "").length * CHAR_W))),
);
const width = Math.round(Math.max(GANTT_LEFT + days * px + 30, labelRight + 16));
const out: string[] = [];
out.push(`<text x="12" y="24" font-size="16" font-weight="600" fill="#222">Диаграмма Ганта процесса (${esc(model.set)}): дни от первой встречи с архитектором</text>`);
// Ось: шаг подписей выбирается так, чтобы подписи не слипались при любом масштабе
const steps = [1, 2, 5, 7, 14, 30, 60, 90, 180];
const tick = steps.find((s) => s * px >= 64) ?? 180;
const gridStep = steps.find((s) => s * px >= 8) ?? 7;
for (let d = 0; d <= days; d += gridStep) {
out.push(`<line x1="${x(d)}" y1="${HEAD - 4}" x2="${x(d)}" y2="${height - 30}" stroke="${d % tick === 0 ? "#c9c9c9" : "#eeeeee"}" stroke-width="1"/>`);
}
for (let d = 0; d <= days; d += tick) {
out.push(`<line x1="${x(d)}" y1="${HEAD - 18}" x2="${x(d)}" y2="${height - 30}" stroke="#bdbdbd" stroke-width="1.2"/>`);
out.push(`<text x="${x(d) + 3}" y="${HEAD - 38}" fill="#444" font-weight="600">день ${d}</text>`);
const date = opts.kickoff ? addDays(opts.kickoff, d) : null;
if (date) out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">${date}</text>`);
else if (d % 30 === 0) out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
}
// Подложки групп и направляющие вех
for (const g of groups) {
const c = color(g.stage);
const gi = groups.indexOf(g);
out.push(`<rect x="0" y="${g.top}" width="${width}" height="${g.bottom - g.top}" fill="${gi % 2 === 0 ? "#f1f1ee" : "#ffffff"}"/>`);
out.push(`<rect x="0" y="${g.top}" width="6" height="${g.bottom - g.top}" fill="${c.stroke}"/>`);
if (!g.collapsed && g.rows.length) {
const xs = new Set<number>([g.summary.start, ...g.summary.milestones.map((m) => m.day)]);
for (const d of xs) out.push(`<line x1="${x(d)}" y1="${g.top + g.headH - GROUP_PAD}" x2="${x(d)}" y2="${g.bottom}" stroke="${c.stroke}" stroke-width="1" stroke-dasharray="4 4" opacity="0.7"/>`);
}
}
// Зависимости под полосами. Если группа свёрнута, от неё остаются вехи: стрелки идут между ромбами сводных полос.
const groupOf = new Map<string, Group>();
for (const g of groups) for (const { row } of g.rows) groupOf.set(row.id, g);
const anchor = (id: string): { xs: number; xe: number; y: number } | null => {
const tm = schedule.timings.get(id);
const g = groupOf.get(id);
if (!tm || !g) return null;
if (!g.collapsed) {
const yy = yOf.get(id);
return yy === undefined ? null : { xs: x(tm.start), xe: x(tm.end), y: yy };
}
const m = g.summary.milestones.find((mm) => mm.row.id === id);
return m ? { xs: x(m.day), xe: x(m.day), y: g.top + GROUP_PAD + g.levels * LABEL_STEP + GROUP_BAR_H / 2 } : null;
};
if (opts.deps !== false) {
const arrows: string[] = [];
for (const g of groups) {
for (const { row } of g.rows) {
for (const dep of row.dependsOn) {
const from = anchor(dep);
const to = anchor(row.id);
if (!from || !to) continue;
const x1 = from.xe;
const x2 = to.xs;
const d = x2 >= x1 ? `M${x1} ${from.y} V${to.y} H${x2}` : `M${x1} ${from.y} H${x1 + 6} V${to.y} H${x2}`;
arrows.push(`<path d="${d}" fill="none" stroke="#444" stroke-width="1.1" marker-end="url(#arr)"/>`);
}
}
}
out.push(`<g opacity="0.75">${arrows.join("")}</g>`);
}
// Строки раскрытых групп
for (const g of groups) {
if (g.collapsed) continue;
const c = color(g.stage);
for (const { row, t } of g.rows) {
const top = rowTop.get(row.id)!;
const cy = top + BAR_CY;
const warn = conflicts.get(row.id);
const tip = tooltip([
`${row.id} - ${row.actionName ?? ""}${row.isMilestone ? " (веха)" : ""}`,
row.description,
`Ответственный: ${describeResponsible(row, model)}`,
row.systemToBe ? `Система: ${row.systemToBe}` : null,
row.dateConstraint ? `Срок: ${row.dateConstraint}` : `Срок выведен из зависимостей: день ${t.start}${t.end !== t.start ? "–" + t.end : ""}`,
row.duration ? `Длительность: ${row.duration}` : null,
row.dependsOn.length ? `После: ${row.dependsOn.join(", ")}` : null,
...(warn ?? []).map((w) => `⚠ ${w}`),
row.questions ? `Вопрос: ${row.questions}` : null,
]);
const ms = row.isMilestone;
const name = row.actionName ?? row.description ?? "";
out.push(`<g${t.fromConstraint || t.kind === "recurring" ? "" : ' opacity="0.65"'}>${tip}`);
out.push(`<text x="12" y="${cy + 4}" font-weight="${ms ? 700 : 500}" fill="${warn ? "#b00020" : "#222"}">${esc(row.id)}</text>`);
out.push(`<text x="62" y="${cy + 4}" font-weight="${ms ? 600 : 400}" fill="#222">${esc(truncate(name, 52))}</text>`);
if (row.questions) out.push(`<circle cx="${GANTT_LEFT - 14}" cy="${cy}" r="4" fill="#e6a100"><title>${esc(row.questions)}</title></circle>`);
const stroke = warn ? "#d32f2f" : c.stroke;
const dash = t.approx ? ' stroke-dasharray="4 2"' : "";
const textW = name.length * CHAR_W;
const idText = (tx: number, anchor: "start" | "end") =>
out.push(`<text x="${tx}" y="${top + ROW - 3}" text-anchor="${anchor}" font-size="9" letter-spacing="0.5" fill="#777">${esc(row.id)}${row.duration ? ` · ${esc(row.duration)}` : ""}</text>`);
if (t.kind === "recurring") {
const w = Math.max(2, (t.end - t.start) * px);
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${w}" height="8" rx="3" fill="${c.stroke}" fill-opacity="0.35" stroke="${c.stroke}" stroke-width="0.8"/>`);
out.push(`<text x="${x(t.start) + 2}" y="${cy - 9}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
idText(x(t.end), "end");
} else {
const hasBar = t.end > t.start;
const w = Math.max(3, (t.end - t.start) * px);
const solid = !t.approx;
if (hasBar) {
out.push(`<rect x="${x(t.start)}" y="${cy - BAR_H / 2}" width="${w}" height="${BAR_H}" rx="3" fill="${solid ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
if (name) {
if (textW + 8 <= w) out.push(`<text x="${x(t.start) + 5}" y="${cy + 4}" font-size="11" font-weight="600" fill="${solid ? "#fff" : "#222"}">${esc(name)}</text>`);
else {
out.push(`<text x="${x(t.start)}" y="${cy - BAR_H / 2 - 3}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
}
}
if (ms || t.kind === "milestone") {
const px0 = x(t.end);
out.push(`<path d="M${px0} ${cy - 8} L${px0 + 8} ${cy} L${px0} ${cy + 8} L${px0 - 8} ${cy} Z" fill="#1f1f1f" stroke="#fff" stroke-width="1.2"/>`);
if (!hasBar && name) {
out.push(`<text x="${px0 + 12}" y="${cy + 4}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
idText(px0 + 10, "start");
} else {
if (!hasBar && name) {
out.push(`<text x="${x(t.end) + 6}" y="${cy + 4}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
idText(hasBar ? x(t.end) : x(t.end) + 6, hasBar ? "end" : "start");
}
}
out.push("</g>");
}
}
// Строки групп: название слева (клик сворачивает), сводная полоса с вехами справа
for (const g of groups) {
const c = color(g.stage);
const s = g.summary;
const barY = g.top + GROUP_PAD + g.levels * LABEL_STEP;
const cy = barY + GROUP_BAR_H / 2;
const tip = tooltip([
`${g.stage}: ${g.rows.length} шаг(ов), дни ${s.start}–${s.end}`,
s.milestones.length ? "Вехи:" : "Вех в группе нет (признак is_milestone)",
...s.milestones.map((m) => ` день ${m.day}: ${m.row.id} - ${m.row.actionName ?? ""}`),
g.collapsed ? "Клик - развернуть" : "Клик - свернуть",
]);
// зона клика: левая колонка и сама полоса
out.push(`<g data-toggle="${esc(g.stage)}" style="cursor:pointer">${tip}<rect x="0" y="${g.top}" width="${GANTT_LEFT - 24}" height="${g.headH}" fill="#000" fill-opacity="0"/>`);
const personOf = new Map(model.responsible.map((r) => [r.id, r.person ?? r.id]));
const people = [
...new Set(
g.rows
.flatMap(({ row }) => (row.responsible.length ? row.responsible.map((id) => personOf.get(id) ?? id) : [row.role ? roleName.get(row.role) ?? row.role : null]))
.filter((v): v is string => !!v),
),
];
out.push(`<text x="14" y="${g.top + 19}" font-size="13" fill="${c.stroke}">${g.collapsed ? "▸" : "▾"}</text>`);
out.push(`<text x="32" y="${g.top + 19}" font-size="14" font-weight="700" fill="#222">${esc(truncate(g.stage, 30))}<tspan dx="6" font-size="11" font-weight="400" fill="#667085">(${g.rows.length})</tspan></text>`);
if (people.length) out.push(`<text x="32" y="${g.top + 34}" font-size="11" fill="#667085">${esc(truncate(people.join(" · "), 44))}</text>`);
out.push("</g>");
out.push(`<g>${tip}`);
for (const [a, b] of s.segments) {
out.push(`<rect x="${x(a)}" y="${barY}" width="${Math.max(2, (b - a) * px)}" height="${GROUP_BAR_H}" rx="2" fill="${c.stroke}" stroke="${c.stroke}" stroke-width="1.2"/>`);
}
const diamond = (dx: number, size: number) => `<path d="M${dx} ${cy - size} L${dx + size} ${cy} L${dx} ${cy + size} L${dx - size} ${cy} Z" fill="${c.stroke}" stroke="#fff" stroke-width="1"/>`;
const markDays = new Set(s.milestones.map((m) => m.day));
if (!markDays.has(s.start)) out.push(diamond(x(s.start), 6));
if (!markDays.has(s.end)) out.push(diamond(x(s.end), 6));
for (const m of s.milestones) out.push(diamond(x(m.day), 8));
for (const l of g.labels) {
const ly = barY - 4 - l.level * LABEL_STEP;
out.push(`<text x="${l.x}" y="${ly}" text-anchor="middle" font-size="11" font-weight="600" fill="${c.stroke}">${esc(l.text)}</text>`);
}
out.push("</g>");
}
// Легенда
const ly = height - 20;
out.push(
`<g font-size="11" fill="#444"><path d="M14 ${ly - 4} l6 6 l-6 6 l-6 -6 z" fill="#777"/><text x="26" y="${ly + 7}">веха</text>` +
`<rect x="72" y="${ly - 1}" width="30" height="10" rx="2" fill="#3f7ea6" stroke="#3f7ea6"/><text x="108" y="${ly + 7}">группа (сводная полоса)</text>` +
`<rect x="260" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4"/><text x="288" y="${ly + 7}">работа</text>` +
`<rect x="342" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4" stroke-dasharray="4 2"/><text x="370" y="${ly + 7}">срок «не позже / около»</text>` +
`<rect x="530" y="${ly - 1}" width="22" height="10" rx="3" fill="#777" fill-opacity="0.35" stroke="#777"/><text x="558" y="${ly + 7}">повторяется</text>` +
`<rect x="645" y="${ly - 1}" width="22" height="10" rx="3" fill="#fff" stroke="#d32f2f" stroke-width="1.6"/><text x="673" y="${ly + 7}">противоречие в сроках</text>` +
`<circle cx="820" cy="${ly + 4}" r="4" fill="#e6a100"/><text x="830" y="${ly + 7}">есть открытый вопрос (наведите курсор)</text></g>`,
);
const defs = `<marker id="arr" viewBox="0 0 6 6" refX="5" refY="3" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#444"/></marker>`;
return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`);
}