Files
khb_microservices/packages/khbuild_process_viz/src/schedule.ts
2026-10-17 17:03:25 +03:00

175 lines
8.4 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
/** «не позже» / «до»: крайний срок (на Ганте - красная черта); «около» крайним сроком не считается */
deadline: boolean;
recurring: "weekly" | "daily" | null;
}
/** Числа в тексте; «-2» - отрицательный день только если минус не приклеен к цифре слева («0-44» - диапазон). */
const numbers = (s: string): number[] => [...s.matchAll(/(?<!\d)-\d+|\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, deadline: 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;
const deadline = /не\s+позже|(^|\s)до\s/.test(t);
if (n.length === 1) return { ...none, end: n[0] ?? null, exact: /^\s*день\s+\d+\s*$/.test(t), deadline };
return { ...none, start: n[0] ?? null, end: n.at(-1) ?? null };
}
/** Каноническая длительность: `5d` - календарные дни, `5wd` - рабочие дни, суффикс `?` - оценка. Колонка `duration` в БД проверяется этим же форматом. */
export const DURATION_FORMAT = /^(\d+(?:\.\d+)?)(d|wd)(\?)?$/;
export interface DurationInfo {
amount: number;
unit: "d" | "wd";
/** суффикс `?`: при расчёте игнорируется, но выводится в визуализации */
uncertain: boolean;
/** длительность в календарных днях (рабочие дни переводятся как 5 рабочих = 7 календарных) */
days: number;
}
/** Прежние текстовые значения (архив khnata и черновики): «4 недели», «10 дней», «~3 месяца». Пороги в «рабочих днях» длительностью не считаются. */
function legacyDays(text: string): number | null {
const t = text.toLowerCase();
if (t.includes("рабоч")) return null;
const m = t.match(/(\d+(?:[.,]\d+)?)\s*(недел|месяц|дн|дней|дня|day|d)/);
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 function parseDurationInfo(text: string | null): DurationInfo | null {
if (!text) return null;
const m = text.trim().toLowerCase().match(DURATION_FORMAT);
if (m) {
const amount = Number(m[1]);
const unit = m[2] as "d" | "wd";
return { amount, unit, uncertain: m[3] === "?", days: Math.round(unit === "wd" ? (amount * 7) / 5 : amount) };
}
const days = legacyDays(text);
return days === null ? null : { amount: days, unit: "d", uncertain: /[?~]|до\s/i.test(text), days };
}
/** Длительность в календарных днях или null. */
export function parseDuration(text: string | null): number | null {
return parseDurationInfo(text)?.days ?? null;
}
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;
/** крайний срок («не позже», «до»): день, где рисуется красная черта; null - крайнего срока нет */
deadline: number | null;
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 (isCheckpoint(id) && c.deadline && !c.exact && row.dependsOn.length > 0) {
// веха с крайним сроком стоит на прогнозе (по предшественникам), а сам срок рисуется красной чертой (Timing.deadline)
start = depEnd;
end = depEnd;
} else 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,
deadline: c.deadline && c.end !== null && c.start === null ? c.end : null,
recurring: c.recurring,
};
timings.set(id, t);
if (!c.recurring && t.fromConstraint && row.dependsOn.length > 0 && end < depEnd) warnings.push({ id, message: `срок (день ${end}) раньше окончания предшественников (день ${depEnd})` });
if (t.deadline !== null && isCheckpoint(id) && row.dependsOn.length > 0 && depEnd > t.deadline) warnings.push({ id, message: `прогноз (день ${depEnd}) позже крайнего срока (день ${t.deadline})` });
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 };
}