Files
khb_microservices/packages/khbuild_process_viz/src/schedule.ts
Yuri Yaryshev 3fa8bb7e8e
Some checks failed
ci / test (push) Successful in 17s
ci / deploy (push) Failing after 22s
Новый сервис khbuild_process_viz: Гант и ARIS eEPC процесса to-be
Читает таблицы 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>
2026-10-14 08:24:50 +03:00

135 lines
5.7 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 type { ProcessRow } from "./model.js";
export interface ParsedConstraint {
start: number | null;
end: number | null;
/** «день N» без «не позже / около / до»: точная дата, а не предел */
exact: boolean;
recurring: "weekly" | "daily" | null;
}
const numbers = (s: string): number[] => [...s.matchAll(/\d+/g)].map((m) => Number(m[0]));
/**
* Разбор поля date_constraint (дни от первой встречи с архитектором).
* «день 7», «не позже дня 7», «около дня 45», «день 45–47», «день 80 → день 90», «день 120 …; день 135 …», «еженедельно …».
*/
export function parseConstraint(text: string | null): ParsedConstraint {
const none: ParsedConstraint = { start: null, end: null, exact: false, recurring: null };
if (!text) return none;
const t = text.toLowerCase();
if (/еженедельно/.test(t)) return { ...none, recurring: "weekly" };
if (/ежедневно/.test(t)) return { ...none, recurring: "daily" };
if (t.includes("→")) {
const [left = "", right = ""] = t.split("→");
return { ...none, start: numbers(left).at(-1) ?? null, end: numbers(right).at(-1) ?? null };
}
const n = numbers(t);
if (n.length === 0) return none;
if (n.length === 1) return { ...none, end: n[0] ?? null, exact: /^\s*день\s+\d+\s*$/.test(t) };
return { ...none, start: n[0] ?? null, end: n.at(-1) ?? null };
}
/** Длительность в днях: «4 недели», «до 9 недель», «10 дней», «~3 месяца», «30d». Пороги в «рабочих днях» не длительность. */
export function parseDuration(text: string | null): number | null {
if (!text) return null;
const t = text.toLowerCase();
if (t.includes("рабоч")) return null;
const m = t.match(/(\d+(?:[.,]\d+)?)\s*(недел|месяц|дн|дней|дня|day|d\b)/);
if (!m) return null;
const n = Number((m[1] ?? "").replace(",", "."));
const unit = m[2] ?? "";
if (unit.startsWith("недел")) return Math.round(n * 7);
if (unit.startsWith("месяц")) return Math.round(n * 30);
return Math.round(n);
}
export type TimingKind = "task" | "milestone" | "recurring";
export interface Timing {
id: string;
/** день от точки отсчёта (kick-off = 0) */
start: number;
end: number;
kind: TimingKind;
/** срок взят из date_constraint (иначе выведен из зависимостей и длительности) */
fromConstraint: boolean;
/** «около», «до», «не позже»: срок не точный */
approx: boolean;
recurring: "weekly" | "daily" | null;
}
export interface ScheduleWarning { id: string; message: string }
export interface Schedule {
timings: Map<string, Timing>;
warnings: ScheduleWarning[];
maxDay: number;
}
const isCheckpoint = (id: string): boolean => /^CP-/.test(id);
/** Строит расписание: сроки из date_constraint, остальное - по зависимостям (depends_on*) и длительности. Противоречия возвращает предупреждениями. */
export function computeSchedule(rows: ProcessRow[]): Schedule {
const byId = new Map(rows.map((r) => [r.id, r]));
const timings = new Map<string, Timing>();
const warnings: ScheduleWarning[] = [];
const visiting = new Set<string>();
const visit = (id: string): Timing => {
const done = timings.get(id);
if (done) return done;
const row = byId.get(id);
if (!row) throw new Error(`нет строки ${id}`);
visiting.add(id);
let depEnd = 0;
for (const dep of row.dependsOn) {
if (!byId.has(dep)) {
warnings.push({ id, message: `зависимость ${dep} не найдена в процессе` });
} else if (visiting.has(dep)) {
warnings.push({ id, message: `цикл зависимостей через ${dep}` });
} else {
depEnd = Math.max(depEnd, visit(dep).end);
}
}
visiting.delete(id);
const c = parseConstraint(row.dateConstraint);
const d = parseDuration(row.duration);
let start: number;
let end: number;
if (c.recurring) {
start = depEnd;
end = depEnd;
} else if (c.start !== null && c.end !== null) {
start = c.start;
end = c.end;
} else if (c.end !== null) {
end = c.end;
if (c.exact || isCheckpoint(id)) start = d !== null && !c.exact ? Math.max(0, end - d) : end;
else start = d !== null ? Math.max(0, end - d) : Math.min(depEnd, end);
} else {
start = depEnd;
end = depEnd + (d ?? 0);
}
const t: Timing = {
id,
start,
end,
kind: c.recurring ? "recurring" : start === end ? "milestone" : "task",
fromConstraint: c.start !== null || c.end !== null,
approx: c.end !== null && c.start === null && !c.exact,
recurring: c.recurring,
};
timings.set(id, t);
if (!c.recurring && t.fromConstraint && end < depEnd) warnings.push({ id, message: `срок (день ${end}) раньше окончания предшественников (день ${depEnd})` });
if (c.start !== null && c.end !== null && d !== null && Math.abs(end - start - d) > 7) warnings.push({ id, message: `срок ${start}→${end} (${end - start} дн.) не сходится с длительностью ${d} дн.` });
return t;
};
for (const r of rows) visit(r.id);
const maxDay = Math.max(0, ...[...timings.values()].filter((t) => t.kind !== "recurring").map((t) => t.end));
for (const t of timings.values()) if (t.kind === "recurring") t.end = maxDay;
return { timings, warnings, maxDay };
}