import { readFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app.ts";
import { renderChapterMarkdown } from "../src/modules/library/chapter.ts";
import { isReviewHost } from "../src/modules/library/config.ts";
import { CHAPTERS, CONTENT_DIR, loadChapters } from "../src/modules/library/chapters.ts";
import { createTestDb } from "./helpers/db.ts";
let app: FastifyInstance;
const PASS = "mock-owner-pass";
const FORM = { "content-type": "application/x-www-form-urlencoded" };
const URL1 = "/library/chapters/osnovy-klientologii";
const chapterText = readFileSync(new URL("chapter-01-osnovy-klientologii.md", CONTENT_DIR), "utf8");
beforeEach(async () => {
app = await buildApp({ db: await createTestDb(), library: { editorPassword: PASS } });
});
afterEach(async () => app.close());
describe("Черновик главы для редакторского ревью", () => {
it("Владелица открывает черновик главы 1", async () => {
const res = await app.inject({ method: "GET", url: URL1 });
expect(res.statusCode).toBe(200);
expect(res.body).toContain("
Глава 1. Основы клиентологии
");
expect(res.body).toContain("Черновик для редакторского ревью");
expect(res.body).toMatch(/[^<]*Клиентоцентричность в госуслугах<\/a>/);
expect(res.body).toContain('id="gosuslugi"');
expect(res.body).toContain('');
expect(res.body).toContain("Раздел оглавления: 1. Основы клиентологии");
});
it("Черновика нет в публичном оглавлении", async () => {
for (const host of ["customer-prod.telecom.quest", "klientologiya.ru", "customer-staging-evil.example.com"]) {
const res = await app.inject({ method: "GET", url: "/library", headers: { host } });
expect(res.statusCode).toBe(200);
expect(res.body).not.toContain(URL1);
expect(res.body).not.toContain("Черновики для редакции");
}
});
it.each(["customer-staging.telecom.quest", "customer-pr16.telecom.quest"])("Черновик в оглавлении версии для проверки: %s", async (host) => {
const res = await app.inject({ method: "GET", url: "/library", headers: { host } });
expect(res.statusCode).toBe(200);
expect(res.body).toContain("Черновики для редакции");
expect(res.body).toContain(`Глава 1. Основы клиентологии`);
expect(res.body).toContain(`Итог редакторской проверки`);
const page = await app.inject({ method: "GET", url: `${URL1}/review`, headers: { host } });
expect(page.statusCode).toBe(200);
});
it("Ссылка на черновик в редакторе", async () => {
const login = await app.inject({ method: "POST", url: "/library/editor/login", headers: FORM, payload: `password=${PASS}` });
const cookie = String(login.headers["set-cookie"]).split(";")[0] as string;
const res = await app.inject({ method: "GET", url: "/library/editor", headers: { cookie } });
expect(res.body).toContain("Черновики глав");
expect(res.body).toContain(`Глава 1. Основы клиентологии`);
const page = await app.inject({ method: "GET", url: URL1, headers: { cookie } });
expect(page.body).toContain('href="/library/editor"');
});
it("Неизвестная глава", async () => {
for (const slug of ["net-takoy-glavy", "constructor", "__proto__"]) {
const res = await app.inject({ method: "GET", url: `/library/chapters/${slug}` });
expect(res.statusCode).toBe(404);
expect(res.body).toContain("Глава не найдена");
}
});
it("Интерфейс главы на казахском и английском, текст — на русском", async () => {
const kk = await app.inject({ method: "GET", url: `${URL1}?lang=kk` });
expect(kk.body).toContain("Тараудың мазмұны");
expect(kk.body).toContain('');
const en = await app.inject({ method: "GET", url: `${URL1}?lang=en` });
expect(en.body).toContain("Russian only");
});
});
describe("Содержание главы 1 по редакционному стандарту", () => {
const ch = loadChapters().get("osnovy-klientologii");
const h2 = chapterText.split(/^## /m).slice(1);
it("Семь разделов по оглавлению задачи", () => {
expect(CHAPTERS.map((c) => c.status)).toEqual(["draft"]);
expect(ch?.toc.map((x) => x.id)).toEqual(["terminy", "put-klienta", "urovni-servisa", "pribyl", "proektirovanie", "gosuslugi", "praktikum", "itog", "utverdit"]);
const titles = ch?.toc.map((x) => x.title).join("\n") ?? "";
for (const w of ["клиентоцентричность", "до, во время и после покупки", "вдохновляющий", "прибыль", "госуслугах", "оценка зрелости"]) expect(titles).toContain(w);
});
it("Структура раздела", () => {
for (const section of h2.slice(0, 6)) {
for (const sub of ["### Ситуация", "**Короткий ответ:**", "### Метод", "### Разбор кейса", "### Задание"]) expect(section).toContain(sub);
}
});
it("Учебный расчёт", () => {
const profit = h2[3] as string;
expect(profit).toContain("### Учебный расчёт");
expect(profit).toContain("цифры условные");
expect(chapterText).toMatch(/повторное обращение из-за нерешённого вопроса/i);
expect(chapterText).toContain("учебный пример");
});
});
const REVIEW = `${URL1}/review`;
const num = (x: string) => Number(x.replace(/\s/g, ""));
describe("Итог редакторской проверки главы", () => {
it("Владелица открывает итог проверки главы 1", async () => {
const res = await app.inject({ method: "GET", url: REVIEW });
expect(res.statusCode).toBe(200);
expect(res.body).toContain("Редакторская проверка: глава 1 «Основы клиентологии»
");
for (const h of ["Критично", "Важно", "Желательно"]) expect(res.body).toMatch(new RegExp(`${h}
`));
expect(res.body).toContain(`href="${URL1}"`);
expect(res.body).toContain('');
const en = await app.inject({ method: "GET", url: `${REVIEW}?lang=en` });
expect(en.body).toContain("Back to the chapter");
});
it("Ссылка на итог проверки с черновика", async () => {
const res = await app.inject({ method: "GET", url: URL1 });
expect(res.body).toContain(`Итог редакторской проверки`);
});
it("Итога проверки нет", async () => {
const res = await app.inject({ method: "GET", url: "/library/chapters/net-takoy-glavy/review" });
expect(res.statusCode).toBe(404);
expect(res.body).toContain("Глава не найдена");
const noReview = await buildApp({
db: await createTestDb(),
library: { editorPassword: PASS, chapters: loadChapters(CONTENT_DIR, [{ ...(CHAPTERS[0] as (typeof CHAPTERS)[0]), review: undefined }]) },
});
const r2 = await noReview.inject({ method: "GET", url: REVIEW });
expect(r2.statusCode).toBe(404);
await noReview.close();
});
});
describe("Глава 1 после редакторской проверки", () => {
const ch = loadChapters().get("osnovy-klientologii");
const gos = chapterText.slice(chapterText.indexOf("## 6."), chapterText.indexOf("## 7."));
it("Три примера госуслуг", () => {
const examples = [...gos.matchAll(/\*\*Учебный пример (\d)\. ([^.]+)/g)].map((m) => `${m[1]} ${m[2]}`);
expect(examples).toHaveLength(3);
expect(examples[0]).toContain("Пособие на ребёнка");
expect(examples[1]).toContain("Замена водительского удостоверения");
expect(examples[2]).toContain("Запись ребёнка в первый класс");
});
it("Расчёт сходится", () => {
const step = (n: number) => chapterText.slice(chapterText.indexOf(`**Шаг ${n}.`)).split("\n")[0] as string;
const saving = (2500 * 150 * 12) / 2;
const retention = (800 / 4) * 12000 * 0.3;
const referrals = 40 * 12000 * 0.3;
expect([saving, retention, referrals]).toEqual([2_250_000, 720_000, 144_000]);
expect(step(1)).toContain("экономия — 2 250 000 ₽");
expect(step(2)).toContain("720 000 ₽ прибыли");
expect(step(3)).toContain("144 000 ₽ прибыли");
const total = /\*\*Итог учебного расчёта:\*\* ([\d ]+) \+ ([\d ]+) \+ ([\d ]+) = \*\*([\d ]+) ₽ в год\*\*/.exec(chapterText);
expect(total).not.toBeNull();
const [, a, b, c, sum] = total as RegExpExecArray;
expect(num(a as string) + num(b as string) + num(c as string)).toBe(num(sum as string));
expect(num(sum as string)).toBe(saving + retention + referrals);
});
it("Навигация по главе", async () => {
expect(ch?.toc).toHaveLength(9);
expect(ch?.toc.slice(-2).map((x) => x.title)).toEqual(["Итог главы", "Что утвердить автору"]);
const res = await app.inject({ method: "GET", url: URL1 });
for (const x of ch?.toc ?? []) {
expect(res.body).toContain(`href="#${x.id}"`);
expect(res.body).toContain(`id="${x.id}"`);
}
expect(chapterText).not.toContain("Заметки для редактора");
});
});
describe("Безопасный вывод текста главы", () => {
it("Тег в тексте главы", () => {
const r = renderChapterMarkdown("# Глава\n\nТекст и **жирный** и *курсив*.\n\n| a | |\n|---|---|\n| 1 | 2 |\n");
expect(r.html).toContain("<script>");
expect(r.html).not.toContain("