Новый сервис 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>
This commit is contained in:
96
packages/khbuild_process_viz/src/http-api.ts
Normal file
96
packages/khbuild_process_viz/src/http-api.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
|
||||
import { renderAris } from "./aris.js";
|
||||
import { renderGantt, stageOrder } from "./gantt.js";
|
||||
import { renderPage } from "./html.js";
|
||||
import { PROCESS_SETS, type ProcessModel, type ProcessSet } from "./model.js";
|
||||
import { computeSchedule } from "./schedule.js";
|
||||
|
||||
export interface ProcessVizApiDeps {
|
||||
token: string;
|
||||
defaultSet: ProcessSet;
|
||||
/** загрузка модели; в тестах подменяется */
|
||||
load: (set: ProcessSet) => Promise<ProcessModel>;
|
||||
/** проверка доступности БД для /healthz */
|
||||
dbOk: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
type Query = Record<string, string | undefined>;
|
||||
const COOKIE = "viz_token";
|
||||
|
||||
function tokenFrom(req: FastifyRequest): string | null {
|
||||
const auth = req.headers.authorization;
|
||||
if (auth?.startsWith("Bearer ")) return auth.slice(7);
|
||||
const q = (req.query as Query).token;
|
||||
if (q) return q;
|
||||
const m = (req.headers.cookie ?? "").split(/;\s*/).find((c) => c.startsWith(`${COOKIE}=`));
|
||||
return m ? decodeURIComponent(m.slice(COOKIE.length + 1)) : null;
|
||||
}
|
||||
|
||||
export function buildApi(deps: ProcessVizApiDeps): FastifyInstance {
|
||||
const app = Fastify();
|
||||
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
if (req.url === "/healthz") return;
|
||||
const t = tokenFrom(req);
|
||||
if (t !== deps.token) return reply.code(401).type("text/plain; charset=utf-8").send("Нужен токен: ?token=... или заголовок Authorization: Bearer ...");
|
||||
// Токен в адресе -> запоминаем в cookie, чтобы страница и SVG открывались без него
|
||||
if ((req.query as Query).token) reply.header("set-cookie", `${COOKIE}=${encodeURIComponent(t)}; Path=/; HttpOnly; SameSite=Strict`);
|
||||
});
|
||||
|
||||
const setOf = (q: Query): ProcessSet => {
|
||||
const s = q.set as ProcessSet | undefined;
|
||||
return s && PROCESS_SETS.includes(s) ? s : deps.defaultSet;
|
||||
};
|
||||
const stagesOf = (q: Query): string[] | null => (q.stages ? q.stages.split("|").filter(Boolean) : null);
|
||||
const svgReply = (reply: FastifyReply, svg: string, name: string, q: Query) =>
|
||||
reply
|
||||
.header("cache-control", "no-store")
|
||||
.header("content-disposition", `${q.download ? "attachment" : "inline"}; filename="${name}"`)
|
||||
.type("image/svg+xml; charset=utf-8")
|
||||
.send(svg);
|
||||
|
||||
app.get("/healthz", async () => {
|
||||
const db = await deps.dbOk().catch(() => false);
|
||||
return { ok: true, db, time: new Date().toISOString() };
|
||||
});
|
||||
|
||||
app.get("/", async (req, reply) => {
|
||||
const model = await deps.load(setOf(req.query as Query));
|
||||
const sch = computeSchedule(model.rows);
|
||||
return reply.type("text/html; charset=utf-8").send(
|
||||
renderPage({
|
||||
set: model.set,
|
||||
stages: stageOrder(model.rows, sch),
|
||||
warnings: sch.warnings,
|
||||
rows: model.rows.length,
|
||||
questions:
|
||||
model.rows.filter((r) => r.questions).length +
|
||||
model.data.filter((d) => d.comment).length +
|
||||
model.roles.filter((r) => r.comment).length +
|
||||
model.systems.filter((s) => s.comment).length,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
app.get("/api/model", async (req) => {
|
||||
const model = await deps.load(setOf(req.query as Query));
|
||||
const sch = computeSchedule(model.rows);
|
||||
return { ...model, schedule: { maxDay: sch.maxDay, timings: [...sch.timings.values()], warnings: sch.warnings } };
|
||||
});
|
||||
|
||||
app.get("/gantt.svg", async (req, reply) => {
|
||||
const q = req.query as Query;
|
||||
const model = await deps.load(setOf(q));
|
||||
const svg = renderGantt(model, computeSchedule(model.rows), { kickoff: q.kickoff ?? null, deps: q.deps !== "0", stages: stagesOf(q) });
|
||||
return svgReply(reply, svg, `process_gantt_${model.set}.svg`, q);
|
||||
});
|
||||
|
||||
app.get("/aris.svg", async (req, reply) => {
|
||||
const q = req.query as Query;
|
||||
const model = await deps.load(setOf(q));
|
||||
const svg = renderAris(model, computeSchedule(model.rows), { data: q.data === "1", events: q.events !== "0", stages: stagesOf(q) });
|
||||
return svgReply(reply, svg, `process_aris_${model.set}.svg`, q);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
Reference in New Issue
Block a user