Визуализатор: справочник ответственных, каноническая длительность, поддержка обеих схем
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>
This commit is contained in:
2026-10-14 19:58:57 +03:00
parent a4f338c5d1
commit f1971b8975
6 changed files with 246 additions and 25 deletions

View File

@@ -1,4 +1,4 @@
import type { ProcessModel, ProcessRow } from "./model.js";
import { describeResponsible, type ProcessModel, type ProcessRow } from "./model.js";
import type { Schedule } from "./schedule.js";
import { esc, svgDoc, tooltip, truncate, wrap } from "./svg.js";
@@ -191,7 +191,7 @@ export function renderAris(model: ProcessModel, schedule: Schedule, opts: ArisOp
// Узлы
for (const n of nodes) {
if (n.kind === "F" && n.row) out.push(fnSvg(n, n.row, roleName, sysName));
if (n.kind === "F" && n.row) out.push(fnSvg(n, n.row, roleName, sysName, model));
else if (n.kind === "E" && n.row) out.push(evSvg(n, n.row, schedule));
else if (n.kind === "D" && n.dataId) out.push(dataSvg(n, dataInfo.get(n.dataId), n.dataId, roleName));
}
@@ -203,14 +203,14 @@ export function renderAris(model: ProcessModel, schedule: Schedule, opts: ArisOp
return svgDoc(width, height, defs, out.join("\n"));
}
function fnSvg(n: Node, r: ProcessRow, roleName: Map<string, string>, sysName: Map<string, string>): string {
function fnSvg(n: Node, r: ProcessRow, roleName: Map<string, string>, sysName: Map<string, string>, model: ProcessModel): string {
const cp = isCp(r.id);
const c = cp ? C.fnCp : C.fn;
const title = wrap(r.actionName ?? r.description ?? "", 23, 2);
const tip = tooltip([
`${r.id} - ${r.actionName ?? ""}`,
r.description,
`Ответственный: ${[r.role ? roleName.get(r.role) ?? r.role : null, r.responsibleName].filter(Boolean).join(" / ") || "не указан"}`,
`Ответственный: ${describeResponsible(r, model)}`,
r.dateConstraint ? `Срок: ${r.dateConstraint}` : null,
r.duration ? `Длительность: ${r.duration}` : null,
r.dataIn.length ? `Вход: ${r.dataIn.join(", ")}` : null,
@@ -225,6 +225,7 @@ function fnSvg(n: Node, r: ProcessRow, roleName: Map<string, string>, sysName: M
const w = Math.min(n.w - 16, 12 + label.length * 6.2);
parts.push(`<rect x="${n.x + 8}" y="${n.y + n.h - 19}" width="${w}" height="14" rx="4" fill="${C.sys.fill}" stroke="${C.sys.stroke}"/><text x="${n.x + 14}" y="${n.y + n.h - 8}" font-size="10" fill="#10335a">${esc(label)}</text>`);
}
if (r.duration) parts.push(`<text x="${n.x + n.w - 8}" y="${n.y + n.h - 8}" text-anchor="end" font-size="10" font-weight="600" fill="#3d5a1f">${esc(r.duration)}</text>`);
if (r.questions) parts.push(`<circle cx="${n.x + n.w - 10}" cy="${n.y + 10}" r="5" fill="#e6a100"/>`);
parts.push("</g>");
return parts.join("");

View File

@@ -1,4 +1,4 @@
import type { ProcessModel, ProcessRow } from "./model.js";
import { describeResponsible, type ProcessModel, type ProcessRow } from "./model.js";
import type { Schedule, Timing } from "./schedule.js";
import { esc, svgDoc, tooltip, truncate } from "./svg.js";
@@ -266,7 +266,7 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
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(" / ") || "не указан"}`,
`Ответственный: ${describeResponsible(row, model)}`,
row.systemToBe ? `Система: ${row.systemToBe}` : null,
row.dateConstraint ? `Срок: ${row.dateConstraint}` : `Срок выведен из зависимостей: день ${t.start}${t.end !== t.start ? "–" + t.end : ""}`,
row.duration ? `Длительность: ${row.duration}` : null,
@@ -284,7 +284,7 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
const dash = t.approx ? ' stroke-dasharray="4 2"' : "";
const textW = name.length * CHAR_W;
const idText = (tx: number, anchor: "start" | "end") =>
out.push(`<text x="${tx}" y="${top + ROW - 3}" text-anchor="${anchor}" font-size="9" letter-spacing="0.5" fill="#777">${esc(row.id)}</text>`);
out.push(`<text x="${tx}" y="${top + ROW - 3}" text-anchor="${anchor}" font-size="9" letter-spacing="0.5" fill="#777">${esc(row.id)}${row.duration ? ` · ${esc(row.duration)}` : ""}</text>`);
if (t.kind === "recurring") {
const w = Math.max(2, (t.end - t.start) * px);
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${w}" height="8" rx="3" fill="${c.stroke}" fill-opacity="0.35" stroke="${c.stroke}" stroke-width="0.8"/>`);
@@ -335,7 +335,14 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
]);
// зона клика: левая колонка и сама полоса
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"/>`);
const people = [...new Set(g.rows.map(({ row }) => (row.role ? roleName.get(row.role) ?? row.role : null)).filter((v): v is string => !!v))];
const personOf = new Map(model.responsible.map((r) => [r.id, r.person ?? r.id]));
const people = [
...new Set(
g.rows
.flatMap(({ row }) => (row.responsible.length ? row.responsible.map((id) => personOf.get(id) ?? id) : [row.role ? roleName.get(row.role) ?? row.role : null]))
.filter((v): v is string => !!v),
),
];
out.push(`<text x="14" y="${g.top + 19}" font-size="13" fill="${c.stroke}">${g.collapsed ? "▸" : "▾"}</text>`);
out.push(`<text x="32" y="${g.top + 19}" font-size="14" font-weight="700" fill="#222">${esc(truncate(g.stage, 30))}<tspan dx="6" font-size="11" font-weight="400" fill="#667085">(${g.rows.length})</tspan></text>`);
if (people.length) out.push(`<text x="32" y="${g.top + 34}" font-size="11" fill="#667085">${esc(truncate(people.join(" · "), 44))}</text>`);

View File

@@ -66,7 +66,7 @@ export function buildApi(deps: ProcessVizApiDeps): FastifyInstance {
questions:
model.rows.filter((r) => r.questions).length +
model.data.filter((d) => d.comment).length +
model.roles.filter((r) => r.comment).length +
model.responsible.filter((r) => r.comment).length +
model.systems.filter((s) => s.comment).length,
}),
);

View File

@@ -9,19 +9,27 @@ export interface ProcessRow {
stage: string | null;
actionName: string | null;
description: string | null;
/** ключи справочника ответственных (колонки responsible, responsible2, responsible3), вида «роль - Имя» */
responsible: string[];
/** роль первого ответственного (для дорожек ARIS); для архива khnata - колонка responsible_role */
role: string | null;
/** имена ответственных через «; »; для архива khnata - колонка responsible_name */
responsibleName: string | null;
systemAsIs: string | null;
systemToBe: string | null;
dataIn: string[];
dataOut: string[];
dependsOn: string[];
/** каноническая длительность: `5d` (календарные дни), `5wd` (рабочие дни), суффикс `?` - оценка (при расчёте игнорируется, но выводится) */
duration: string | null;
dateConstraint: string | null;
questions: string | null;
/** признак вехи: колонка is_milestone; если колонки нет или она пустая - вехами считаются чек-поинты CP-* */
isMilestone: boolean;
}
/** Запись справочника ответственных: ключ `id` = «роль - Имя». */
export interface ResponsibleRow { id: string; role: string | null; person: string | null; comment: string | null }
/** Роль (производная от справочника ответственных): имена всех ответственных этой роли. */
export interface RoleRow { id: string; person: string | null; comment: string | null }
export interface SystemRow { id: string; name: string | null; comment: string | null }
export interface DataRow { id: string; description: string | null; role: string | null; comment: string | null }
@@ -29,6 +37,7 @@ export interface DataRow { id: string; description: string | null; role: string
export interface ProcessModel {
set: ProcessSet;
rows: ProcessRow[];
responsible: ResponsibleRow[];
roles: RoleRow[];
systems: SystemRow[];
data: DataRow[];
@@ -44,7 +53,8 @@ export function mapRow(r: Raw): ProcessRow {
stage: str(r.stage),
actionName: str(r.action_name),
description: str(r.action_description),
role: str(r.responsible_role),
responsible: list(r.responsible, r.responsible2, r.responsible3),
role: str(r.responsible_role), // архив khnata; для актуальной схемы заполняется в buildModel
responsibleName: str(r.responsible_name),
systemAsIs: str(r.system_as_is),
systemToBe: str(r.system_to_be),
@@ -58,16 +68,84 @@ export function mapRow(r: Raw): ProcessRow {
};
}
/** Читает «звезду» из БД. Имена таблиц берутся только из белого списка PROCESS_SETS. Отсутствующие колонки (в архиве khnata их меньше) дают null. */
export interface RawStar {
process: Raw[];
/** справочник ответственных (khbuild_responsible) либо прежний справочник ролей (khnata_roles) */
refs: Raw[];
/** true, если refs - прежний справочник ролей (id, role_person, comment) */
legacyRoles: boolean;
systems: Raw[];
data: Raw[];
}
/** Собирает модель из сырых строк. Чистая функция: проверяется тестами без БД. */
export function buildModel(set: ProcessSet, raw: RawStar): ProcessModel {
const responsible: ResponsibleRow[] = raw.refs.map((r) =>
raw.legacyRoles
? { id: String(r.id), role: String(r.id), person: str(r.role_person), comment: str(r.comment) }
: { id: String(r.id), role: str(r.role), person: str(r.person), comment: str(r.comment) },
);
const byId = new Map(responsible.map((r) => [r.id, r]));
const rows = raw.process.map(mapRow).map((row) => {
const refs = row.responsible.map((id) => byId.get(id));
if (!refs.length) return row;
return { ...row, role: refs[0]?.role ?? row.role, responsibleName: refs.map((r, i) => r?.person ?? row.responsible[i]).join("; ") };
});
// Роли: в новой схеме производные (группировка справочника по роли), в архиве - сам справочник
const roles: RoleRow[] = [];
for (const r of responsible) {
const key = r.role ?? r.id;
const found = roles.find((x) => x.id === key);
const person = r.person ?? null;
if (!found) roles.push({ id: key, person, comment: r.comment });
else {
if (person && !(found.person ?? "").split(", ").includes(person)) found.person = found.person ? `${found.person}, ${person}` : person;
found.comment ??= r.comment;
}
}
const data: DataRow[] = raw.data.map((r) => {
const ref = str(r.responsible) ? byId.get(String(r.responsible)) : undefined;
return { id: String(r.id), description: str(r.data_description), role: ref?.role ?? str(r.responsible_role), comment: str(r.comment) };
});
return {
set,
rows,
responsible,
roles,
systems: raw.systems.map((r) => ({ id: String(r.id), name: str(r.system_name), comment: str(r.comment) })),
data,
};
}
/** Ответственные строки для подсказок: ключи «роль - Имя»; для архива (колонки роль и имя) - в прежнем виде. */
export function describeResponsible(row: ProcessRow, model: ProcessModel): string {
if (row.responsible.length) return row.responsible.join("; ");
const roleLabel = row.role ? model.roles.find((r) => r.id === row.role)?.person ?? row.role : null;
return [roleLabel, row.responsibleName].filter(Boolean).join(" / ") || "не указан";
}
const PG_UNDEFINED_TABLE = "42P01";
/**
* Читает «звезду» из БД. Имена таблиц берутся только из белого списка PROCESS_SETS.
* Справочник ответственных: `<набор>_responsible`; если такой таблицы нет (архив khnata), читается прежний `<набор>_roles`.
*/
export async function loadModel(db: Queryable, set: ProcessSet): Promise<ProcessModel> {
if (!PROCESS_SETS.includes(set)) throw new Error(`неизвестный набор: ${set}`);
const q = async (table: string): Promise<Raw[]> => (await db.query(`select * from ${set}_${table} order by id`)).rows as Raw[];
const [process, roles, systems, data] = await Promise.all([q("process"), q("roles"), q("systems"), q("data_objects")]);
return {
set,
rows: process.map(mapRow),
roles: roles.map((r) => ({ id: String(r.id), person: str(r.role_person), comment: str(r.comment) })),
systems: systems.map((r) => ({ id: String(r.id), name: str(r.system_name), comment: str(r.comment) })),
data: data.map((r) => ({ id: String(r.id), description: str(r.data_description), role: str(r.responsible_role), comment: str(r.comment) })),
};
const [process, systems, data] = await Promise.all([q("process"), q("systems"), q("data_objects")]);
let refs: Raw[];
let legacyRoles = false;
try {
refs = await q("responsible");
} catch (e) {
if ((e as { code?: string }).code !== PG_UNDEFINED_TABLE) throw e;
refs = await q("roles");
legacyRoles = true;
}
return buildModel(set, { process, refs, legacyRoles, systems, data });
}

View File

@@ -30,12 +30,23 @@ export function parseConstraint(text: string | null): ParsedConstraint {
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;
/** Каноническая длительность: `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\b)/);
const m = t.match(/(\d+(?:[.,]\d+)?)\s*(недел|месяц|дн|дней|дня|day|d)/);
if (!m) return null;
const n = Number((m[1] ?? "").replace(",", "."));
const unit = m[2] ?? "";
@@ -44,6 +55,23 @@ export function parseDuration(text: string | null): number | null {
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;

View File

@@ -3,8 +3,8 @@ import { renderPage } from "./html.js";
import { renderAris } from "./aris.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";
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 });
@@ -35,6 +35,109 @@ describe("parseDuration", () => {
});
});
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 - RIOS", responsible2: "arch_permit_lead - Андрей", data_out1: "Plan" },
{ id: "S-1", responsible: "pm - PM" },
{ id: "S-2" },
],
refs: [
{ id: "architect - RIOS", role: "architect", person: "RIOS", comment: null },
{ id: "arch_permit_lead - Андрей", role: "arch_permit_lead", person: "Андрей", comment: "уточнить" },
{ id: "specs_client_mgr - Austin", role: "specs_client_mgr", person: "Austin", comment: null },
{ id: "specs_client_mgr - Маша", role: "specs_client_mgr", person: "Маша", comment: "делит с Austin" },
{ id: "pm - PM", role: "pm", person: "PM", comment: null },
],
legacyRoles: false,
systems: [],
data: [{ id: "Plan", data_description: "План", responsible: "architect - RIOS", comment: null }],
};
it("колонки responsible, responsible2, responsible3 дают список ключей, роль берётся у первого", () => {
const m = buildModel("khbuild", raw);
expect(m.rows[0]).toMatchObject({ responsible: ["architect - RIOS", "arch_permit_lead - Андрей"], role: "architect", responsibleName: "RIOS; Андрей" });
expect(m.rows[1]).toMatchObject({ responsible: ["pm - 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("computeSchedule", () => {
it("берёт срок из ограничения, остальное выводит по зависимостям", () => {
const rows = [
@@ -72,6 +175,10 @@ describe("computeSchedule", () => {
const model: ProcessModel = {
set: "khbuild",
responsible: [
{ id: "architect - RIOS", role: "architect", person: "RIOS", comment: null },
{ id: "pm - PM", role: "pm", person: "PM", comment: "кто именно?" },
],
roles: [
{ id: "architect", person: "RIOS", comment: null },
{ id: "pm", person: "PM", comment: "кто именно?" },