Files
khb_microservices/packages/khbuild_process_viz/src/schedule.ts
Yuri Yaryshev f1971b8975
All checks were successful
ci / test (push) Successful in 18s
ci / deploy (push) Successful in 1m18s
Визуализатор: справочник ответственных, каноническая длительность, поддержка обеих схем
Модель читает khbuild_responsible (колонки responsible, responsible2/3 =
ключ «роль - Имя»); если справочника нет (архив khnata) - прежние
responsible_role/responsible_name и khnata_roles. Длительность: 5d - календарные
дни, 5wd - рабочие, суффикс ? игнорируется при расчёте и выводится в Ганте и
ARIS. Тесты на обе схемы и откат на прежний справочник.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 19:58:57 +03:00

163 lines
7.1 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;
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 };
}
/** Каноническая длительность: `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;
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 };
}