import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { FastifyInstance } from "fastify"; import { buildApp } from "../src/app.ts"; import { LlmUnavailableError } from "../src/modules/audits/llm.ts"; import { mockLlm } from "../src/modules/audits/mock-llm.ts"; import { mockChannel } from "../src/modules/content/mock-channel.ts"; import { createTestDb } from "./helpers/db.ts"; const BASE = "https://clt.example"; const ADMIN = { "content-type": "application/json", authorization: "Bearer mock-admin-token" }; let clock = 0; let app: FastifyInstance; let db: Awaited>; let channel: ReturnType; async function setup(extra: Record = {}) { clock = Date.parse("2026-11-10T10:00:00Z"); db = await createTestDb(); channel = mockChannel(); app = await buildApp({ db, accounts: { now: () => clock }, content: { baseUrl: BASE, adminToken: "mock-admin-token", sweepIntervalMs: 0, telegram: { client: channel, chatId: "@clt_channel" }, ...extra }, }); } beforeEach(() => setup()); afterEach(async () => app.close()); const post = (o: Record = {}) => ({ slug: "cold-tone", title: "Разбор ошибки: холодный тон", summary: "Почему клиент уходит после сухого ответа", body: "Первый абзац.\n\nВторой абзац.", topic: "mistakes", ctaProduct: "express-audit", ...o, }); const create = (o: Record = {}) => app.inject({ method: "POST", url: "/api/admin/content/posts", headers: ADMIN, payload: post(o) }); const approve = (id: string) => app.inject({ method: "POST", url: `/api/admin/content/posts/${id}/approve`, headers: { authorization: ADMIN.authorization } }); async function publish(o: Record = {}) { const pid = (await create(o)).json().id as string; await approve(pid); clock += 1000; await app.publishContent(); return pid; } describe("Requirement: Модерация и расписание публикаций", () => { it("Scenario: Публикация одобренного поста по расписанию", async () => { const id = (await create({ publishAt: "2026-11-10T09:00:00Z" })).json().id as string; await approve(id); expect(await app.publishContent()).toEqual({ published: 1, sent: 1 }); const status = (await db.query<{ status: string }>("SELECT status FROM content_posts WHERE id = $1", [id])).rows[0]?.status; expect(status).toBe("published"); expect((await app.inject({ url: "/blog" })).body).toContain("Разбор ошибки: холодный тон"); }); it("Scenario: Неодобренный пост не публикуется", async () => { await create({ publishAt: "2026-11-10T09:00:00Z" }); expect((await app.publishContent()).published).toBe(0); expect((await app.inject({ url: "/blog" })).body).not.toContain("холодный тон"); }); it("Scenario: Админ-API без токена", async () => { const res = await app.inject({ method: "POST", url: "/api/admin/content/posts", payload: post() }); expect(res.statusCode).toBe(401); expect(res.json()).toEqual({ error: "unauthenticated" }); }); it("Scenario: Автоодобрение по решению PM", async () => { await app.close(); await setup({ autoApprove: true }); expect((await create()).json().status).toBe("approved"); }); it("Scenario: Автоодобрение выключено по умолчанию", async () => { expect((await create()).json().status).toBe("draft"); }); }); describe("Requirement: Ссылки только на собственные домены", () => { it("Scenario: Чужая ссылка отклонена", async () => { const res = await create({ body: "Смотрите https://evil.example/x" }); expect(res.statusCode).toBe(422); expect(res.json()).toEqual({ error: "foreign_link" }); }); it("Scenario: Своя ссылка допустима", async () => { expect((await create({ body: `Подробнее ${BASE}/legal/offer` })).statusCode).toBe(201); }); it("Scenario: Неизвестный продукт", async () => { const res = await create({ ctaProduct: "nope" }); expect(res.statusCode).toBe(422); expect(res.json()).toEqual({ error: "unknown_product" }); }); it("Scenario: CTA с UTM", async () => { await publish(); const html = (await app.inject({ url: "/blog/cold-tone" })).body; expect(html).toContain(`${BASE}/?utm_source=blog&utm_medium=content&utm_campaign=cold-tone#express-audit`); }); }); describe("Requirement: Блог и SEO", () => { it("Scenario: Sitemap", async () => { await publish(); await create({ slug: "draft-one" }); const xml = (await app.inject({ url: "/sitemap.xml" })).body; expect(xml).toContain(`${BASE}/blog/cold-tone`); expect(xml).not.toContain("draft-one"); }); it("Scenario: Мета-теги", async () => { await publish(); const html = (await app.inject({ url: "/blog/cold-tone" })).body; expect(html).toContain(''); expect(html).toContain('property="og:title"'); expect(html).toContain(``); }); it("Scenario: Черновик недоступен", async () => { await create(); expect((await app.inject({ url: "/blog/cold-tone" })).statusCode).toBe(404); }); it("Scenario: Экранирование", async () => { await publish({ title: "" }); const html = (await app.inject({ url: "/blog" })).body; expect(html).not.toContain("