Страница отчётов reports и встраивание визуализатора под /viz/ за входом Keycloak
Новый package reports: статический список ссылок (khbuild_process - Гант и ARIS), порт 8087, добавлен в deploy.sh. Визуализатор открывается под префиксом /viz/ (относительные адреса, ?view=gantt|aris, возврат к списку). Для хоста reports.khbuild.freeddns.org: nginx, oauth2-proxy и клиент Keycloak reports-proxy настроены под root, справочные копии - deploy/infra/. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
Статус: работает (khb-process-viz, 127.0.0.1:8086). Владелец: ИТ-команда. Назначение: рисовать процесс to-be из таблиц `khbuild_*` Supabase в виде диаграммы Ганта и ARIS eEPC (SVG) и показывать их на странице просмотра.
|
||||
|
||||
## Endpoints и доступ
|
||||
`GET /healthz` (без авторизации), `GET /`, `/gantt.svg`, `/aris.svg`, `/api/model` - токен `khbuild_process_viz.http.token`. Подробно: [api_objects.md](../../../docs/proposed/data_objects/khbuild_process_viz/api_objects.md). Порт доступен только на 127.0.0.1: открыть можно через SSH-туннель `ssh -L 8086:127.0.0.1:8086 khbuild-vps` и адрес `http://127.0.0.1:8086/?token=<token>`.
|
||||
`GET /healthz` (без авторизации), `GET /`, `/gantt.svg`, `/aris.svg`, `/api/model` - токен `khbuild_process_viz.http.token`. Подробно: [api_objects.md](../../../docs/proposed/data_objects/khbuild_process_viz/api_objects.md). Для людей сервис открыт через `https://reports.khbuild.freeddns.org/viz/?view=gantt` (или `view=aris`) за входом Keycloak/Google (группа `/it-admins`), список ссылок - пакет `reports`. Токен подставляет nginx. Прямой доступ (отладка): порт 127.0.0.1:8086, SSH-туннель `ssh -L 8086:127.0.0.1:8086 khbuild-vps` и `http://127.0.0.1:8086/?token=<token>`.
|
||||
|
||||
## Как читать диаграммы
|
||||
- **Гант**: ось - дни от первой встречи клиента с архитектором (kick-off = день 0), при заданной дате kick-off на оси календарные даты. Ромб - чек-поинт или веха, полоса - работа, штриховка - повторяющийся шаг (`еженедельно`/`ежедневно`), пунктир - срок «не позже / около», красная обводка - противоречие в сроках, бледная строка - срок выведен из зависимостей, а не задан, жёлтая точка - есть открытый вопрос (текст в подсказке).
|
||||
@@ -25,4 +25,4 @@ Docker Compose `/y/services/khb-process-viz`, образ `khb-microservices:<tag
|
||||
Автодеплой из Gitea Actions (последний в списке сервисов `deploy.sh`), откат - `docs/deploy.md`.
|
||||
|
||||
## Отклонения от стандарта
|
||||
См. `docs/deploy.md`; доступ к странице пока только через SSH-туннель (nginx и домен не настроены).
|
||||
См. `docs/deploy.md` и `deploy/infra/README.md`; вход и nginx настроены вручную под root.
|
||||
|
||||
@@ -18,6 +18,7 @@ export function renderPage(opts: { set: string; stages: string[]; warnings: Arra
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.4 "Segoe UI",Arial,sans-serif;display:flex;flex-direction:column;height:100vh}
|
||||
header{padding:10px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;background:var(--panel)}
|
||||
h1{font-size:16px;margin:0 8px 0 0}
|
||||
a.back{color:var(--acc);text-decoration:none;margin-right:4px}
|
||||
.tabs button{border:1px solid var(--line);background:var(--bg);color:var(--fg);padding:6px 14px;cursor:pointer}
|
||||
.tabs button:first-child{border-radius:6px 0 0 6px}
|
||||
.tabs button:last-child{border-radius:0 6px 6px 0;border-left:0}
|
||||
@@ -36,7 +37,7 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
.stagebox{position:absolute;z-index:5;background:var(--bg);border:1px solid var(--line);padding:8px;display:flex;flex-direction:column}
|
||||
</style></head><body>
|
||||
<header>
|
||||
<h1>Процесс khbuild</h1>
|
||||
<h1><a class="back" href="../" title="К списку отчётов">←</a> Процесс khbuild</h1>
|
||||
<div class="tabs"><button id="tG" class="on">Гант</button><button id="tA">ARIS</button></div>
|
||||
<div class="opts">
|
||||
<label>Данные <select id="set">${sets}</select></label>
|
||||
@@ -71,20 +72,22 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
}
|
||||
function place() { stage.style.transform = 'translate(' + tx + 'px,' + ty + 'px) scale(' + k + ')'; }
|
||||
function load() {
|
||||
var u = '/' + tab + '.svg?' + qs();
|
||||
var u = tab + '.svg?' + qs(); // относительный адрес: страница работает и на корне, и под префиксом /viz/
|
||||
$('dl').href = u + '&download=1';
|
||||
$('msg').textContent = 'Загрузка…';
|
||||
$('msg').style.display = '';
|
||||
fetch(u, { credentials: 'same-origin' })
|
||||
.then(function (r) { if (!r.ok) throw new Error(r.status); return r.text(); })
|
||||
.then(function (t) { stage.innerHTML = t; $('msg').style.display = 'none'; place(); })
|
||||
.catch(function (e) { $('msg').textContent = 'Ошибка: ' + e.message; });
|
||||
.catch(function (e) { $('msg').textContent = 'Ошибка загрузки (' + e.message + '). Если истёк вход - обновите страницу.'; });
|
||||
}
|
||||
function setTab(t) {
|
||||
tab = t;
|
||||
$('tG').className = t === 'gantt' ? 'on' : '';
|
||||
$('tA').className = t === 'aris' ? 'on' : '';
|
||||
$('lEv').style.display = $('lData').style.display = t === 'aris' ? '' : 'none';
|
||||
document.title = 'khbuild_process — ' + (t === 'aris' ? 'ARIS' : 'Gantt');
|
||||
try { history.replaceState(null, '', '?view=' + t); } catch (e) {}
|
||||
k = 1; tx = 8; ty = 8;
|
||||
load();
|
||||
}
|
||||
@@ -102,7 +105,7 @@ a.btn{color:var(--acc);text-decoration:none;border:1px solid var(--line);border-
|
||||
view.addEventListener('pointerdown', function (e) { drag = { x: e.clientX - tx, y: e.clientY - ty }; view.classList.add('drag'); view.setPointerCapture(e.pointerId); });
|
||||
view.addEventListener('pointermove', function (e) { if (!drag) return; tx = e.clientX - drag.x; ty = e.clientY - drag.y; place(); });
|
||||
view.addEventListener('pointerup', function () { drag = null; view.classList.remove('drag'); });
|
||||
setTab('gantt');
|
||||
setTab(new URLSearchParams(location.search).get('view') === 'aris' ? 'aris' : 'gantt');
|
||||
})();
|
||||
</script></body></html>`;
|
||||
}
|
||||
|
||||
@@ -154,6 +154,13 @@ describe("http-api", () => {
|
||||
expect(m.rows).toHaveLength(3);
|
||||
expect(m.schedule.timings).toHaveLength(3);
|
||||
});
|
||||
it("страница работает под префиксом /viz/: относительные адреса, выбор вкладки по ?view", async () => {
|
||||
const page = (await app.inject({ url: "/", headers: { authorization: "Bearer t" } })).body;
|
||||
expect(page).toContain("tab + '.svg?'");
|
||||
expect(page).not.toMatch(/fetch\('\/|u = '\//); // нет абсолютных адресов, которые ломаются за прокси
|
||||
expect(page).toContain("get('view') === 'aris'");
|
||||
expect(page).toContain('href="../"'); // возврат к списку отчётов
|
||||
});
|
||||
it("неизвестный набор данных заменяется на настроенный", async () => {
|
||||
let asked = "";
|
||||
const a = buildApi({ token: "t", defaultSet: "khbuild", load: async (s) => ((asked = s), model), dbOk: async () => true });
|
||||
|
||||
26
packages/reports/docs/service.md
Normal file
26
packages/reports/docs/service.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# reports
|
||||
Статус: работает (khb-reports, 127.0.0.1:8087, снаружи `https://reports.khbuild.freeddns.org/`). Владелец: ИТ-команда. Назначение: страница со статическим списком ссылок на отчёты и визуализации. Сейчас в списке две визуализации: `khbuild_process - Гант` и `khbuild_process - ARIS` (их рисует `khbuild_process_viz`). Раздел «Отчёты» пока пуст.
|
||||
|
||||
## Endpoints и доступ
|
||||
`GET /healthz`, `GET /` (страница), `GET /api/links` (JSON списка). Собственной авторизации у сервиса нет: порт слушает только 127.0.0.1, наружу его выставляет nginx за входом Keycloak (Google), группа `/it-admins`. Подробно: [api_objects.md](../../../docs/proposed/data_objects/reports/api_objects.md), устройство входа: [deploy/infra/README.md](../../../deploy/infra/README.md).
|
||||
|
||||
## Как добавить отчёт
|
||||
Дописать элемент в `src/links.ts` (`group`: `reports` или `visualizations`, названия на en/ru, относительный `href`, буква для плашки) и сделать push в `main`: CI выкатит новую версию. Каждая ссылка открывается в новой вкладке.
|
||||
|
||||
## Запуск и зависимости
|
||||
Docker Compose `/y/services/khb-reports`, образ `khb-microservices:<tag>`. Не зависит ни от БД, ни от других сервисов.
|
||||
|
||||
## Конфигурация и секреты
|
||||
`/y/services/khb-config/settings.json5`: секция `reports` необязательна (`http.host` 0.0.0.0 внутри контейнера, `http.port` 8087). Секретов нет.
|
||||
|
||||
## Данные
|
||||
Нет: список ссылок зашит в код.
|
||||
|
||||
## Логи и healthcheck
|
||||
`docker logs khb-reports`; healthcheck `/healthz` в compose.
|
||||
|
||||
## Обновление и rollback
|
||||
Автодеплой из Gitea Actions (последний в списке сервисов `deploy.sh`), откат - `docs/deploy.md`.
|
||||
|
||||
## Отклонения от стандарта
|
||||
Вход и nginx настроены вручную под root (см. `deploy/infra/README.md`, `docs/proposed/deviations.md`, п. 18).
|
||||
18
packages/reports/package.json
Normal file
18
packages/reports/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "reports",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"start": "node dist/main.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.2.0",
|
||||
"khb_common": "workspace:*",
|
||||
"zod": "3.25.76"
|
||||
}
|
||||
}
|
||||
17
packages/reports/src/http-api.ts
Normal file
17
packages/reports/src/http-api.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { REPORT_LINKS } from "./links.js";
|
||||
import { renderIndex } from "./page.js";
|
||||
|
||||
/**
|
||||
* Список отчётов. Без собственной авторизации: порт слушает только 127.0.0.1, наружу сервис выставляет nginx
|
||||
* (reports.khbuild.freeddns.org) за входом Keycloak (oauth2-proxy). Никаких данных, кроме статических ссылок, он не отдаёт.
|
||||
*/
|
||||
export function buildApi(): FastifyInstance {
|
||||
const app = Fastify();
|
||||
const page = renderIndex();
|
||||
|
||||
app.get("/healthz", async () => ({ ok: true, links: REPORT_LINKS.length, time: new Date().toISOString() }));
|
||||
app.get("/", async (_req, reply) => reply.header("cache-control", "no-store").type("text/html; charset=utf-8").send(page));
|
||||
app.get("/api/links", async () => REPORT_LINKS);
|
||||
return app;
|
||||
}
|
||||
2
packages/reports/src/index.ts
Normal file
2
packages/reports/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from "./links.js";
|
||||
export * from "./page.js";
|
||||
41
packages/reports/src/links.ts
Normal file
41
packages/reports/src/links.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Статический список отчётов и визуализаций. Чтобы добавить ссылку - допишите элемент сюда и выкатите (push в main).
|
||||
* Адреса относительные: страница и все цели живут на одном хосте (reports.khbuild.freeddns.org) за одним входом Keycloak.
|
||||
*/
|
||||
export type ReportGroup = "reports" | "visualizations";
|
||||
|
||||
export interface ReportLink {
|
||||
id: string;
|
||||
group: ReportGroup;
|
||||
/** название (en / ru) */
|
||||
title: { en: string; ru: string };
|
||||
description: { en: string; ru: string };
|
||||
/** относительный адрес на этом хосте */
|
||||
href: string;
|
||||
/** одна-две буквы для плашки */
|
||||
badge: string;
|
||||
}
|
||||
|
||||
export const REPORT_LINKS: ReportLink[] = [
|
||||
{
|
||||
id: "khbuild_process_gantt",
|
||||
group: "visualizations",
|
||||
title: { en: "khbuild_process - Gantt", ru: "khbuild_process - Гант" },
|
||||
description: { en: "To-be process as a Gantt chart: days from the first architect meeting", ru: "Процесс to-be в виде диаграммы Ганта: дни от первой встречи с архитектором" },
|
||||
href: "/viz/?view=gantt",
|
||||
badge: "G",
|
||||
},
|
||||
{
|
||||
id: "khbuild_process_aris",
|
||||
group: "visualizations",
|
||||
title: { en: "khbuild_process - ARIS", ru: "khbuild_process - ARIS" },
|
||||
description: { en: "To-be process as an ARIS eEPC: roles, functions, events, systems, data", ru: "Процесс to-be в виде ARIS eEPC: роли, функции, события, системы, данные" },
|
||||
href: "/viz/?view=aris",
|
||||
badge: "A",
|
||||
},
|
||||
];
|
||||
|
||||
export const GROUP_TITLES: Record<ReportGroup, { en: string; ru: string }> = {
|
||||
reports: { en: "Reports", ru: "Отчёты" },
|
||||
visualizations: { en: "Visualizations", ru: "Визуализации" },
|
||||
};
|
||||
11
packages/reports/src/main.ts
Normal file
11
packages/reports/src/main.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { createLogger, loadServiceSettings } from "khb_common";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { reportsSchema } from "./settings.js";
|
||||
|
||||
const { common, service } = loadServiceSettings("reports", reportsSchema);
|
||||
const log = createLogger("reports", common.logLevel);
|
||||
|
||||
const app = buildApi();
|
||||
await app.listen({ host: service.http.host, port: service.http.port });
|
||||
log.info({ port: service.http.port }, "reports запущен");
|
||||
process.on("SIGTERM", () => void app.close());
|
||||
66
packages/reports/src/page.ts
Normal file
66
packages/reports/src/page.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { GROUP_TITLES, REPORT_LINKS, type ReportGroup, type ReportLink } from "./links.js";
|
||||
|
||||
const esc = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const card = (l: ReportLink): string =>
|
||||
`<a class="service" href="${esc(l.href)}" target="_blank" rel="noopener noreferrer"><span class="service-icon ${esc(l.group)}">${esc(l.badge)}</span><span><strong data-en="${esc(l.title.en)}" data-ru="${esc(l.title.ru)}">${esc(l.title.en)}</strong><small data-en="${esc(l.description.en)}" data-ru="${esc(l.description.ru)}">${esc(l.description.en)}</small></span></a>`;
|
||||
|
||||
/** Страница списка: тот же стиль и переключатель языка, что у домашней страницы; каждая ссылка открывается в новой вкладке. */
|
||||
export function renderIndex(links: ReportLink[] = REPORT_LINKS): string {
|
||||
const order: ReportGroup[] = ["reports", "visualizations"];
|
||||
const sections = order
|
||||
.map((g) => {
|
||||
const items = links.filter((l) => l.group === g);
|
||||
const t = GROUP_TITLES[g];
|
||||
const body = items.length
|
||||
? items.map(card).join("")
|
||||
: `<p class="empty" data-en="No items yet." data-ru="Пока ничего нет.">No items yet.</p>`;
|
||||
return `<h2 class="section-title" data-en="${esc(t.en)}" data-ru="${esc(t.ru)}">${esc(t.en)}</h2><section class="grid" aria-label="${esc(t.en)}">${body}</section>`;
|
||||
})
|
||||
.join("");
|
||||
return `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex">
|
||||
<title>Reports and visualizations</title>
|
||||
<style>
|
||||
:root{color-scheme:light dark;font-family:Inter,system-ui,sans-serif}
|
||||
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f7fb;color:#172033}
|
||||
main{width:min(960px,calc(100% - 40px));padding:40px 0}
|
||||
.masthead{display:flex;align-items:flex-start;justify-content:space-between;gap:20px}
|
||||
h1{margin:0 0 8px;font-size:clamp(2rem,6vw,3rem)}
|
||||
.intro{color:#5c667a;margin:0}
|
||||
.back{display:inline-block;margin-top:10px;color:#3664d9;text-decoration:none}
|
||||
.language-switcher{display:inline-flex;flex:0 0 auto;padding:3px;border:1px solid #dce3ef;border-radius:9px;background:#fff;box-shadow:0 2px 8px #17203312}
|
||||
.language-switcher button{border:0;border-radius:6px;padding:6px 9px;background:transparent;color:#5c667a;font:inherit;font-weight:650;cursor:pointer}
|
||||
.language-switcher button[aria-pressed=true]{color:#fff;background:#3664d9}
|
||||
.section-title{margin:28px 0 12px;font-size:1.05rem}
|
||||
.grid{display:grid;gap:14px;grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}
|
||||
a.service{display:flex;align-items:center;gap:14px;padding:20px;text-decoration:none;background:#fff;color:#172033;border:1px solid #dce3ef;border-radius:12px;box-shadow:0 2px 8px #17203312}
|
||||
a.service:hover,a.service:focus{border-color:#3664d9;box-shadow:0 6px 20px #17203320}
|
||||
strong,small{display:block}small{color:#5c667a;margin-top:5px}
|
||||
.service-icon{flex:0 0 auto;width:42px;height:42px;display:grid;place-items:center;border-radius:12px;color:#fff;font-size:1.1rem;font-weight:800;box-shadow:inset 0 1px #ffffff42}
|
||||
.reports{background:#0f766e}.visualizations{background:#7c3aed}
|
||||
.empty{color:#5c667a;margin:0}
|
||||
footer{margin-top:24px;font-size:.85rem;color:#6f788a}
|
||||
@media(max-width:520px){.masthead{align-items:stretch;flex-direction:column}.language-switcher{align-self:flex-start}}
|
||||
@media(prefers-color-scheme:dark){body{background:#111827;color:#edf2ff}.intro,small,footer,.empty{color:#aeb9d0}a.service,.language-switcher{background:#1b2638;color:#edf2ff;border-color:#33445f}.language-switcher button{color:#aeb9d0}}
|
||||
</style></head>
|
||||
<body><main>
|
||||
<header class="masthead"><div><h1 data-en="Reports and visualizations" data-ru="Отчёты и визуализации">Reports and visualizations</h1><p class="intro" data-en="Reports and charts built from KH Build data. Each opens in a new tab." data-ru="Отчёты и диаграммы по данным KH Build. Каждый открывается в новой вкладке.">Reports and charts built from KH Build data. Each opens in a new tab.</p><a class="back" href="https://home.khbuild.freeddns.org/" data-en="← KH Build services" data-ru="← Сервисы KH Build">← KH Build services</a></div><div class="language-switcher" role="group" aria-label="Language"><button type="button" data-language="en" aria-pressed="true">Eng</button><button type="button" data-language="ru" aria-pressed="false">Rus</button></div></header>
|
||||
${sections}
|
||||
<footer data-en="Access is by KH Build sign-in (Keycloak, Google)." data-ru="Доступ по входу KH Build (Keycloak, Google).">Access is by KH Build sign-in (Keycloak, Google).</footer>
|
||||
</main>
|
||||
<script>
|
||||
(function () {
|
||||
var name = 'khbuild_language', valid = { en: 1, ru: 1 };
|
||||
function read() { var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); var v = m && decodeURIComponent(m[1]); return v && valid[v] ? v : 'en'; }
|
||||
function apply(lang, persist) {
|
||||
document.documentElement.lang = lang;
|
||||
[].forEach.call(document.querySelectorAll('[data-en][data-ru]'), function (el) { el.textContent = el.dataset[lang]; });
|
||||
[].forEach.call(document.querySelectorAll('[data-language]'), function (b) { b.setAttribute('aria-pressed', String(b.dataset.language === lang)); });
|
||||
if (persist) document.cookie = name + '=' + lang + '; Max-Age=31536000; Path=/; SameSite=Lax';
|
||||
}
|
||||
[].forEach.call(document.querySelectorAll('[data-language]'), function (b) { b.addEventListener('click', function () { apply(b.dataset.language, true); }); });
|
||||
apply(read(), false);
|
||||
})();
|
||||
</script></body></html>`;
|
||||
}
|
||||
51
packages/reports/src/reports.test.ts
Normal file
51
packages/reports/src/reports.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { REPORT_LINKS } from "./links.js";
|
||||
import { renderIndex } from "./page.js";
|
||||
import { reportsSchema } from "./settings.js";
|
||||
|
||||
describe("список отчётов", () => {
|
||||
it("содержит Гант и ARIS процесса khbuild_process, оба на странице визуализатора", () => {
|
||||
const g = REPORT_LINKS.find((l) => l.id === "khbuild_process_gantt");
|
||||
const a = REPORT_LINKS.find((l) => l.id === "khbuild_process_aris");
|
||||
expect(g?.group).toBe("visualizations");
|
||||
expect(g?.href).toBe("/viz/?view=gantt");
|
||||
expect(a?.href).toBe("/viz/?view=aris");
|
||||
});
|
||||
|
||||
it("все ссылки относительные и id уникальны", () => {
|
||||
expect(REPORT_LINKS.every((l) => l.href.startsWith("/") && !l.href.startsWith("//"))).toBe(true);
|
||||
expect(new Set(REPORT_LINKS.map((l) => l.id)).size).toBe(REPORT_LINKS.length);
|
||||
});
|
||||
|
||||
it("страница открывает каждую ссылку в новой вкладке, есть оба языка и обе группы", () => {
|
||||
const html = renderIndex();
|
||||
expect(html.match(/target="_blank"/g)?.length).toBe(REPORT_LINKS.length);
|
||||
expect(html).toContain('href="/viz/?view=gantt"');
|
||||
expect(html).toContain("Гант");
|
||||
expect(html).toContain("Reports");
|
||||
expect(html).toContain("Visualizations");
|
||||
expect(html).toContain("No items yet."); // группа отчётов пока пуста
|
||||
});
|
||||
|
||||
it("экранирует разметку в названиях", () => {
|
||||
const html = renderIndex([{ id: "x", group: "reports", title: { en: "<b>&", ru: "<b>&" }, description: { en: "d", ru: "d" }, href: "/x", badge: "X" }]);
|
||||
expect(html).not.toContain("<b>&<");
|
||||
expect(html).toContain("<b>&");
|
||||
});
|
||||
});
|
||||
|
||||
describe("http-api и настройки", () => {
|
||||
const app = buildApi();
|
||||
it("healthz, страница и json", async () => {
|
||||
expect((await app.inject("/healthz")).json()).toMatchObject({ ok: true, links: REPORT_LINKS.length });
|
||||
const page = await app.inject("/");
|
||||
expect(page.statusCode).toBe(200);
|
||||
expect(page.headers["content-type"]).toContain("text/html");
|
||||
expect((await app.inject("/api/links")).json()).toHaveLength(REPORT_LINKS.length);
|
||||
});
|
||||
it("секция настроек необязательна", () => {
|
||||
expect(reportsSchema.parse(undefined)).toEqual({ http: { host: "0.0.0.0", port: 8087 } });
|
||||
expect(reportsSchema.parse({ http: { port: 9000 } }).http.port).toBe(9000);
|
||||
});
|
||||
});
|
||||
9
packages/reports/src/settings.ts
Normal file
9
packages/reports/src/settings.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Секция `reports` в settings.json5 необязательна: без неё действуют значения по умолчанию. */
|
||||
export const reportsSchema = z
|
||||
.object({
|
||||
http: z.object({ host: z.string().default("0.0.0.0"), port: z.number().default(8087) }).default({}),
|
||||
})
|
||||
.default({});
|
||||
export type ReportsSettings = z.infer<typeof reportsSchema>;
|
||||
6
packages/reports/tsconfig.json
Normal file
6
packages/reports/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user