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(); 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> = []; 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(); 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(); const rowTop = new Map(); 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(`Диаграмма Ганта процесса (${esc(model.set)}): дни от первой встречи с архитектором`); // Ось: шаг подписей выбирается так, чтобы подписи не слипались при любом масштабе 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(``); } for (let d = 0; d <= days; d += tick) { out.push(``); out.push(`день ${d}`); const date = opts.kickoff ? addDays(opts.kickoff, d) : null; if (date) out.push(`${date}`); else if (d % 30 === 0) out.push(`мес. ${d / 30}`); } // Подложки групп и направляющие вех for (const g of groups) { const c = color(g.stage); const gi = groups.indexOf(g); out.push(``); out.push(``); if (!g.collapsed && g.rows.length) { const xs = new Set([g.summary.start, ...g.summary.milestones.map((m) => m.day)]); for (const d of xs) out.push(``); } } // Зависимости под полосами. Если группа свёрнута, от неё остаются вехи: стрелки идут между ромбами сводных полос. const groupOf = new Map(); 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(``); } } } out.push(`${arrows.join("")}`); } // Строки раскрытых групп 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(`${tip}`); out.push(`${esc(row.id)}`); out.push(`${esc(truncate(name, 52))}`); if (row.questions) out.push(`${esc(row.questions)}`); 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(`${esc(row.id)}${row.duration ? ` · ${esc(row.duration)}` : ""}`); if (t.kind === "recurring") { const w = Math.max(2, (t.end - t.start) * px); out.push(``); out.push(`${esc(name)}`); 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(``); if (name) { if (textW + 8 <= w) out.push(`${esc(name)}`); else { out.push(`${esc(name)}`); } } } if (ms || t.kind === "milestone") { const px0 = x(t.end); out.push(``); if (!hasBar && name) { out.push(`${esc(name)}`); } idText(px0 + 10, "start"); } else { if (!hasBar && name) { out.push(`${esc(name)}`); } idText(hasBar ? x(t.end) : x(t.end) + 6, hasBar ? "end" : "start"); } } out.push(""); } } // Строки групп: название слева (клик сворачивает), сводная полоса с вехами справа 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(`${tip}`); 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(`${g.collapsed ? "▸" : "▾"}`); out.push(`${esc(truncate(g.stage, 30))}(${g.rows.length})`); if (people.length) out.push(`${esc(truncate(people.join(" · "), 44))}`); out.push(""); out.push(`${tip}`); for (const [a, b] of s.segments) { out.push(``); } const diamond = (dx: number, size: number) => ``; 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(`${esc(l.text)}`); } out.push(""); } // Легенда const ly = height - 20; out.push( `веха` + `группа (сводная полоса)` + `работа` + `срок «не позже / около»` + `повторяется` + `противоречие в сроках` + `есть открытый вопрос (наведите курсор)`, ); const defs = ``; return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`); }