Files
khb_microservices/packages/khbuild_process_viz/src/viz.test.ts
Yuri Yaryshev 538849e300
All checks were successful
ci / test (push) Successful in 25s
ci / deploy (push) Successful in 2m7s
Гант: предшественники с отрицательным днём не дают ложного противоречия сроков
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 19:14:03 +03:00

538 lines
35 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 { describe, expect, it } from "vitest";
import { renderPage } from "./html.js";
import { renderAris } from "./aris.js";
import { clampPx, placeLabels, redundantDependencies, renderGantt, stageOrder, summarizeGroup } from "./gantt.js";
import { buildApi } from "./http-api.js";
import { buildModel, describeResponsible, loadModel, mapRow, type ProcessModel } from "./model.js";
import { computeSchedule, parseConstraint, parseDuration, parseDurationInfo } from "./schedule.js";
const row = (o: Record<string, unknown>) => mapRow({ id: "X", ...o });
describe("parseConstraint", () => {
it("разбирает форматы из процесса", () => {
expect(parseConstraint("день 0")).toMatchObject({ start: null, end: 0, exact: true });
expect(parseConstraint("день -2 → день -1")).toMatchObject({ start: -2, end: -1 });
expect(parseConstraint("день 0-44")).toMatchObject({ start: 0, end: 44 });
expect(parseConstraint("не позже дня 7")).toMatchObject({ end: 7, exact: false });
expect(parseConstraint("около дня 45")).toMatchObject({ end: 45, exact: false });
expect(parseConstraint("день 45–47")).toMatchObject({ start: 45, end: 47 });
expect(parseConstraint("день 80 → день 90")).toMatchObject({ start: 80, end: 90 });
expect(parseConstraint("день 45–47 → день 108")).toMatchObject({ start: 47, end: 108 });
expect(parseConstraint("день 120 по коробке и экстерьеру; день 135 по интерьеру")).toMatchObject({ start: 120, end: 135 });
expect(parseConstraint("еженедельно, пятница утром").recurring).toBe("weekly");
expect(parseConstraint("ежедневно, утром").recurring).toBe("daily");
expect(parseConstraint(null)).toMatchObject({ start: null, end: null });
});
});
describe("parseDuration", () => {
it("переводит в дни", () => {
expect(parseDuration("4 недели")).toBe(28);
expect(parseDuration("до 9 недель")).toBe(63);
expect(parseDuration("10 дней")).toBe(10);
expect(parseDuration("~3 месяца")).toBe(90);
expect(parseDuration("30d")).toBe(30);
expect(parseDuration("3 рабочих дня")).toBeNull();
expect(parseDuration(null)).toBeNull();
});
});
describe("каноническая длительность", () => {
it("5d - календарные дни, 5wd - рабочие (5 рабочих = 7 календарных), ? - оценка, при расчёте игнорируется", () => {
expect(parseDurationInfo("5d")).toEqual({ amount: 5, unit: "d", uncertain: false, days: 5 });
expect(parseDurationInfo("30d?")).toMatchObject({ days: 30, uncertain: true });
expect(parseDurationInfo("5wd")).toMatchObject({ unit: "wd", days: 7, uncertain: false });
expect(parseDurationInfo("10wd")).toMatchObject({ days: 14 });
expect(parseDurationInfo("2wd?")).toMatchObject({ days: 3, uncertain: true });
expect(parseDurationInfo("0d")).toMatchObject({ days: 0 });
expect(parseDurationInfo("1.5d")).toMatchObject({ amount: 1.5 });
expect(parseDuration("30d?")).toBe(30);
expect(parseDuration("10wd")).toBe(14);
});
it("прежние текстовые значения архива по-прежнему читаются", () => {
expect(parseDurationInfo("4 недели")).toMatchObject({ days: 28 });
expect(parseDurationInfo("~3 месяца")).toMatchObject({ days: 90, uncertain: true });
expect(parseDurationInfo("TBD")).toBeNull();
});
it("вопросик не влияет на расписание, но выводится в Ганте и ARIS", () => {
const rows = [row({ id: "A", stage: "S", action_name: "Работа", duration: "28d?", date_constraint: "день 0 → день 28" }), row({ id: "B", stage: "S", action_name: "Ещё", duration: "28d", date_constraint: "день 0 → день 28" })];
const sch = computeSchedule(rows);
expect(sch.timings.get("A")).toMatchObject({ start: 0, end: 28 });
expect(sch.warnings).toEqual([]);
const m: ProcessModel = { ...model, rows };
expect(renderGantt(m, sch, {})).toContain("A · 28d?");
expect(renderGantt(m, sch, {})).toContain("B · 28d<");
expect(renderAris(m, sch, {})).toContain(">28d?<");
});
it("рабочие дни в расписании переводятся в календарные", () => {
const sch = computeSchedule([row({ id: "A", duration: "10wd" }), row({ id: "B", depends_on: "A", duration: "5d" })]);
expect(sch.timings.get("A")).toMatchObject({ start: 0, end: 14 });
expect(sch.timings.get("B")).toMatchObject({ start: 14, end: 19 });
});
});
describe("справочник ответственных", () => {
const raw = {
process: [
{ id: "CP-0", responsible: "architect", responsible2: "arch_permit_lead", data_out1: "Plan" },
{ id: "S-1", responsible: "pm" },
{ id: "S-2" },
],
refs: [
{ id: "architect", role: "architect", person: "RIOS", comment: null },
{ id: "arch_permit_lead", role: "arch_permit_lead", person: "Андрей", comment: "уточнить" },
{ id: "specs_client_mgr", role: "specs_client_mgr", person: "Austin", comment: null },
{ id: "specs_client_mgr_2", role: "specs_client_mgr", person: "Маша", comment: "делит с Austin" },
{ id: "pm", role: "pm", person: "PM", comment: null },
],
legacyRoles: false,
systems: [],
data: [{ id: "Plan", data_description: "План", responsible: "architect", comment: null }],
};
it("колонки responsible, responsible2, responsible3 дают список ключей, роль берётся у первого", () => {
const m = buildModel("khbuild", raw);
expect(m.rows[0]).toMatchObject({ responsible: ["architect", "arch_permit_lead"], role: "architect", responsibleName: "RIOS; Андрей" });
expect(m.rows[1]).toMatchObject({ responsible: ["pm"], role: "pm" });
expect(m.rows[2]).toMatchObject({ responsible: [], role: null });
expect(describeResponsible(m.rows[0]!, m)).toBe("architect - RIOS; arch_permit_lead - Андрей");
expect(describeResponsible(m.rows[2]!, m)).toBe("не указан");
});
it("роли производны от справочника: имена одной роли собираются, комментарий берётся первый непустой", () => {
const m = buildModel("khbuild", raw);
const sc = m.roles.find((r) => r.id === "specs_client_mgr")!;
expect(sc.person).toBe("Austin, Маша");
expect(sc.comment).toBe("делит с Austin");
expect(m.roles.map((r) => r.id)).toEqual(["architect", "arch_permit_lead", "specs_client_mgr", "pm"]);
});
it("ответственный за объект данных берётся из справочника", () => {
expect(buildModel("khbuild", raw).data[0]).toMatchObject({ id: "Plan", role: "architect" });
});
it("прежняя схема (архив khnata): responsible_role / responsible_name и справочник ролей", () => {
const m = buildModel("khnata", {
process: [{ id: "S1001", responsible_role: "seller", responsible_name: "Arthur" }],
refs: [{ id: "seller", role_person: "Arthur", comment: null }],
legacyRoles: true,
systems: [],
data: [{ id: "D", responsible_role: "seller" }],
});
expect(m.rows[0]).toMatchObject({ responsible: [], role: "seller", responsibleName: "Arthur" });
expect(describeResponsible(m.rows[0]!, m)).toBe("Arthur / Arthur");
expect(m.roles).toEqual([{ id: "seller", person: "Arthur", comment: null }]);
expect(m.data[0]).toMatchObject({ role: "seller" });
});
it("loadModel: нет таблицы responsible (42P01) - читается прежний справочник ролей; другие ошибки пробрасываются", async () => {
const calls: string[] = [];
const db = {
query: async (sql: string) => {
calls.push(sql);
if (sql.includes("_responsible")) throw Object.assign(new Error("relation does not exist"), { code: "42P01" });
if (sql.includes("_roles")) return { rows: [{ id: "seller", role_person: "Arthur", comment: null }] };
if (sql.includes("_process")) return { rows: [{ id: "S1", responsible_role: "seller" }] };
return { rows: [] };
},
};
const m = await loadModel(db as never, "khnata");
expect(m.rows[0]?.role).toBe("seller");
expect(calls.some((c) => c.includes("khnata_responsible"))).toBe(true);
expect(calls.some((c) => c.includes("khnata_roles"))).toBe(true);
const bad = { query: async (sql: string) => { if (sql.includes("_responsible")) throw Object.assign(new Error("permission denied"), { code: "42501" }); return { rows: [] }; } };
await expect(loadModel(bad as never, "khbuild")).rejects.toThrow("permission denied");
});
});
describe("справочник этапов", () => {
it("название этапа берётся из справочника, без справочника остаётся значение колонки stage", () => {
const base = { refs: [], legacyRoles: false, systems: [], data: [] };
const withRef = buildModel("khbuild", { ...base, process: [{ id: "S1", stage: "st_arch" }, { id: "S2", stage: "нет в справочнике" }, { id: "S3" }], stages: [{ id: "st_arch", stage_name: "Архитектура", comment: "уточнить границы", ord: 40, color_fill: "#d4ece3", color_stroke: "#3f9a78" }] });
expect(withRef.rows.map((r) => r.stage)).toEqual(["Архитектура", "нет в справочнике", null]);
expect(withRef.stages).toEqual([{ id: "st_arch", name: "Архитектура", comment: "уточнить границы", ord: 40, fill: "#d4ece3", stroke: "#3f9a78" }]);
const without = buildModel("khnata", { ...base, process: [{ id: "S1", stage: "Architecture" }] });
expect(without.rows[0]?.stage).toBe("Architecture");
expect(without.stages).toEqual([]);
});
it("loadModel: нет таблицы stages (42P01) - читается без справочника", async () => {
const db = {
query: async (sql: string) => {
if (sql.includes("_stages")) throw Object.assign(new Error("relation does not exist"), { code: "42P01" });
if (sql.includes("_process")) return { rows: [{ id: "S1", stage: "A" }] };
return { rows: [] };
},
};
const m = await loadModel(db as never, "khbuild");
expect(m.rows[0]?.stage).toBe("A");
expect(m.stages).toEqual([]);
});
});
describe("computeSchedule", () => {
it("берёт срок из ограничения, остальное выводит по зависимостям", () => {
const rows = [
row({ id: "CP-0", date_constraint: "день 0" }),
row({ id: "S-1", depends_on: "CP-0", duration: "10 дней" }),
row({ id: "S-2", depends_on: "S-1" }),
row({ id: "CP-1", depends_on: "S-2", date_constraint: "не позже дня 7" }),
];
const { timings, warnings, maxDay } = computeSchedule(rows);
expect(timings.get("S-1")).toMatchObject({ start: 0, end: 10, kind: "task", fromConstraint: false });
expect(timings.get("S-2")).toMatchObject({ start: 10, end: 10, kind: "milestone" });
expect(timings.get("CP-1")).toMatchObject({ start: 10, end: 10, approx: true, deadline: 7 }); // веха на прогнозе, крайний срок отдельно
expect(maxDay).toBe(10);
expect(warnings).toEqual([{ id: "CP-1", message: expect.stringContaining("позже крайнего срока") }]);
});
it("предшественник до точки отсчёта (день < 0) не даёт ложного противоречия", () => {
const rows = [
row({ id: "A", date_constraint: "день -3 → день -2", duration: "1d" }),
row({ id: "B", depends_on: "A", date_constraint: "день -2 → день -1", duration: "1d" }),
];
const sc = computeSchedule(rows);
expect(sc.timings.get("B")).toMatchObject({ start: -2, end: -1 });
expect(sc.warnings).toEqual([]);
});
it("веха с крайним сроком стоит на прогнозе по предшественникам, а крайний срок рисуется красной чертой", () => {
const rows = [
row({ id: "CP-0", stage: "S", date_constraint: "день 0" }),
row({ id: "S-1", stage: "S", depends_on: "CP-0", duration: "5d" }),
row({ id: "CP-5", stage: "S", depends_on: "S-1", date_constraint: "не позже дня 75" }),
row({ id: "CP-3", stage: "S", depends_on: "CP-0", date_constraint: "около дня 45" }),
];
const sc = computeSchedule(rows);
expect(sc.timings.get("CP-5")).toMatchObject({ start: 5, end: 5, deadline: 75 });
expect(sc.timings.get("CP-3")).toMatchObject({ end: 45, deadline: null }); // «около» крайним сроком не считается
expect(sc.warnings).toEqual([]);
const svg = renderGantt({ ...model, rows }, sc, {});
expect(svg.split('stroke="#d32f2f" stroke-width="3"').length - 1).toBe(3); // черта у CP-5, в сводной полосе группы и знак в легенде
expect(svg).toContain("Крайний срок: день 75");
expect(svg).toContain("Крайний срок: CP-5, день 75"); // и в сводной полосе группы
expect(svg).toContain('stroke="#d32f2f" stroke-width="1" stroke-dasharray="3 3"'); // пунктир от ромба до красной черты
expect(svg).not.toContain('stroke="#d32f2f" stroke-width="2.5"'); // опоздавшей вехи нет
});
it("веха правее крайнего срока: ромб остаётся справа от черты и обведён красным", () => {
const rows = [
row({ id: "CP-0", stage: "S", date_constraint: "день 0" }),
row({ id: "S-1", stage: "S", depends_on: "CP-0", duration: "20d" }),
row({ id: "CP-5", stage: "S", depends_on: "S-1", date_constraint: "не позже дня 7" }),
];
const sc = computeSchedule(rows);
expect(sc.timings.get("CP-5")).toMatchObject({ end: 20, deadline: 7 });
const svg = renderGantt({ ...model, rows }, sc, {});
expect(svg).toContain('stroke="#d32f2f" stroke-width="2.5"'); // красный контур ромба
});
it("повторяющиеся шаги тянутся до конца проекта и не считаются предшественниками", () => {
const rows = [row({ id: "CP-0", date_constraint: "день 0" }), row({ id: "CP-9", depends_on: "CP-0", date_constraint: "день 90" }), row({ id: "S-W", depends_on: "CP-0", date_constraint: "еженедельно" })];
const { timings } = computeSchedule(rows);
expect(timings.get("S-W")).toMatchObject({ kind: "recurring", start: 0, end: 90 });
});
it("не падает на цикле и неизвестной зависимости", () => {
const rows = [row({ id: "A", depends_on: "B" }), row({ id: "B", depends_on: "A", depends_on2: "ZZZ" })];
const { warnings } = computeSchedule(rows);
expect(warnings.map((w) => w.message).join("|")).toMatch(/цикл/);
expect(warnings.map((w) => w.message).join("|")).toMatch(/ZZZ/);
});
it("предупреждает, когда срок не сходится с длительностью", () => {
const { warnings } = computeSchedule([row({ id: "A", date_constraint: "день 10 → день 100", duration: "10 дней" })]);
expect(warnings[0]?.message).toMatch(/длительност/);
});
});
const model: ProcessModel = {
set: "khbuild",
stages: [],
responsible: [
{ id: "architect", role: "architect", person: "RIOS", comment: null },
{ id: "pm", role: "pm", person: "PM", comment: "кто именно?" },
],
roles: [
{ id: "architect", person: "RIOS", comment: null },
{ id: "pm", person: "PM", comment: "кто именно?" },
],
systems: [{ id: "JobTread", name: "JobTread", comment: null }],
data: [
{ id: "Plan", description: "План", role: "architect", comment: null },
{ id: "Doc", description: null, role: null, comment: "откуда?" },
],
rows: [
row({ id: "CP-0", stage: "Kick-off", action_name: "Kick-off & <старт>", responsible_role: "architect", date_constraint: "день 0", data_out1: "Plan" }),
row({ id: "S-1", stage: "Build", action_name: "Построить", responsible_role: "pm", system_to_be: "JobTread", depends_on: "CP-0", duration: "10 дней", data_in1: "Plan", data_in2: "Doc", questions: "вопрос" }),
row({ id: "CP-1", stage: "Build", action_name: "Готово", depends_on: "S-1", date_constraint: "день 10" }),
],
};
describe("renderGantt", () => {
it("рисует строки, вехи и экранирует текст", () => {
const svg = renderGantt(model, computeSchedule(model.rows), { kickoff: "2026-11-02" });
expect(svg.startsWith("<?xml")).toBe(true);
expect(svg).toContain("CP-0");
expect(svg).toContain("Kick-off &amp; &lt;старт&gt;");
expect(svg).toContain("2026-11-02");
expect(svg).not.toMatch(/<старт>/);
});
it("фильтр по этапам", () => {
const svg = renderGantt(model, computeSchedule(model.rows), { stages: ["Kick-off"] });
expect(svg).toContain("CP-0");
expect(svg).not.toContain(">S-1<");
});
it("порядок этапов по срокам", () => {
expect(stageOrder(model.rows, computeSchedule(model.rows))).toEqual(["Kick-off", "Build"]);
});
});
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: "A", date_constraint: "день 0 → день 10" }),
row({ id: "B", date_constraint: "день 5 → день 12" }), // перекрывается с A: отрезки объединяются
row({ id: "C", date_constraint: "день 30 → день 40" }), // после паузы
row({ id: "M", date_constraint: "день 20", is_milestone: true }), // веха в паузе: ромб есть, полосы нет
];
const s2 = computeSchedule(rows);
const g = summarizeGroup("G", rows.map((r) => ({ row: r, t: s2.timings.get(r.id)! })));
expect(g.segments).toEqual([[0, 12], [30, 40]]);
expect([g.start, g.end]).toEqual([0, 40]);
expect(g.milestones.map((m) => m.row.id)).toEqual(["M"]);
const svg = renderGantt({ ...model, rows: rows.map((r) => ({ ...r, stage: "G" })) }, s2, {});
// два прямоугольника сводной полосы (две высоты 14 с заливкой цвета группы) вместо одного
expect(svg.match(/height="14" rx="2"/g)).toHaveLength(2);
});
it("группа только из вех или без работ с длительностью рисуется одним сплошным отрезком", () => {
const rows = [row({ id: "M1", date_constraint: "день 7", is_milestone: true }), row({ id: "M2", date_constraint: "день 75", is_milestone: true })];
const s2 = computeSchedule(rows);
const g = summarizeGroup("G", rows.map((r) => ({ row: r, t: s2.timings.get(r.id)! })));
expect(g.segments).toEqual([[7, 75]]);
});
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 ghost = (svg: string) => svg.split('fill="#fff" stroke="').length - 1;
const shut = renderGantt(ms, sch, { collapsed: ["A"] });
expect(shut).toContain("X-9 Своя веха"); // подпись контурной вехи на строке S-3
expect(ghost(shut)).toBeGreaterThanOrEqual(1);
expect(renderGantt(ms, sch, { collapsed: ["A", "B"] })).not.toContain("X-9 Своя веха"); // S-3 не веха, строки для ромба нет
expect(renderGantt(ms, sch, {})).toContain("X-9 Своя веха");
});
it("стрелка зависимости имеет подсказку «от -> к» с названиями шагов", () => {
const rows = [row({ id: "A", stage: "S", action_name: "Первый", duration: "1d", date_constraint: "день 0 → день 1" }), row({ id: "B", stage: "S", action_name: "Второй", depends_on: "A", duration: "1d" })];
const m: ProcessModel = { ...model, rows };
const svg = renderGantt(m, computeSchedule(rows), {});
expect(svg).toContain("<title>A -&gt; B Первый -&gt; Второй</title>");
});
it("зависимость, следующая из цепочки других, не рисуется стрелкой (A→C при A→B→C)", () => {
const rows = [row({ id: "A" }), row({ id: "B", depends_on: "A" }), row({ id: "C", depends_on: "B", depends_on2: "A" })];
const redundant = redundantDependencies(rows);
expect([...redundant]).toEqual(["A>C"]);
});
it("подпись полосы - название работы (внутри полосы или над ней), id справа снизу, без дат", () => {
const svg = renderGantt(ms, sch, { px: 20 });
expect(svg).toContain('fill="#fff">Работа</text>'); // название внутри длинной полосы
expect(svg).toMatch(/text-anchor="end" font-size="9"[^>]*>S-1<[/]text>/); // id справа снизу
expect(svg).not.toMatch(/>[0-9]+–[0-9]+<[/]text>/); // подписей-интервалов дат у полос нет
const narrow = renderGantt(ms, sch, { px: 0.5 });
expect(narrow).toMatch(/font-weight="600" fill="#[0-9a-f]{6}">Работа<[/]text>/); // не влезло - подпись над полосой
});
it("этапы: порядок и цвета берутся из справочника (ord, color_fill, color_stroke), заливка сплошная (без штриховки)", () => {
const names = ["Стройка", "Пермит", "Договоры PreConstruction", "Финансы", "Свой этап", "Спецификации", "Архитектура", "Закупки"];
const rows = names.map((s, i) => row({ id: "S-" + i, stage: s, date_constraint: "день " + (10 + i) }));
const refs: ProcessModel["stages"] = [
{ id: "Договоры PreConstruction", name: "Договоры PreConstruction", comment: null, ord: 20, fill: "#dde0e6", stroke: "#7a808f" },
{ id: "Пермит", name: "Пермит", comment: null, ord: 30, fill: "#f7d9cc", stroke: "#d8622f" },
{ id: "Архитектура", name: "Архитектура", comment: null, ord: 40, fill: "#d4ece3", stroke: "#3f9a78" },
{ id: "Спецификации", name: "Спецификации", comment: null, ord: 50, fill: "#d3e4ef", stroke: "#3f7ea6" },
{ id: "Финансы", name: "Финансы", comment: null, ord: 60, fill: "#f5e6c8", stroke: "#d4982f" },
{ id: "Закупки", name: "Закупки", comment: null, ord: 80, fill: "#dbe6ee", stroke: "#6f93ab" },
{ id: "Стройка", name: "Стройка", comment: null, ord: 90, fill: "#cfe6da", stroke: "#1f7a52" },
];
const m: ProcessModel = { ...model, rows, stages: refs };
const sc = computeSchedule(m.rows);
expect(stageOrder(m.rows, sc, refs)).toEqual(["Договоры PreConstruction", "Пермит", "Архитектура", "Спецификации", "Финансы", "Закупки", "Стройка", "Свой этап"]);
const svg = renderGantt(m, sc, {});
expect(svg).toContain("#7a808f"); // Договоры
expect(svg).toContain("#d8622f"); // Пермит
expect(svg).toContain("#1f7a52"); // Стройка
expect(svg).not.toContain("<pattern");
expect(svg).not.toContain("url(#hatch)");
});
it("страница: колесо - вертикальная прокрутка, Ctrl+колесо - горизонтальная, Ctrl+Shift+колесо - масштаб, границы полотна", () => {
const html = renderPage({ set: "khbuild", stages: [], warnings: [], rows: 0, questions: 0 });
expect(html).toContain("e.ctrlKey && e.shiftKey");
expect(html).toContain("ty -= e.deltaY"); // колесо - вертикально
expect(html).toContain("tx -= dd * lin"); // Ctrl+колесо - горизонтально
expect(html).toContain("function clamp()"); // границы полотна
expect(html).toContain("window.addEventListener('resize', place)");
});
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), {});
expect(svg).toContain("RIOS");
expect(svg).toContain("<polygon"); // событие CP
expect(svg).toContain("JobTread");
expect(svg).not.toContain("#c8eef5"); // заливка объектов данных: при выключенных данных их нет
});
it("с данными добавляет информационные объекты и потоки", () => {
const svg = renderAris(model, computeSchedule(model.rows), { data: true });
expect(svg).toContain("#c8eef5");
expect(svg).toContain(">Plan<");
expect(svg).toContain(">Doc<");
expect(svg).toContain("stroke-dasharray");
});
it("без событий нет шестиугольников", () => {
expect(renderAris(model, computeSchedule(model.rows), { events: false })).not.toContain("<polygon");
});
});
describe("http-api", () => {
const app = buildApi({ token: "t", defaultSet: "khbuild", load: async () => model, dbOk: async () => true });
it("healthz без токена", async () => {
const r = await app.inject("/healthz");
expect(r.statusCode).toBe(200);
expect(r.json()).toMatchObject({ ok: true, db: true });
});
it("остальное требует токен", async () => {
expect((await app.inject("/gantt.svg")).statusCode).toBe(401);
expect((await app.inject({ url: "/gantt.svg", headers: { authorization: "Bearer bad" } })).statusCode).toBe(401);
});
it("токен в адресе выдаёт cookie, по cookie открывается без токена", async () => {
const r = await app.inject("/gantt.svg?token=t");
expect(r.statusCode).toBe(200);
expect(r.headers["content-type"]).toContain("image/svg+xml");
const cookie = String(r.headers["set-cookie"]).split(";")[0] ?? "";
expect((await app.inject({ url: "/aris.svg?data=1", headers: { cookie } })).statusCode).toBe(200);
});
it("страница и JSON-модель", async () => {
const h = { authorization: "Bearer t" };
const page = await app.inject({ url: "/", headers: h });
expect(page.statusCode).toBe(200);
expect(page.body).toContain("Гант");
const m = (await app.inject({ url: "/api/model", headers: h })).json();
expect(m.rows).toHaveLength(3);
expect(m.schedule.timings).toHaveLength(3);
});
it("страница работает под префиксом /viz/: относительные адреса, выбор вкладки по ?view", async () => {
const page = (await app.inject({ url: "/", headers: { authorization: "Bearer t" } })).body;
expect(page).toContain("tab + '.svg?'");
expect(page).not.toMatch(/fetch\('\/|u = '\//); // нет абсолютных адресов, которые ломаются за прокси
expect(page).toContain("get('view') === 'aris'");
expect(page).toContain('href="../"'); // возврат к списку отчётов
});
it("выделение текста только у названий и id активностей слева, остальное - под перетаскивание", async () => {
const page = (await app.inject({ url: "/", headers: { authorization: "Bearer t" } })).body;
expect(page).toContain("#view,#view *{-webkit-user-select:none;user-select:none}");
expect(page).toContain("#view .sel{-webkit-user-select:text;user-select:text");
expect(page).toContain("closest('.sel')) return;"); // нажатие на выделяемый текст не запускает pan
const svg = renderGantt(model, computeSchedule(model.rows), {});
const sel = svg.match(/<text class="sel"/g) ?? [];
expect(sel.length).toBe(model.rows.length * 2); // id и название каждой строки
expect(svg).not.toMatch(/<text class="sel"[^>]*font-size="9"/); // id у полосы, подписи на оси и вех не выделяются
});
it("неизвестный набор данных заменяется на настроенный", async () => {
let asked = "";
const a = buildApi({ token: "t", defaultSet: "khbuild", load: async (s) => ((asked = s), model), dbOk: async () => true });
await a.inject({ url: "/api/model?set=drop_table", headers: { authorization: "Bearer t" } });
expect(asked).toBe("khbuild");
await a.inject({ url: "/api/model?set=khnata", headers: { authorization: "Bearer t" } });
expect(asked).toBe("khnata");
});
it("download=1 отдаёт вложение", async () => {
const r = await app.inject({ url: "/gantt.svg?download=1", headers: { authorization: "Bearer t" } });
expect(String(r.headers["content-disposition"])).toContain("attachment");
});
});