import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { FastifyInstance } from "fastify"; import { inflateSync } from "node:zlib"; import { buildApp } from "../src/app.ts"; import { QUESTIONS } from "../src/modules/hr/questions.ts"; import { sweepHr } from "../src/modules/hr/index.ts"; import { createMockProdamus, mockProdamusWebhook } from "../src/modules/billing/mock-prodamus.ts"; import { createTestDb } from "./helpers/db.ts"; import { mockTtf } from "./helpers/font.ts"; let app: FastifyInstance; let db: Awaited>; let clock = Date.parse("2026-11-15T10:00:00Z"); const PASS = "correct-horse-9"; const JSON_H = { "content-type": "application/json" }; const MIN = 60_000; const HOUR = 60 * MIN; beforeEach(async () => { clock = Date.parse("2026-11-15T10:00:00Z"); db = await createTestDb(); app = await buildApp({ db, accounts: { now: () => clock }, hr: { fontData: mockTtf() } }); }); afterEach(async () => app.close()); async function user(email = "hr@example.com", credits = 2) { const res = await app.inject({ method: "POST", url: "/api/auth/register", payload: { email, password: PASS }, headers: JSON_H }); const id = (await db.query<{ id: string }>("SELECT id FROM users WHERE email = $1", [email])).rows[0]?.id as string; if (credits) await db.query("INSERT INTO hr_balances (user_id, credits) VALUES ($1, $2)", [id, credits]); const cookie = String(res.headers["set-cookie"]).split(";")[0] ?? ""; const csrf = (await db.query<{ csrf_token: string }>("SELECT csrf_token FROM sessions WHERE user_id = $1", [id])).rows[0]?.csrf_token as string; return { id, cookie, csrf }; } type U = Awaited>; const invite = (u: U, body: unknown = { position: "operator", label: "Кандидат 17" }) => app.inject({ method: "POST", url: "/api/hr/invites", payload: body as object, headers: { ...JSON_H, cookie: u.cookie, "x-csrf-token": u.csrf } }); const balance = async (u: U) => ((await app.inject({ method: "GET", url: "/api/hr/balance", headers: { cookie: u.cookie } })).json() as { credits: number }).credits; const tokenOf = (link: string) => link.split("/").pop() as string; const api = (token: string, path = "") => `/api/hr/test/${token}${path}`; const consent = (token: string) => app.inject({ method: "POST", url: api(token, "/consent"), payload: { version: "2026-11-15" }, headers: JSON_H }); const submit = (token: string, answers: unknown) => app.inject({ method: "POST", url: api(token, "/answers"), payload: { answers }, headers: JSON_H }); const pick = (kind: "best" | "worst") => Object.fromEntries( QUESTIONS.map((q) => { const sorted = [...q.options].sort((a, b) => b.points - a.points); return [q.id, (kind === "best" ? sorted[0] : sorted[sorted.length - 1])?.text]; }), ); async function fresh(u: U, position = "operator") { const res = await invite(u, { position, label: "Кандидат 17" }); const id = (res.json() as { id: string }).id; return { id, token: tokenOf((res.json() as { link: string }).link) }; } const pdfText = (buf: Buffer) => { const s = buf.toString("latin1"); return [...s.matchAll(/stream\n([\s\S]*?)\nendstream/g)].map((m) => { try { return inflateSync(Buffer.from(m[1] as string, "latin1")).toString("latin1"); } catch { return ""; } }).join("\n"); }; describe("Requirement: Приглашение кандидата", () => { it("Scenario: Создание приглашения", async () => { const u = await user(); const res = await invite(u); expect(res.statusCode).toBe(201); expect((res.json() as { link: string }).link).toMatch(/^\/hr\/test\/[A-Za-z0-9_-]{16,}$/); expect(await balance(u)).toBe(1); const row = (await db.query<{ token_hash: string }>("SELECT token_hash FROM hr_invites")).rows[0]; expect(row?.token_hash).not.toContain(tokenOf((res.json() as { link: string }).link)); }); it("Scenario: Нет кредитов", async () => { const u = await user("hr@example.com", 0); const res = await invite(u); expect(res.statusCode).toBe(402); expect(res.json()).toEqual({ error: "no_credits" }); }); it("Scenario: Без входа и CSRF, неверные данные", async () => { const u = await user(); expect((await app.inject({ method: "POST", url: "/api/hr/invites", payload: { position: "operator", label: "x" }, headers: JSON_H })).statusCode).toBe(401); expect((await app.inject({ method: "POST", url: "/api/hr/invites", payload: { position: "operator", label: "x" }, headers: { ...JSON_H, cookie: u.cookie } })).statusCode).toBe(403); expect((await invite(u, { position: "ceo", label: "x" })).statusCode).toBe(400); expect((await invite(u, { position: "sales", label: "" })).statusCode).toBe(400); expect(await balance(u)).toBe(2); }); it("Scenario: Просроченная ссылка", async () => { const u = await user(); const { token } = await fresh(u); clock += 73 * HOUR; const res = await app.inject({ method: "GET", url: api(token) }); expect(res.statusCode).toBe(410); expect(res.json()).toEqual({ error: "link_expired" }); expect(await sweepHr(db, clock)).toMatchObject({ expired: 1 }); expect(await balance(u)).toBe(2); }); it("Scenario: Неизвестная ссылка", async () => { const res = await app.inject({ method: "GET", url: api("A".repeat(22)) }); expect(res.statusCode).toBe(404); }); }); describe("Requirement: Согласие до начала теста", () => { it("Scenario: Вопросы без согласия", async () => { const { token } = await fresh(await user()); const res = await app.inject({ method: "GET", url: api(token, "/questions") }); expect(res.statusCode).toBe(403); expect(res.json()).toEqual({ error: "consent_required" }); }); it("Scenario: Согласие и вопросы", async () => { const { token } = await fresh(await user()); expect((await consent(token)).statusCode).toBe(200); const res = await app.inject({ method: "GET", url: api(token, "/questions") }); const body = res.json() as { questions: { id: string; options: string[] }[] }; expect(body.questions).toHaveLength(QUESTIONS.length); expect(res.body).not.toContain("points"); expect(new Set(body.questions.map((q) => q.id).map((id) => id[0]))).toEqual(new Set(["n", "l", "s"])); const row = (await db.query<{ consent_at: unknown; consent_version: string }>("SELECT consent_at, consent_version FROM hr_invites")).rows[0]; expect(row?.consent_at).toBeTruthy(); expect(row?.consent_version).toBe("2026-11-15"); }); it("Scenario: Неверная версия согласия", async () => { const { token } = await fresh(await user()); const res = await app.inject({ method: "POST", url: api(token, "/consent"), payload: { version: "old" }, headers: JSON_H }); expect(res.statusCode).toBe(400); }); }); describe("Requirement: Прохождение и одноразовость", () => { it("Scenario: Успешное прохождение", async () => { const { token } = await fresh(await user()); await consent(token); const res = await submit(token, pick("best")); expect(res.statusCode).toBe(200); expect(res.json()).toEqual({ status: "completed" }); }); it("Scenario: Повторная отправка", async () => { const { token } = await fresh(await user()); await consent(token); await submit(token, pick("best")); const res = await submit(token, pick("worst")); expect(res.statusCode).toBe(410); expect(res.json()).toEqual({ error: "link_used" }); }); it("Scenario: Неполные ответы", async () => { const { token } = await fresh(await user()); await consent(token); const part = pick("best"); delete part.n1; expect((await submit(token, part)).json()).toEqual({ error: "invalid_answers" }); expect((await submit(token, { ...pick("best"), n1: "нет такого" })).statusCode).toBe(400); expect((await submit(token, pick("best"))).statusCode).toBe(200); }); it("Scenario: Время вышло", async () => { const { token } = await fresh(await user()); await consent(token); clock += 31 * MIN; const res = await submit(token, pick("best")); expect(res.statusCode).toBe(410); expect(res.json()).toEqual({ error: "time_expired" }); }); it("Scenario: Ответы кандидата не сохраняются", async () => { const { token } = await fresh(await user()); await consent(token); await submit(token, pick("best")); const r = (await db.query<{ result: { items: { chosen: string }[] } }>("SELECT result FROM hr_invites")).rows[0]; expect(r?.result.items.length).toBe(QUESTIONS.length); }); }); describe("Requirement: Прозрачный скоринг и отчёт-рекомендация", () => { it("Scenario: Высокий результат", async () => { const u = await user(); const { id, token } = await fresh(u); await consent(token); await submit(token, pick("best")); const sum = (await app.inject({ method: "GET", url: `/api/hr/checks/${id}`, headers: { cookie: u.cookie } })).json() as { total: number; recommendation: string }; expect(sum).toMatchObject({ total: 100, recommendation: "recommended" }); const res = await app.inject({ method: "GET", url: `/api/hr/checks/${id}/report`, headers: { cookie: u.cookie } }); expect(res.statusCode).toBe(200); expect(res.headers["content-type"]).toBe("application/pdf"); expect(res.rawPayload.subarray(0, 5).toString()).toBe("%PDF-"); expect(pdfText(res.rawPayload).length).toBeGreaterThan(100); }); it("Scenario: Низкий результат", async () => { const u = await user(); const { id, token } = await fresh(u, "sales"); await consent(token); await submit(token, pick("worst")); const sum = (await app.inject({ method: "GET", url: `/api/hr/checks/${id}`, headers: { cookie: u.cookie } })).json() as { total: number; recommendation: string; attention: string[] }; expect(sum).toMatchObject({ total: 0, recommendation: "more_assessment" }); expect(sum.attention).toHaveLength(3); expect(JSON.stringify(sum).toLowerCase()).not.toContain("отказ"); }); it("Scenario: Чужой отчёт и незавершённая проверка", async () => { const u = await user(); const other = await user("other@example.com", 0); const { id, token } = await fresh(u); expect((await app.inject({ method: "GET", url: `/api/hr/checks/${id}/report`, headers: { cookie: u.cookie } })).statusCode).toBe(404); await consent(token); await submit(token, pick("best")); expect((await app.inject({ method: "GET", url: `/api/hr/checks/${id}/report`, headers: { cookie: other.cookie } })).statusCode).toBe(404); expect((await app.inject({ method: "GET", url: `/api/hr/checks/${id}`, headers: { cookie: other.cookie } })).statusCode).toBe(404); }); it("Scenario: Методика открыта, ключ ответов скрыт", async () => { const res = await app.inject({ method: "GET", url: "/api/hr/methodology" }); const m = res.json() as { weights: Record>; bands: unknown[] }; expect(m.weights.operator).toEqual({ numerals: 0.3, literacy: 0.3, stress: 0.4 }); expect(m.bands).toHaveLength(3); expect(res.body).not.toContain("рабочих дня"); }); }); describe("Requirement: Пакеты проверок и удаление данных", () => { it("Scenario: Оплата пакета", async () => { const u = await user("buyer@example.com", 0); await app.close(); app = await buildApp({ db, accounts: { now: () => clock }, billing: { provider: createMockProdamus() }, hr: { fontData: mockTtf() } }); const h = { ...JSON_H, cookie: u.cookie, "x-csrf-token": u.csrf }; const o = (await app.inject({ method: "POST", url: "/api/orders", payload: { productId: "hr-checks-10" }, headers: h })).json() as { orderId: string }; const w = mockProdamusWebhook({ order_id: "pay-1", order_num: o.orderId, sum: "3900.00", payment_status: "success" }); const hook = () => app.inject({ method: "POST", url: "/api/billing/webhook", payload: w.body, headers: { "content-type": "application/x-www-form-urlencoded", sign: w.sign } }); expect((await hook()).statusCode).toBe(200); await hook(); expect(await balance(u)).toBe(10); }); it("Scenario: Отмена неначатого приглашения", async () => { const u = await user(); const { id, token } = await fresh(u); expect(await balance(u)).toBe(1); const del = await app.inject({ method: "DELETE", url: `/api/hr/checks/${id}`, headers: { cookie: u.cookie, "x-csrf-token": u.csrf } }); expect(del.statusCode).toBe(204); expect(await balance(u)).toBe(2); expect((await app.inject({ method: "GET", url: api(token) })).statusCode).toBe(404); }); it("Scenario: Результаты удаляются через 180 дней", async () => { const u = await user(); const { token } = await fresh(u); await consent(token); await submit(token, pick("best")); expect(await sweepHr(db, clock + 179 * 24 * HOUR)).toMatchObject({ deleted: 0 }); expect(await sweepHr(db, clock + 181 * 24 * HOUR)).toMatchObject({ deleted: 1 }); }); }); describe("Страница кандидата", () => { it("отдаёт HTML без inline-скриптов и экранирует токен", async () => { const { token } = await fresh(await user()); const res = await app.inject({ method: "GET", url: `/hr/test/${token}` }); expect(res.statusCode).toBe(200); expect(res.body).toContain('src="/hr/test.js"'); expect(res.body).not.toMatch(/