Новый сервис khbuild_process_viz: Гант и ARIS eEPC процесса to-be
Some checks failed
ci / test (push) Successful in 17s
ci / deploy (push) Failing after 22s

Читает таблицы khbuild_* (и архивные khnata_*) из Supabase и рисует SVG:
диаграмму Ганта (сроки из date_constraint и зависимостей, предупреждения о
противоречиях) и ARIS eEPC (дорожки ролей, функции, события, системы, данные).
Страница просмотра с вкладками, масштабом и фильтрами, доступ по токену.
Сервис добавлен в deploy/deploy.sh последним (порт 8086), документация в
docs/proposed, отклонение 16.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 08:24:50 +03:00
parent d8f3ddee37
commit 3fa8bb7e8e
30 changed files with 1246 additions and 4 deletions

View File

@@ -0,0 +1,173 @@
import type { ProcessModel, ProcessRow } from "./model.js";
import type { Schedule, Timing } from "./schedule.js";
import { PALETTE, esc, svgDoc, tooltip, truncate } from "./svg.js";
export interface GanttOptions {
/** дата kick-off (YYYY-MM-DD) - если задана, на оси подписываются календарные даты */
kickoff?: string | null;
/** рисовать стрелки зависимостей */
deps?: boolean;
/** показывать только эти этапы */
stages?: string[] | null;
}
const LEFT = 420;
const PX = 5; // пикселей на день
const ROW = 24;
const HEAD = 76;
const STAGE_ROW = 24;
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 function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
const key = new Map<string, number>();
for (const r of rows) {
const s = r.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));
}
return [...key.entries()].sort((a, b) => a[1] - b[1]).map(([s]) => s);
}
export function renderGantt(model: ProcessModel, schedule: Schedule, opts: GanttOptions = {}): string {
const stages = stageOrder(model.rows, schedule).filter((s) => !opts.stages?.length || opts.stages.includes(s));
const color = (stage: string) => PALETTE[stages.indexOf(stage) % PALETTE.length] ?? PALETTE[0]!;
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]);
// Строки: заголовок этапа, затем его шаги по началу
type Line = { kind: "stage"; stage: string } | { kind: "row"; row: ProcessRow; t: Timing };
const lines: Line[] = [];
for (const stage of stages) {
lines.push({ kind: "stage", stage });
const rs = model.rows
.filter((r) => (r.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 }));
for (const x of rs) lines.push({ kind: "row", ...x });
}
const yOf = new Map<string, number>();
let y = HEAD;
const ys: number[] = [];
for (const l of lines) {
ys.push(y);
if (l.kind === "row") yOf.set(l.row.id, y + ROW / 2);
y += l.kind === "stage" ? STAGE_ROW : ROW;
}
const height = y + 40;
const days = Math.ceil((schedule.maxDay + 10) / 10) * 10;
const width = LEFT + days * PX + 30;
const x = (d: number) => LEFT + d * PX;
const out: string[] = [];
// Ось и сетка
out.push(`<text x="12" y="24" font-size="16" font-weight="600" fill="#222">Диаграмма Ганта процесса (${esc(model.set)}): дни от первой встречи с архитектором</text>`);
for (let d = 0; d <= days; d += 7) {
const major = d % 30 === 0 || d % 28 === 0 ? d % 28 === 0 : false;
out.push(`<line x1="${x(d)}" y1="${HEAD - 4}" x2="${x(d)}" y2="${height - 30}" stroke="${major ? "#c9c9c9" : "#eeeeee"}" stroke-width="1"/>`);
}
for (let d = 0; d <= days; d += 30) {
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 out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
}
// Вертикальные линии чек-поинтов
const cpDays = new Set<number>();
for (const l of lines) if (l.kind === "row" && /^CP-/.test(l.row.id)) cpDays.add(l.t.end);
for (const d of cpDays) out.push(`<line x1="${x(d)}" y1="${HEAD}" x2="${x(d)}" y2="${height - 30}" stroke="#d9a1a1" stroke-width="1" stroke-dasharray="2 4"/>`);
// Зависимости под полосами
if (opts.deps !== false) {
const arrows: string[] = [];
for (const l of lines) {
if (l.kind !== "row") continue;
for (const dep of l.row.dependsOn) {
const dt = schedule.timings.get(dep);
const y1 = yOf.get(dep);
const y2 = yOf.get(l.row.id);
if (!dt || y1 === undefined || y2 === undefined) continue;
const x1 = x(dt.end);
const x2 = x(l.t.start);
const xm = Math.min(x2 - 4, Math.max(x1 + 4, (x1 + x2) / 2));
arrows.push(`<path d="M${x1} ${y1} H${xm} V${y2} H${x2}" fill="none" stroke="#9aa0a6" stroke-width="0.8" marker-end="url(#arr)"/>`);
}
}
out.push(`<g opacity="0.7">${arrows.join("")}</g>`);
}
// Строки
lines.forEach((l, i) => {
const top = ys[i]!;
if (l.kind === "stage") {
const c = color(l.stage);
out.push(`<rect x="0" y="${top}" width="${width}" height="${STAGE_ROW}" fill="${c.fill}" opacity="0.55"/>`);
out.push(`<text x="12" y="${top + 16}" font-weight="700" fill="${c.stroke}">${esc(l.stage)}</text>`);
return;
}
const { row, t } = l;
const c = color(row.stage ?? "(без этапа)");
const cy = top + ROW / 2;
const warn = conflicts.get(row.id);
const tip = tooltip([
`${row.id} - ${row.actionName ?? ""}`,
row.description,
`Ответственный: ${[row.role ? roleName.get(row.role) ?? row.role : null, row.responsibleName].filter(Boolean).join(" / ") || "не указан"}`,
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 isCp = /^CP-/.test(row.id);
out.push(`<g${t.fromConstraint || t.kind === "recurring" ? "" : ' opacity="0.65"'}>${tip}`);
out.push(`<text x="12" y="${cy + 4}" font-weight="${isCp ? 700 : 500}" fill="${warn ? "#b00020" : "#222"}">${esc(row.id)}</text>`);
out.push(`<text x="62" y="${cy + 4}" font-weight="${isCp ? 600 : 400}" fill="#222">${esc(truncate(row.actionName ?? row.description ?? "", 52))}</text>`);
if (row.questions) out.push(`<circle cx="${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"' : "";
if (t.kind === "milestone") {
const px = x(t.end);
out.push(`<path d="M${px} ${cy - 8} L${px + 8} ${cy} L${px} ${cy + 8} L${px - 8} ${cy} Z" fill="${isCp ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${isCp ? 1.5 : 1}"${dash}/>`);
if (isCp) out.push(`<text x="${px + 12}" y="${cy + 4}" fill="#555" font-size="11">день ${t.end}</text>`);
} else if (t.kind === "recurring") {
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${Math.max(2, (t.end - t.start) * PX)}" height="8" rx="3" fill="url(#hatch)" stroke="${c.stroke}" stroke-width="0.8"/>`);
} else {
out.push(`<rect x="${x(t.start)}" y="${cy - 7}" width="${Math.max(3, (t.end - t.start) * PX)}" height="14" rx="3" fill="${c.fill}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
out.push(`<text x="${x(t.end) + 5}" y="${cy + 4}" fill="#555" font-size="11">${t.start}–${t.end}</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="130" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4"/><text x="158" y="${ly + 7}">работа</text>` +
`<rect x="212" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4" stroke-dasharray="4 2"/><text x="240" y="${ly + 7}">срок «не позже / около»</text>` +
`<rect x="400" y="${ly - 1}" width="22" height="10" rx="3" fill="url(#hatch)" stroke="#777"/><text x="428" y="${ly + 7}">повторяется</text>` +
`<rect x="515" y="${ly - 1}" width="22" height="10" rx="3" fill="#fff" stroke="#d32f2f" stroke-width="1.6"/><text x="543" y="${ly + 7}">противоречие в сроках</text>` +
`<circle cx="690" cy="${ly + 4}" r="4" fill="#e6a100"/><text x="700" y="${ly + 7}">есть открытый вопрос (наведите курсор)</text></g>`,
);
const defs =
`<marker id="arr" viewBox="0 0 6 6" refX="5" refY="3" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#9aa0a6"/></marker>` +
`<pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="6" height="6" fill="#ffffff"/><line x1="0" y1="0" x2="0" y2="6" stroke="#9aa0a6" stroke-width="2"/></pattern>`;
return svgDoc(width, height, defs, out.join("\n"));
}