Гант: свёртывание групп, сводные полосы с вехами, масштаб времени
Каждый этап - группа со сводной штрихованной полосой; вехи (колонка is_milestone, по умолчанию чек-пойнты CP-*) отмечены ромбами с подписями над полосой и пунктирными направляющими вниз. Группы сворачиваются кликом, кнопками «Свернуть все / Развернуть все». Масштаб времени (кнопки и Shift+колесо) меняет только ось, шрифты и интервалы не меняются. Состояние в адресе: px, collapsed. Параметры px и collapsed у /gantt.svg. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -148,7 +148,7 @@ pnpm test # весь набор (интеграционные т
|
||||
|
||||
`khbuild_process_viz` строит Гант и ARIS из таблиц процесса. Данные редактируются в БД (Mathesar/NocoDB или SQL), код менять не нужно:
|
||||
- Сроки задаёт колонка `date_constraint` (дни от первой встречи с архитектором: `день 7`, `не позже дня 7`, `день 45–47`, `день 80 → день 90`, `еженедельно`), остальное считается по `depends_on`, `depends_on2`, `depends_on3` и `duration`. Противоречия подсвечиваются красным и перечислены на странице.
|
||||
- Параметры: `?view=gantt|aris`, `set=khbuild|khnata`, `kickoff=YYYY-MM-DD`, `data=1` (объекты данных в ARIS), `events=0`, `deps=0`, `stages=a|b`. Описание: `docs/proposed/data_objects/khbuild_process_viz/api_objects.md`, модель данных - `docs/proposed/data_objects/process_star.md`.
|
||||
- Параметры: `?view=gantt|aris`, `set=khbuild|khnata`, `kickoff=YYYY-MM-DD`, `data=1` (объекты данных в ARIS), `events=0`, `deps=0`, `stages=a|b`, для Ганта ещё `px=<пикселей на день>` (масштаб времени) и `collapsed=a|b` (свёрнутые группы). Вехи на сводной полосе группы - строки с `is_milestone = true` (у `CP-*` стоит по умолчанию; другие строки можно пометить в Mathesar/NocoDB). Описание: `docs/proposed/data_objects/khbuild_process_viz/api_objects.md`, модель данных - `docs/proposed/data_objects/process_star.md`.
|
||||
- Новая таблица для отчёта: раздел 2 (GRANT + политика RLS).
|
||||
|
||||
## 6. Деплой и проверка результата
|
||||
|
||||
@@ -6,7 +6,7 @@ HTTP на 127.0.0.1:8086, токен из `settings.json5` (`khbuild_process_viz
|
||||
|---|---|---|
|
||||
| GET | `/healthz` | `{ "ok": true, "db": true, "time": "<iso>" }` без авторизации; `ok` не зависит от БД (признак `db` - отдельно) |
|
||||
| GET | `/` | страница просмотра: вкладки Гант / ARIS, выбор набора данных, дата kick-off, фильтр этапов, масштаб и перетаскивание |
|
||||
| GET | `/gantt.svg` | диаграмма Ганта. Параметры: `set` (`khbuild`/`khnata`), `kickoff=YYYY-MM-DD` (даты на оси), `deps=0` (без стрелок), `stages=a\|b` (фильтр этапов), `download=1` (вложение) |
|
||||
| GET | `/gantt.svg` | диаграмма Ганта. Параметры: `set` (`khbuild`/`khnata`), `kickoff=YYYY-MM-DD` (даты на оси), `deps=0` (без стрелок), `stages=a\|b` (фильтр этапов), `px=<число>` (масштаб времени, пикселей на день, по умолчанию 5, от 0.5 до 40; шрифты и высота строк не меняются), `collapsed=a\|b` (свёрнутые группы-этапы: остаётся сводная полоса), `download=1` (вложение) |
|
||||
| GET | `/aris.svg` | диаграмма ARIS eEPC. Параметры: `set`, `data=1` (объекты данных и потоки), `events=0` (без событий-чек-поинтов), `stages`, `download=1` |
|
||||
| GET | `/api/model` | JSON: строки процесса, роли, системы, объекты данных и рассчитанные сроки (`schedule.timings`, `schedule.warnings`) |
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
| Таблица | Колонки |
|
||||
|---|---|
|
||||
| `khbuild_process` | `id` PK (номер Дмитрия `CP-0`…`CP-17`, новые шаги `S-001`…), `stage`, `action_name`, `action_description`, `responsible_role`, `responsible_name`, `system_as_is`, `system_to_be`, `data_in1..3`, `data_out1..3`, `depends_on`, `depends_on2`, `depends_on3` (FK на `khbuild_process.id`), `duration`, `date_constraint` (дни от kick-off: `день 7`, `не позже дня 7`, `день 45–47`, `день 80 → день 90`, `еженедельно`), `questions` (открытые вопросы по шагу) |
|
||||
| `khbuild_process` | `id` PK (номер Дмитрия `CP-0`…`CP-17`, новые шаги `S-001`…), `stage`, `action_name`, `action_description`, `responsible_role`, `responsible_name`, `system_as_is`, `system_to_be`, `data_in1..3`, `data_out1..3`, `depends_on`, `depends_on2`, `depends_on3` (FK на `khbuild_process.id`), `duration`, `date_constraint` (дни от kick-off: `день 7`, `не позже дня 7`, `день 45–47`, `день 80 → день 90`, `еженедельно`), `questions` (открытые вопросы по шагу), `is_milestone` (boolean, по умолчанию `false`: признак вехи; у чек-пойнтов `CP-*` стоит `true`, любую другую строку можно пометить вручную в Mathesar/NocoDB - она появится вехой на сводной полосе группы в Ганте) |
|
||||
| `khbuild_roles` | `id` PK, `role_person`, `comment` |
|
||||
| `khbuild_systems` | `id` PK, `system_name`, `comment` |
|
||||
| `khbuild_data_objects` | `id` PK, `data_description`, `responsible_role`, `comment` |
|
||||
@@ -12,3 +12,5 @@
|
||||
Владелец таблиц - роль `mathesar_process`; права и RLS как у прежних таблиц (`khb_app`, `service_role`, `authenticated`, `anon` - все права; `nocodb_process` на `khbuild_process`). Таблицы создаются вне миграций `khb_common`: сервис не должен падать, если их нет (признак `db` в `/healthz` не влияет на `ok`).
|
||||
|
||||
Доступ роли `khb_app` (под ней работают все сервисы): на таблицах включён RLS, поэтому кроме права `select` нужна политика. Вручную, от суперпользователя (`docker exec supabase-db psql -U supabase_admin`), для каждой из восьми таблиц `khbuild_*` и `khnata_*` создана `CREATE POLICY khb_app_read ON public.<таблица> FOR SELECT TO khb_app USING (true)`. Без неё сервис видит 0 строк. Новую таблицу «звезды» нужно подключать так же.
|
||||
|
||||
Если колонки `is_milestone` нет (архив `khnata_*`), визуализатор считает вехами строки с id `CP-*`.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
`GET /healthz` (без авторизации), `GET /`, `/gantt.svg`, `/aris.svg`, `/api/model` - токен `khbuild_process_viz.http.token`. Подробно: [api_objects.md](../../../docs/proposed/data_objects/khbuild_process_viz/api_objects.md). Для людей сервис открыт через `https://reports.khbuild.freeddns.org/viz/?view=gantt` (или `view=aris`) за входом Keycloak/Google (любой пользователь `@khbuild.pro`), список ссылок - пакет `reports`. Токен подставляет nginx. Прямой доступ (отладка): порт 127.0.0.1:8086, SSH-туннель `ssh -L 8086:127.0.0.1:8086 khbuild-vps` и `http://127.0.0.1:8086/?token=<token>`.
|
||||
|
||||
## Как читать диаграммы
|
||||
- **Гант**: ось - дни от первой встречи клиента с архитектором (kick-off = день 0), при заданной дате kick-off на оси календарные даты. Ромб - чек-поинт или веха, полоса - работа, штриховка - повторяющийся шаг (`еженедельно`/`ежедневно`), пунктир - срок «не позже / около», красная обводка - противоречие в сроках, бледная строка - срок выведен из зависимостей, а не задан, жёлтая точка - есть открытый вопрос (текст в подсказке).
|
||||
- **Гант**: ось - дни от первой встречи клиента с архитектором (kick-off = день 0), при заданной дате kick-off на оси календарные даты. Каждый этап - группа со **сводной штрихованной полосой** (от начала до конца этапа) в строке с названием; на полосе ромбами отмечены **вехи** (строки с признаком `is_milestone`, по дате завершения), над ромбами - подписи (при тесноте уходят на верхние уровни или сокращаются до id), от вех вниз идут пунктирные направляющие. Клик по названию или полосе группы сворачивает и разворачивает её (остаётся только сводная полоса), кнопки «Свернуть все» / «Развернуть все» управляют всеми группами. Кнопки «Время − / +» (и Shift + колесо мыши) меняют только масштаб оси времени, остальное (шрифты, интервалы, ширина левой колонки) не меняется; колесо без Shift по-прежнему масштабирует картинку целиком. Состояние (`px`, `collapsed`, вкладка) хранится в адресе страницы, ссылкой можно поделиться. Границы группы не растягивают повторяющиеся шаги и шаги без срока. Остальные обозначения: Ромб - чек-поинт или веха, полоса - работа, штриховка - повторяющийся шаг (`еженедельно`/`ежедневно`), пунктир - срок «не позже / около», красная обводка - противоречие в сроках, бледная строка - срок выведен из зависимостей, а не задан, жёлтая точка - есть открытый вопрос (текст в подсказке).
|
||||
- **ARIS eEPC**: дорожки - роли (жёлтые овалы), зелёные функции - шаги (тёмные - чек-поинты), розовые шестиугольники - события «CP достигнут», синие метки - системы, голубые документы - объекты данных (параметр `data=1`).
|
||||
- Сроки считаются так: срок из `date_constraint`, иначе окончание предшественников (`depends_on*`) плюс `duration`. Если срок раньше окончания предшественников, появляется предупреждение (красная обводка и список на странице).
|
||||
|
||||
|
||||
@@ -9,13 +9,26 @@ export interface GanttOptions {
|
||||
deps?: boolean;
|
||||
/** показывать только эти этапы */
|
||||
stages?: string[] | null;
|
||||
/** масштаб времени: пикселей на день. Меняет только ось времени, шрифты и интервалы строк остаются прежними */
|
||||
px?: number;
|
||||
/** свёрнутые группы (этапы): от них остаётся только сводная полоса */
|
||||
collapsed?: string[] | null;
|
||||
}
|
||||
|
||||
const LEFT = 420;
|
||||
const PX = 5; // пикселей на день
|
||||
/** Ширина левой колонки с названиями; не зависит от масштаба времени. */
|
||||
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 = 24;
|
||||
const HEAD = 76;
|
||||
const STAGE_ROW = 24;
|
||||
const GROUP_BAR_H = 14; // высота сводной полосы
|
||||
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`);
|
||||
@@ -24,11 +37,16 @@ const addDays = (iso: string, days: number): string | null => {
|
||||
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));
|
||||
};
|
||||
|
||||
/** Порядок этапов: по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
|
||||
export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
|
||||
const key = new Map<string, number>();
|
||||
for (const r of rows) {
|
||||
const s = r.stage ?? "(без этапа)";
|
||||
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);
|
||||
@@ -40,134 +58,254 @@ export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
|
||||
return [...key.entries()].sort((a, b) => a[1] - b[1]).map(([s]) => s);
|
||||
}
|
||||
|
||||
export interface GroupSummary {
|
||||
stage: string;
|
||||
/** границы сводной полосы (дни) */
|
||||
start: number;
|
||||
end: number;
|
||||
/** вехи группы: строки с признаком is_milestone, по дате завершения */
|
||||
milestones: Array<{ row: ProcessRow; day: 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 }));
|
||||
return { stage, start: Number.isFinite(start) ? start : 0, end: Number.isFinite(end) ? end : 0, milestones };
|
||||
}
|
||||
|
||||
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 color = (stage: string) => PALETTE[stages.indexOf(stage) % PALETTE.length] ?? PALETTE[0]!;
|
||||
const colorIdx = (stage: string) => Math.max(0, stages.indexOf(stage)) % PALETTE.length;
|
||||
const color = (stage: string) => PALETTE[colorIdx(stage)] ?? 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]);
|
||||
const x = (d: number) => GANTT_LEFT + d * px;
|
||||
|
||||
// Строки: заголовок этапа, затем его шаги по началу
|
||||
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)
|
||||
// Группы: строки этапа по началу
|
||||
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 }));
|
||||
for (const x of rs) lines.push({ kind: "row", ...x });
|
||||
}
|
||||
const summary = summarizeGroup(stage, rows);
|
||||
const { labels, levels } = placeLabels(summary.milestones.map((m) => ({ x: x(m.day), row: m.row })));
|
||||
const headH = 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;
|
||||
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;
|
||||
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 + ROW / 2);
|
||||
y += ROW;
|
||||
}
|
||||
}
|
||||
g.bottom = y;
|
||||
}
|
||||
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 labelRight = Math.max(0, ...groups.flatMap((g) => g.labels.map((l) => l.x + (l.text.length * CHAR_W) / 2)));
|
||||
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>`);
|
||||
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"/>`);
|
||||
|
||||
// Ось: шаг подписей выбирается так, чтобы подписи не слипались при любом масштабе
|
||||
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 += 30) {
|
||||
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 out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
|
||||
else if (d % 30 === 0) 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"/>`);
|
||||
// Подложки групп и направляющие вех
|
||||
for (const g of groups) {
|
||||
const c = color(g.stage);
|
||||
out.push(`<rect x="0" y="${g.top}" width="${width}" height="${g.headH}" fill="${c.fill}" opacity="0.45"/>`);
|
||||
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"/>`);
|
||||
}
|
||||
}
|
||||
|
||||
// Зависимости под полосами
|
||||
// Зависимости под полосами (только между видимыми строками)
|
||||
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)"/>`);
|
||||
for (const g of groups) {
|
||||
for (const { row, t } of g.rows) {
|
||||
for (const dep of row.dependsOn) {
|
||||
const dt = schedule.timings.get(dep);
|
||||
const y1 = yOf.get(dep);
|
||||
const y2 = yOf.get(row.id);
|
||||
if (!dt || y1 === undefined || y2 === undefined) continue;
|
||||
const x1 = x(dt.end);
|
||||
const x2 = x(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;
|
||||
// Строки раскрытых групп
|
||||
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 + ROW / 2;
|
||||
const warn = conflicts.get(row.id);
|
||||
const tip = tooltip([
|
||||
`${row.id} - ${row.actionName ?? ""}${row.isMilestone ? " (веха)" : ""}`,
|
||||
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 ms = row.isMilestone;
|
||||
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(row.actionName ?? row.description ?? "", 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"' : "";
|
||||
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 {
|
||||
if (t.end > t.start) {
|
||||
out.push(`<rect x="${x(t.start)}" y="${cy - 7}" width="${Math.max(3, (t.end - t.start) * px)}" height="14" rx="3" fill="${ms ? c.stroke : c.fill}" fill-opacity="${ms ? 0.55 : 1}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
|
||||
}
|
||||
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="${ms ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${ms ? 1.5 : 1}"${dash}/>`);
|
||||
out.push(`<text x="${px0 + 12}" y="${cy + 4}" fill="#555" font-size="11">день ${t.end}</text>`);
|
||||
} else {
|
||||
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 { row, t } = l;
|
||||
const c = color(row.stage ?? "(без этапа)");
|
||||
const cy = top + ROW / 2;
|
||||
const warn = conflicts.get(row.id);
|
||||
}
|
||||
|
||||
// Строки групп: название слева (клик сворачивает), сводная полоса с вехами справа
|
||||
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([
|
||||
`${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,
|
||||
`${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 ? "Клик - развернуть" : "Клик - свернуть",
|
||||
]);
|
||||
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 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"/>`);
|
||||
out.push(`<text x="10" y="${cy + 5}" font-size="14" fill="${c.stroke}">${g.collapsed ? "▸" : "▾"}</text>`);
|
||||
out.push(`<text x="28" y="${cy + 5}" font-weight="700" fill="${c.stroke}">${esc(truncate(g.stage, 34))}<tspan dx="6" font-weight="400" fill="#667085">(${g.rows.length})</tspan></text>`);
|
||||
out.push("</g>");
|
||||
out.push(`<g>${tip}`);
|
||||
out.push(`<rect x="${x(s.start)}" y="${barY}" width="${Math.max(2, (s.end - s.start) * px)}" height="${GROUP_BAR_H}" rx="2" fill="url(#gh${colorIdx(g.stage)})" 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="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>`,
|
||||
`<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="url(#gh0)" stroke="#3b7dc4"/><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="url(#hatch)" 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 hatches = stages
|
||||
.map((_, i) => {
|
||||
const c = PALETTE[i % PALETTE.length]!;
|
||||
return `<pattern id="gh${i}" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="7" height="7" fill="${c.fill}"/><line x1="0" y1="0" x2="0" y2="7" stroke="${c.stroke}" stroke-width="2.4"/></pattern>`;
|
||||
})
|
||||
.join("");
|
||||
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"));
|
||||
`<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>` +
|
||||
hatches +
|
||||
// запасной шаблон для легенды, если этапов нет
|
||||
(stages.length ? "" : `<pattern id="gh0" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="7" height="7" fill="#cfe8ff"/><line x1="0" y1="0" x2="0" y2="7" stroke="#3b7dc4" stroke-width="2.4"/></pattern>`);
|
||||
return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,11 @@ body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.4 "Segoe UI",Aria
|
||||
header{padding:10px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;background:var(--panel)}
|
||||
h1{font-size:16px;margin:0 8px 0 0}
|
||||
a.back{color:var(--acc);text-decoration:none;margin-right:4px}
|
||||
button.sm{border:1px solid var(--line);background:var(--bg);color:var(--fg);border-radius:6px;padding:3px 9px;cursor:pointer;font:inherit}
|
||||
button.sm:hover{border-color:var(--acc)}
|
||||
#gCtl{display:inline-flex;gap:6px 10px;align-items:center;flex-wrap:wrap}
|
||||
.tz{display:inline-flex;gap:4px;align-items:center;color:var(--mut)}
|
||||
#pxv{min-width:64px;text-align:center;color:var(--fg)}
|
||||
.tabs button{border:1px solid var(--line);background:var(--bg);color:var(--fg);padding:6px 14px;cursor:pointer}
|
||||
.tabs button:first-child{border-radius:6px 0 0 6px}
|
||||
.tabs button:last-child{border-radius:0 6px 6px 0;border-left:0}
|
||||
@@ -45,6 +50,13 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
<label class="chk"><input type="checkbox" id="deps" checked> зависимости</label>
|
||||
<label class="chk" id="lEv"><input type="checkbox" id="events" checked> события</label>
|
||||
<label class="chk" id="lData"><input type="checkbox" id="data"> объекты данных</label>
|
||||
<span id="gCtl">
|
||||
<button class="sm" id="colAll" title="Свернуть все группы">Свернуть все</button>
|
||||
<button class="sm" id="expAll" title="Развернуть все группы">Развернуть все</button>
|
||||
<span class="tz" title="Масштаб только оси времени. Shift + колесо мыши - то же">Время:
|
||||
<button class="sm" id="tzm">−</button><b id="pxv"></b><button class="sm" id="tzp">+</button><button class="sm" id="tz0" title="Сбросить масштаб времени">↺</button>
|
||||
</span>
|
||||
</span>
|
||||
<details><summary>Этапы</summary><div class="stagebox">${stages}</div></details>
|
||||
<a class="btn" id="dl" href="#">SVG</a>
|
||||
</div>
|
||||
@@ -53,9 +65,14 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
<div id="view"><div id="msg">Загрузка…</div><div id="stage"></div></div>
|
||||
<script>
|
||||
(function () {
|
||||
var tab = 'gantt', k = 1, tx = 8, ty = 8;
|
||||
var PX0 = 5, PXMIN = 0.5, PXMAX = 40;
|
||||
var tab = 'gantt', k = 1, tx = 8, ty = 8, px = PX0, collapsed = {};
|
||||
var $ = function (i) { return document.getElementById(i); };
|
||||
var stage = $('stage'), view = $('view');
|
||||
var urlp = new URLSearchParams(location.search);
|
||||
if (urlp.get('px') && +urlp.get('px') > 0) px = Math.min(PXMAX, Math.max(PXMIN, +urlp.get('px')));
|
||||
(urlp.get('collapsed') || '').split('|').filter(Boolean).forEach(function (s) { collapsed[s] = 1; });
|
||||
function collapsedList() { return Object.keys(collapsed); }
|
||||
function qs() {
|
||||
var p = new URLSearchParams();
|
||||
p.set('set', $('set').value);
|
||||
@@ -64,48 +81,97 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
if (tab === 'aris') {
|
||||
if (!$('events').checked) p.set('events', '0');
|
||||
if ($('data').checked) p.set('data', '1');
|
||||
} else {
|
||||
if (Math.abs(px - PX0) > 1e-6) p.set('px', String(Math.round(px * 100) / 100));
|
||||
if (collapsedList().length) p.set('collapsed', collapsedList().join('|'));
|
||||
}
|
||||
var all = [].slice.call(document.querySelectorAll('.stage'));
|
||||
var on = all.filter(function (c) { return c.checked; }).map(function (c) { return c.value; });
|
||||
if (on.length && on.length < all.length) p.set('stages', on.join('|'));
|
||||
return p.toString();
|
||||
}
|
||||
function syncUrl() {
|
||||
var p = new URLSearchParams(); p.set('view', tab);
|
||||
if (tab === 'gantt') {
|
||||
if (Math.abs(px - PX0) > 1e-6) p.set('px', String(Math.round(px * 100) / 100));
|
||||
if (collapsedList().length) p.set('collapsed', collapsedList().join('|'));
|
||||
}
|
||||
try { history.replaceState(null, '', '?' + p.toString()); } catch (e) {}
|
||||
}
|
||||
function place() { stage.style.transform = 'translate(' + tx + 'px,' + ty + 'px) scale(' + k + ')'; }
|
||||
function load() {
|
||||
function showPx() { $('pxv').textContent = (Math.round(px * 10) / 10) + ' px/дн'; }
|
||||
// load(newTx): newTx применяется вместе с новой картинкой, чтобы не было скачка
|
||||
function load(newTx) {
|
||||
var u = tab + '.svg?' + qs(); // относительный адрес: страница работает и на корне, и под префиксом /viz/
|
||||
$('dl').href = u + '&download=1';
|
||||
$('msg').textContent = 'Загрузка…';
|
||||
$('msg').style.display = '';
|
||||
fetch(u, { credentials: 'same-origin' })
|
||||
.then(function (r) { if (!r.ok) throw new Error(r.status); return r.text(); })
|
||||
.then(function (t) { stage.innerHTML = t; $('msg').style.display = 'none'; place(); })
|
||||
.then(function (t) { stage.innerHTML = t; $('msg').style.display = 'none'; if (typeof newTx === 'number') tx = newTx; place(); })
|
||||
.catch(function (e) { $('msg').textContent = 'Ошибка загрузки (' + e.message + '). Если истёк вход - обновите страницу.'; });
|
||||
}
|
||||
// Масштаб только времени: перерисовка на сервере с другим px; шрифты и высота строк не меняются. Точка под центром окна остаётся на месте.
|
||||
var pxTimer = null;
|
||||
function setPx(n) {
|
||||
n = Math.min(PXMAX, Math.max(PXMIN, n));
|
||||
if (Math.abs(n - px) < 1e-6) return;
|
||||
var svg = stage.querySelector('svg');
|
||||
var left = svg ? +svg.getAttribute('data-left') : 420, cur = svg ? +svg.getAttribute('data-px') : px;
|
||||
var cx = view.clientWidth / 2, sx = (cx - tx) / k, day = (sx - left) / cur;
|
||||
px = n; showPx(); syncUrl();
|
||||
var nt = cx - (left + day * px) * k;
|
||||
clearTimeout(pxTimer);
|
||||
pxTimer = setTimeout(function () { load(nt); }, 90);
|
||||
}
|
||||
function setTab(t) {
|
||||
tab = t;
|
||||
$('tG').className = t === 'gantt' ? 'on' : '';
|
||||
$('tA').className = t === 'aris' ? 'on' : '';
|
||||
$('lEv').style.display = $('lData').style.display = t === 'aris' ? '' : 'none';
|
||||
$('gCtl').style.display = t === 'gantt' ? '' : 'none';
|
||||
document.title = 'khbuild_process — ' + (t === 'aris' ? 'ARIS' : 'Gantt');
|
||||
try { history.replaceState(null, '', '?view=' + t); } catch (e) {}
|
||||
syncUrl(); showPx();
|
||||
k = 1; tx = 8; ty = 8;
|
||||
load();
|
||||
}
|
||||
function toggleStage(name) {
|
||||
if (collapsed[name]) delete collapsed[name]; else collapsed[name] = 1;
|
||||
syncUrl(); load();
|
||||
}
|
||||
$('tG').onclick = function () { setTab('gantt'); };
|
||||
$('tA').onclick = function () { setTab('aris'); };
|
||||
['set', 'kick', 'deps', 'events', 'data'].forEach(function (i) { $(i).onchange = load; });
|
||||
[].forEach.call(document.querySelectorAll('.stage'), function (c) { c.onchange = load; });
|
||||
$('colAll').onclick = function () {
|
||||
[].forEach.call(document.querySelectorAll('.stage'), function (c) { collapsed[c.value] = 1; });
|
||||
syncUrl(); load();
|
||||
};
|
||||
$('expAll').onclick = function () { collapsed = {}; syncUrl(); load(); };
|
||||
$('tzp').onclick = function () { setPx(px * 1.25); };
|
||||
$('tzm').onclick = function () { setPx(px / 1.25); };
|
||||
$('tz0').onclick = function () { setPx(PX0); };
|
||||
['set', 'kick', 'deps', 'events', 'data'].forEach(function (i) { $(i).onchange = function () { load(); }; });
|
||||
[].forEach.call(document.querySelectorAll('.stage'), function (c) { c.onchange = function () { load(); }; });
|
||||
view.addEventListener('wheel', function (e) {
|
||||
e.preventDefault();
|
||||
var dd = e.deltaY || e.deltaX;
|
||||
if (e.shiftKey && tab === 'gantt') { setPx(px * (dd < 0 ? 1.15 : 1 / 1.15)); return; }
|
||||
var r = view.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
|
||||
var nk = Math.min(4, Math.max(0.15, k * (e.deltaY < 0 ? 1.12 : 1 / 1.12)));
|
||||
var nk = Math.min(4, Math.max(0.15, k * (dd < 0 ? 1.12 : 1 / 1.12)));
|
||||
tx = mx - (mx - tx) * nk / k; ty = my - (my - ty) * nk / k; k = nk; place();
|
||||
}, { passive: false });
|
||||
var drag = null;
|
||||
view.addEventListener('pointerdown', function (e) { drag = { x: e.clientX - tx, y: e.clientY - ty }; view.classList.add('drag'); view.setPointerCapture(e.pointerId); });
|
||||
view.addEventListener('pointerdown', function (e) { drag = { x: e.clientX - tx, y: e.clientY - ty, sx: e.clientX, sy: e.clientY }; view.classList.add('drag'); view.setPointerCapture(e.pointerId); });
|
||||
view.addEventListener('pointermove', function (e) { if (!drag) return; tx = e.clientX - drag.x; ty = e.clientY - drag.y; place(); });
|
||||
view.addEventListener('pointerup', function () { drag = null; view.classList.remove('drag'); });
|
||||
setTab(new URLSearchParams(location.search).get('view') === 'aris' ? 'aris' : 'gantt');
|
||||
view.addEventListener('pointerup', function (e) {
|
||||
var moved = drag ? Math.abs(e.clientX - drag.sx) + Math.abs(e.clientY - drag.sy) : 99;
|
||||
drag = null; view.classList.remove('drag');
|
||||
if (moved < 4 && tab === 'gantt') {
|
||||
var el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
var t = el && el.closest ? el.closest('[data-toggle]') : null;
|
||||
if (t) toggleStage(t.getAttribute('data-toggle'));
|
||||
}
|
||||
});
|
||||
setTab(urlp.get('view') === 'aris' ? 'aris' : 'gantt');
|
||||
})();
|
||||
</script></body></html>`;
|
||||
}
|
||||
|
||||
@@ -81,7 +81,9 @@ export function buildApi(deps: ProcessVizApiDeps): FastifyInstance {
|
||||
app.get("/gantt.svg", async (req, reply) => {
|
||||
const q = req.query as Query;
|
||||
const model = await deps.load(setOf(q));
|
||||
const svg = renderGantt(model, computeSchedule(model.rows), { kickoff: q.kickoff ?? null, deps: q.deps !== "0", stages: stagesOf(q) });
|
||||
const px = q.px !== undefined && q.px !== "" ? Number(q.px) : undefined;
|
||||
const collapsed = q.collapsed ? q.collapsed.split("|").filter(Boolean) : null;
|
||||
const svg = renderGantt(model, computeSchedule(model.rows), { kickoff: q.kickoff ?? null, deps: q.deps !== "0", stages: stagesOf(q), px, collapsed });
|
||||
return svgReply(reply, svg, `process_gantt_${model.set}.svg`, q);
|
||||
});
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface ProcessRow {
|
||||
duration: string | null;
|
||||
dateConstraint: string | null;
|
||||
questions: string | null;
|
||||
/** признак вехи: колонка is_milestone; если колонки нет или она пустая - вехами считаются чек-поинты CP-* */
|
||||
isMilestone: boolean;
|
||||
}
|
||||
export interface RoleRow { id: string; person: string | null; comment: string | null }
|
||||
export interface SystemRow { id: string; name: string | null; comment: string | null }
|
||||
@@ -52,6 +54,7 @@ export function mapRow(r: Raw): ProcessRow {
|
||||
duration: str(r.duration),
|
||||
dateConstraint: str(r.date_constraint),
|
||||
questions: str(r.questions),
|
||||
isMilestone: typeof r.is_milestone === "boolean" ? r.is_milestone : /^CP-/.test(String(r.id)),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -38,8 +38,14 @@ export const PALETTE: ReadonlyArray<{ fill: string; stroke: string }> = [
|
||||
{ fill: "#f3efb0", stroke: "#a39a1c" },
|
||||
];
|
||||
|
||||
export function svgDoc(width: number, height: number, defs: string, body: string): string {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="Segoe UI, Arial, sans-serif" font-size="12">\n<defs>${defs}</defs>\n<rect width="${width}" height="${height}" fill="#ffffff"/>\n${body}\n</svg>\n`;
|
||||
export function svgDoc(width: number, height: number, defs: string, body: string, attrs = ""): string {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="Segoe UI, Arial, sans-serif" font-size="12"${attrs ? " " + attrs : ""}>
|
||||
<defs>${defs}</defs>
|
||||
<rect width="${width}" height="${height}" fill="#ffffff"/>
|
||||
${body}
|
||||
</svg>
|
||||
`;
|
||||
}
|
||||
|
||||
export function tooltip(parts: Array<string | null | undefined>): string {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderAris } from "./aris.js";
|
||||
import { renderGantt, stageOrder } from "./gantt.js";
|
||||
import { clampPx, placeLabels, renderGantt, stageOrder, summarizeGroup } from "./gantt.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { mapRow, type ProcessModel } from "./model.js";
|
||||
import { computeSchedule, parseConstraint, parseDuration } from "./schedule.js";
|
||||
@@ -106,6 +106,94 @@ describe("renderGantt", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Гант: группы, вехи, свёртывание, масштаб времени", () => {
|
||||
const ms: ProcessModel = {
|
||||
...model,
|
||||
rows: [
|
||||
row({ id: "CP-0", stage: "A", action_name: "Старт", date_constraint: "день 0" }),
|
||||
row({ id: "S-1", stage: "A", action_name: "Работа", depends_on: "CP-0", date_constraint: "день 0 → день 20" }),
|
||||
row({ id: "S-2", stage: "A", action_name: "Обычный шаг", depends_on: "S-1", date_constraint: "день 25", is_milestone: false }),
|
||||
row({ id: "X-9", stage: "A", action_name: "Своя веха", depends_on: "S-1", date_constraint: "день 30", is_milestone: true }),
|
||||
row({ id: "S-3", stage: "B", action_name: "Другое", depends_on: "X-9", duration: "10 дней" }),
|
||||
],
|
||||
};
|
||||
const sch = computeSchedule(ms.rows);
|
||||
|
||||
it("признак вехи: колонка is_milestone, а без неё чек-поинты CP-*", () => {
|
||||
const byId = new Map(ms.rows.map((r) => [r.id, r.isMilestone]));
|
||||
expect(byId.get("CP-0")).toBe(true); // колонки нет -> по префиксу
|
||||
expect(byId.get("S-2")).toBe(false);
|
||||
expect(byId.get("X-9")).toBe(true); // явный признак
|
||||
expect(row({ id: "CP-5", is_milestone: false }).isMilestone).toBe(false); // явное «нет» сильнее префикса
|
||||
});
|
||||
|
||||
it("сводка группы: границы и вехи по датам завершения", () => {
|
||||
const rows = ms.rows.filter((r) => r.stage === "A").map((r) => ({ row: r, t: sch.timings.get(r.id)! }));
|
||||
const g = summarizeGroup("A", rows);
|
||||
expect([g.start, g.end]).toEqual([0, 30]);
|
||||
expect(g.milestones.map((m) => [m.row.id, m.day])).toEqual([["CP-0", 0], ["X-9", 30]]);
|
||||
});
|
||||
|
||||
it("повторяющиеся шаги и шаги без срока не растягивают группу", () => {
|
||||
const rows = [row({ id: "R", date_constraint: "еженедельно" }), row({ id: "Q", date_constraint: "день 10 → день 20" }), row({ id: "Z" })];
|
||||
const s2 = computeSchedule(rows);
|
||||
const g = summarizeGroup("G", rows.map((r) => ({ row: r, t: s2.timings.get(r.id)! })).concat([]));
|
||||
expect([g.start, g.end]).toEqual([10, 20]);
|
||||
});
|
||||
|
||||
it("подписи вех не налезают друг на друга: близкие вехи уходят на другой уровень или сокращаются до id", () => {
|
||||
const r = (id: string) => row({ id, action_name: "Очень длинное название вехи" });
|
||||
const { labels, levels } = placeLabels([{ x: 100, row: r("CP-1") }, { x: 110, row: r("CP-2") }, { x: 500, row: r("CP-3") }]);
|
||||
expect(labels).toHaveLength(3);
|
||||
expect(levels).toBeGreaterThanOrEqual(2);
|
||||
expect(labels.find((l) => l.row.id === "CP-3")?.level).toBe(0);
|
||||
expect(labels.find((l) => l.row.id === "CP-3")?.text).toContain("Очень длинное");
|
||||
});
|
||||
|
||||
it("свёрнутая группа остаётся одной сводной строкой, развёрнутые строки и направляющие остаются", () => {
|
||||
const open = renderGantt(ms, sch, {});
|
||||
const shut = renderGantt(ms, sch, { collapsed: ["A"] });
|
||||
expect(open).toContain(">S-2<");
|
||||
expect(shut).not.toContain(">S-2<");
|
||||
expect(shut).toContain(">S-3<"); // группа B осталась раскрытой
|
||||
expect(shut).toContain('data-toggle="A"'); // группа по-прежнему кликабельна
|
||||
expect(shut).toContain("▸");
|
||||
expect(open).toContain("▾");
|
||||
expect(open).toContain("stroke-dasharray=\"4 4\""); // направляющие вех
|
||||
expect(shut.split("\n").filter((l) => l.includes('stroke-dasharray="4 4"')).length).toBeLessThan(open.split("\n").filter((l) => l.includes('stroke-dasharray="4 4"')).length);
|
||||
expect(open).toContain("X-9 · Своя веха"); // подпись над вехой
|
||||
expect(shut.match(/<svg[^>]*height="(\d+)"/)![1]!).not.toBe(open.match(/<svg[^>]*height="(\d+)"/)![1]!);
|
||||
});
|
||||
|
||||
it("масштаб времени меняет только ось: ширина растёт, шрифты и высота остаются", () => {
|
||||
const a = renderGantt(ms, sch, { px: 5 });
|
||||
const b = renderGantt(ms, sch, { px: 20 });
|
||||
const attr = (svg: string, n: string) => Number(svg.match(new RegExp(`<svg[^>]*\\s${n}="([\\d.]+)"`))![1]);
|
||||
expect(attr(b, "width")).toBeGreaterThan(attr(a, "width"));
|
||||
expect(attr(b, "height")).toBe(attr(a, "height"));
|
||||
expect(a).toContain('data-px="5"');
|
||||
expect(b).toContain('data-px="20"');
|
||||
expect(a).toContain('data-left="420"');
|
||||
const fonts = (svg: string) => [...new Set([...svg.matchAll(/font-size="(\d+)"/g)].map((m) => m[1]))].sort().join(","); // набор размеров, а не их число: подписей на оси больше или меньше
|
||||
expect(fonts(b)).toBe(fonts(a));
|
||||
expect(clampPx(1000)).toBe(40);
|
||||
expect(clampPx(0)).toBe(0.5);
|
||||
expect(clampPx(undefined)).toBe(5);
|
||||
});
|
||||
|
||||
it("API: параметры px и collapsed", async () => {
|
||||
const app2 = buildApi({ token: "t", defaultSet: "khbuild", load: async () => ms, dbOk: async () => true });
|
||||
const h = { authorization: "Bearer t" };
|
||||
const svg = (await app2.inject({ url: "/gantt.svg?px=12&collapsed=A", headers: h })).body;
|
||||
expect(svg).toContain('data-px="12"');
|
||||
expect(svg).not.toContain(">S-2<");
|
||||
const page = (await app2.inject({ url: "/", headers: h })).body;
|
||||
expect(page).toContain('id="colAll"');
|
||||
expect(page).toContain('id="expAll"');
|
||||
expect(page).toContain('id="tzp"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderAris", () => {
|
||||
it("рисует дорожки ролей, функции, события и системы", () => {
|
||||
const svg = renderAris(model, computeSchedule(model.rows), {});
|
||||
|
||||
Reference in New Issue
Block a user