feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

+505
View File
@@ -0,0 +1,505 @@
import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
type InboxMessage = {
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type AttemptSnapshot = {
id: string;
kind: "root" | "demo_express";
current_item: { id: string; prompt: string } | null;
progress: { answered_items: number; max_items: number };
};
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const password = "correct horse battery staple 2026";
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
function baseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local end-to-end base URL is not configured.");
return value;
}
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token)
throw new Error("The local registration mailbox fixture is not configured.");
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function registerVerifiedCandidate(page: Page): Promise<void> {
const email = `assessment-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await expect(
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
).toBeVisible();
await expect(page.getByText(/C4/)).toHaveCount(0);
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Кандидат/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await expect.poll(() => page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
const confirmResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/email-verifications",
);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
expect((await confirmResponse).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
}
async function grantC3(page: Page): Promise<void> {
await page.goto("/candidate/privacy");
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
const response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" &&
new URL(item.url()).pathname === "/api/v1/me/consents/c3",
);
await page.getByRole("button", { name: "Дать согласие C3" }).click();
expect((await response).status()).toBe(200);
}
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
const response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" &&
new URL(item.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await response).status()).toBe(200);
}
async function focusWithKeyboard(page: Page, target: Locator): Promise<void> {
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 80; attempt += 1) {
await page.keyboard.press("Tab");
if (await target.evaluate((element) => element === document.activeElement)) {
const visible = await target.evaluate((element) => {
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
const style = getComputedStyle(element);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(visible).toBe(true);
return;
}
}
throw new Error("Keyboard navigation did not reach the assessment action.");
}
async function expectNoHorizontalOverflow(page: Page, width: number): Promise<void> {
await page.setViewportSize({ width, height: 900 });
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
}
async function navigateInApp(page: Page, path: string): Promise<void> {
await page.evaluate((target) => {
window.history.pushState(window.history.state, "", target);
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
}, path);
}
function attemptPath(
response: { url(): string; request(): { method(): string } },
method: string,
): boolean {
return (
response.request().method() === method &&
/^\/api\/v1\/me\/assessment-attempts\/[^/]+$/.test(new URL(response.url()).pathname)
);
}
async function answerRequiredNumericItems(
page: Page,
attemptId: string,
itemCount: number,
): Promise<number> {
let submitted = 0;
for (let sequence = 1; sequence <= itemCount; sequence += 1) {
await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible();
const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ });
await focusWithKeyboard(page, answerField);
await page.keyboard.type("1");
const answerResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`,
);
const submitButton = page.getByRole("button", { name: "Отправить ответ" });
await focusWithKeyboard(page, submitButton);
await page.keyboard.press("Enter");
expect((await answerResponsePromise).status()).toBe(200);
submitted += 1;
}
return submitted;
}
test("candidate can review, resume, and finish separate assessment modes", async ({ page }) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the isolated reviewed assessment-bank and mail fixtures.",
);
test.setTimeout(120_000);
await registerVerifiedCandidate(page);
await grantC3(page);
await saveAssessmentQuestionnaire(page);
await page.goto("/candidate/assessment");
await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible();
await expect(page.getByText(/Метод:/)).toBeVisible();
await expect(page.getByText("Лимит времени", { exact: true })).toBeVisible();
await expect(page.getByText(/Камера, микрофон и запись экрана не используются/)).toBeVisible();
await page.getByLabel("Язык задания").selectOption("python");
await expect(page.getByLabel("Язык задания")).toHaveValue("python");
await expectNoHorizontalOverflow(page, 360);
await expectNoHorizontalOverflow(page, 1280);
await expectNoHorizontalOverflow(page, 360);
const createRealResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
);
await page.getByRole("button", { name: "Начать полную проверку" }).click();
const createRealResponse = await createRealResponsePromise;
expect(createRealResponse.status()).toBe(201);
expect(createRealResponse.request().postDataJSON()).toMatchObject({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "python",
});
const realAttempt = (await createRealResponse.json()) as AttemptSnapshot;
expect(realAttempt.kind).toBe("root");
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${realAttempt.id}$`));
const startRealResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`,
);
const firstResume = page.getByRole("button", { name: "Начать или продолжить" });
await focusWithKeyboard(page, firstResume);
await page.keyboard.press("Enter");
const firstResumeResponse = await startRealResponsePromise;
expect(firstResumeResponse.status()).toBe(200);
const firstRealSnapshot = (await firstResumeResponse.json()) as AttemptSnapshot;
expect(firstRealSnapshot.current_item?.id).toBeTruthy();
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
await expectNoHorizontalOverflow(page, 360);
await page.screenshot({
path: `${artifactsDirectory}/assessment-attempt-360.png`,
animations: "disabled",
});
await expectNoHorizontalOverflow(page, 1280);
await page.screenshot({
path: `${artifactsDirectory}/assessment-attempt-1280.png`,
animations: "disabled",
});
await expectNoHorizontalOverflow(page, 360);
const reloadResponsePromise = page.waitForResponse((response) => attemptPath(response, "GET"));
await page.reload();
const reloadedRealResponse = await reloadResponsePromise;
expect(reloadedRealResponse.status()).toBe(200);
const reloadedRealSnapshot = (await reloadedRealResponse.json()) as AttemptSnapshot;
expect(reloadedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id);
const resumeAgainPromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`,
);
await page.getByRole("button", { name: "Начать или продолжить" }).click();
const resumeAgainResponse = await resumeAgainPromise;
expect(resumeAgainResponse.status()).toBe(200);
const resumedRealSnapshot = (await resumeAgainResponse.json()) as AttemptSnapshot;
expect(resumedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id);
await expectNoHorizontalOverflow(page, 360);
expect(resumedRealSnapshot.progress.max_items).toBeGreaterThan(0);
expect(resumedRealSnapshot.progress.answered_items).toBe(0);
expect(
await answerRequiredNumericItems(page, realAttempt.id, resumedRealSnapshot.progress.max_items),
).toBe(resumedRealSnapshot.progress.max_items);
await expect(page.getByRole("button", { name: "Завершить проверку" })).toBeVisible();
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toHaveCount(0);
const finalizeRealResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${realAttempt.id}/finalize`,
);
const resultResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
response.status() === 200 &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${realAttempt.id}/result`,
);
const finalizeRootButton = page.getByRole("button", { name: "Завершить проверку" });
await focusWithKeyboard(page, finalizeRootButton);
await page.keyboard.press("Enter");
expect((await finalizeRealResponsePromise).status()).toBe(200);
const resultResponse = await resultResponsePromise;
expect(resultResponse.status()).toBe(200);
expect(await resultResponse.json()).toMatchObject({
attempt_id: realAttempt.id,
kind: "root",
task_language: "python",
});
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
await page.goto("/candidate/assessment");
await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible();
const createExpressResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
);
await page.getByRole("button", { name: "Начать демонстрацию" }).click();
const createExpressResponse = await createExpressResponsePromise;
expect(createExpressResponse.status()).toBe(201);
const expressAttempt = (await createExpressResponse.json()) as AttemptSnapshot;
expect(expressAttempt.kind).toBe("demo_express");
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`));
const startExpressResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
);
await page.getByRole("button", { name: "Начать или продолжить" }).click();
const startExpressResponse = await startExpressResponsePromise;
expect(startExpressResponse.status()).toBe(200);
const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot;
expect(firstExpressSnapshot.current_item?.id).toBeTruthy();
await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`);
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0);
await expect(page.getByRole("heading", { name: "Демонстрационная проверка" })).toHaveCount(0);
await navigateInApp(page, `/candidate/assessment/${expressAttempt.id}`);
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toBeVisible();
const resumedExpressResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
);
await page.getByRole("button", { name: "Начать или продолжить" }).click();
const resumedExpressResponse = await resumedExpressResponsePromise;
expect(resumedExpressResponse.status()).toBe(200);
const resumedExpressSnapshot = (await resumedExpressResponse.json()) as AttemptSnapshot;
expect(resumedExpressSnapshot.current_item?.id).toBe(firstExpressSnapshot.current_item?.id);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
const answerCommands: { key: string | undefined; body: string | null }[] = [];
const captureAnswerCommand = (request: Request) => {
if (
request.method() !== "POST" ||
new URL(request.url()).pathname !==
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`
) {
return;
}
answerCommands.push({
key: request.headers()["idempotency-key"],
body: request.postData(),
});
};
page.on("request", captureAnswerCommand);
await expectNoHorizontalOverflow(page, 360);
const numberAnswer = page.getByRole("textbox", { name: /^Числовой ответ/ });
await focusWithKeyboard(page, numberAnswer);
await numberAnswer.fill("1");
const firstSubmitButton = page.getByRole("button", { name: "Отправить ответ" });
await focusWithKeyboard(page, firstSubmitButton);
await page.context().setOffline(true);
await page.keyboard.press("Enter");
await expect(page.getByRole("alert")).toContainText("Не удалось связаться с сервером");
await expect.poll(() => answerCommands.length).toBe(1);
const offlineCommand = answerCommands[0];
expect(offlineCommand?.key).toBeTruthy();
await expect(
page.getByRole("button", { name: "Повторить отправку того же ответа" }),
).toBeVisible();
await page.context().setOffline(false);
let forwardedResponses = 0;
await page.route("**/api/v1/me/assessment-attempts/*/answers", async (route: Route) => {
const response = await route.fetch();
forwardedResponses += 1;
if (forwardedResponses === 1) {
await route.fulfill({ response, body: "{}" });
return;
}
await route.fulfill({ response });
});
const firstAnswerResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
);
await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click();
expect((await firstAnswerResponsePromise).status()).toBe(200);
await expect(page.getByRole("alert")).toBeVisible();
const retryResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
);
const savedAfterAnswerPromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`,
);
await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click();
expect((await retryResponsePromise).status()).toBe(200);
const savedAfterAnswer = await savedAfterAnswerPromise;
expect(savedAfterAnswer.status()).toBe(200);
const savedAfterAnswerSnapshot = (await savedAfterAnswer.json()) as AttemptSnapshot;
expect(savedAfterAnswerSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id);
expect(savedAfterAnswerSnapshot.progress.answered_items).toBe(1);
expect(answerCommands).toHaveLength(3);
expect(answerCommands[0]?.key).toBeTruthy();
expect(answerCommands[1]?.key).toBe(answerCommands[0]?.key);
expect(answerCommands[1]?.body).toBe(answerCommands[0]?.body);
expect(answerCommands[2]?.key).toBe(answerCommands[0]?.key);
expect(answerCommands[2]?.body).toBe(answerCommands[0]?.body);
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
await page.unroute("**/api/v1/me/assessment-attempts/*/answers");
const expressReloadResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`,
);
await page.reload();
const expressReloadResponse = await expressReloadResponsePromise;
expect(expressReloadResponse.status()).toBe(200);
const reloadedExpressSnapshot = (await expressReloadResponse.json()) as AttemptSnapshot;
expect(reloadedExpressSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id);
expect(reloadedExpressSnapshot.progress.answered_items).toBe(1);
const resumeSavedProgressPromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
);
await page.getByRole("button", { name: "Начать или продолжить" }).click();
const resumeSavedProgressResponse = await resumeSavedProgressPromise;
expect(resumeSavedProgressResponse.status()).toBe(200);
const resumedExpressProgress = (await resumeSavedProgressResponse.json()) as AttemptSnapshot;
expect(resumedExpressProgress.current_item?.id).toBe(reloadedExpressSnapshot.current_item?.id);
expect(resumedExpressProgress.progress.answered_items).toBe(1);
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
for (const sequence of [2, 3]) {
const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ });
await focusWithKeyboard(page, answerField);
await page.keyboard.type("1");
const answerResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
);
const submitButton = page.getByRole("button", { name: "Отправить ответ" });
await focusWithKeyboard(page, submitButton);
await page.keyboard.press("Enter");
expect((await answerResponsePromise).status()).toBe(200);
if (sequence < 3)
await expect(page.getByRole("heading", { name: `Задание ${sequence + 1}` })).toBeVisible();
}
const finalizeResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${expressAttempt.id}/finalize`,
);
const finalizeButton = page.getByRole("button", { name: "Завершить проверку" });
await focusWithKeyboard(page, finalizeButton);
await page.keyboard.press("Enter");
expect((await finalizeResponsePromise).status()).toBe(200);
await expect(
page.getByText(
"Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.",
),
).toBeVisible();
await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0);
page.off("request", captureAnswerCommand);
});
+8
View File
@@ -294,6 +294,12 @@ test.describe("company cabinet", () => {
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 412,
);
const csrfFailureResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 403,
);
const refreshedSessionPromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
@@ -301,6 +307,8 @@ test.describe("company cabinet", () => {
response.status() === 200,
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const csrfFailureResponse = await csrfFailureResponsePromise;
expect(await csrfFailureResponse.json()).toMatchObject({ code: "csrf_check_failed" });
await expect(page.getByRole("alert")).toContainText("Проверка входа обновлена");
await refreshedSessionPromise;
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
+558
View File
@@ -0,0 +1,558 @@
import { expect, test, type Locator, type Page, type Response } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type CurrentSessionResponse = {
account: { id: string };
};
type OrganizationResponse = {
id: string;
name: string;
};
type NeedResponse = {
id: string;
title: string;
source_text?: string | null;
version: number;
requirements_version: number;
requirements: {
specialization: { status: string; value: string | null; source?: { origin: string } | null };
required_skills: {
name: string;
status: string;
source?: { origin: string } | null;
}[];
tasks: { text: string; status: string; source?: { origin: string } | null }[];
grade: {
status: string;
value: string | null;
source?: { origin: string } | null;
};
salary: {
status: string;
value: { tax_basis: string } | null;
source?: { origin: string } | null;
};
};
readiness: { status: string; missing_fields: { field: string; question: string }[] };
recommendations: { status: string; categories: unknown[] };
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
const password = "correct horse battery staple 2026";
function baseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local browser test origin is not configured.");
return value;
}
function needCollectionPath(organizationId: string): string {
return `/api/v1/organizations/${organizationId}/needs`;
}
function needPath(organizationId: string, needId: string): string {
return `${needCollectionPath(organizationId)}/${needId}`;
}
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token)
throw new Error("The local registration mailbox fixture is not configured.");
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the expected message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function registerVerifiedEmployer(page: Page): Promise<{ email: string; userId: string }> {
const email = `company-${crypto.randomUUID().slice(0, 8)}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Работодатель/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/employer/company");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Компания" })).toBeVisible();
const loginResponse = await loginResponsePromise;
const currentSession = (await loginResponse.json()) as CurrentSessionResponse;
return { email, userId: currentSession.account.id };
}
async function signInEmployer(page: Page, email: string): Promise<void> {
await page.goto("/employer/needs");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await loginResponsePromise;
}
async function createOrganization(page: Page, name: string): Promise<OrganizationResponse> {
const result = await page.evaluate(
async ({ organizationName, key }) => {
const sessionResponse = await fetch("/api/v1/identity/sessions/current", {
cache: "no-store",
});
if (!sessionResponse.ok) return { status: sessionResponse.status, body: null };
const session = (await sessionResponse.json()) as { csrf_token?: string };
if (!session.csrf_token) return { status: 401, body: null };
const response = await fetch("/api/v1/organizations", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": key,
"X-CSRF-Token": session.csrf_token,
},
body: JSON.stringify({ name: organizationName }),
});
return {
status: response.status,
body: (await response.json()) as OrganizationResponse,
};
},
{ organizationName: name, key: crypto.randomUUID() },
);
if (result.status !== 201 || !result.body) {
throw new Error("Could not create the synthetic organization for the need flow.");
}
return result.body;
}
async function revokeMembership(
organizationId: string,
userId: string,
successorUserId: string,
): Promise<void> {
const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL;
const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN;
if (!fixtureURL || !fixtureToken)
throw new Error("The isolated company fixture is not configured.");
const response = await fetch(new URL(fixtureURL), {
method: "POST",
headers: {
Authorization: `Bearer ${fixtureToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
organization_id: organizationId,
user_id: userId,
successor_user_id: successorUserId,
}),
});
if (response.status !== 204) {
throw new Error(
`The isolated company fixture could not transfer the synthetic membership (status ${response.status}).`,
);
}
}
async function findSkillRow(section: Locator, name: string): Promise<Locator> {
const rows = section.getByRole("listitem");
for (let index = 0; index < (await rows.count()); index += 1) {
const row = rows.nth(index);
if ((await row.locator("input").inputValue()) === name) return row;
}
throw new Error(`The parsed need did not contain the expected skill ${name}.`);
}
function isResponse(response: Response, method: string, path: string, status: number): boolean {
return (
response.request().method() === method &&
new URL(response.url()).pathname === path &&
response.status() === status
);
}
function sanitizedPageError(error: Error, privateValues: string[]): string {
let message = error.message.split("\n", 1)[0] ?? "";
for (const value of privateValues) {
if (value !== "") message = message.replaceAll(value, "[redacted]");
}
message = message
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[email]")
.replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, "[id]");
return `${error.name}: ${message.slice(0, 180)}`;
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("employer needs", () => {
test.skip(
!mailFixtureEnabled || !companyFixtureEnabled,
"Requires the isolated mail and company fixtures.",
);
test("creates, edits, reloads, handles conflicts, and removes private data after owner access ends", async ({
browser,
page,
}) => {
const owner = await registerVerifiedEmployer(page);
const suffix = crypto.randomUUID().slice(0, 8);
const organization = await createOrganization(page, `Need team ${suffix}`);
const sourceText =
"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.";
const pageErrors: string[] = [];
page.on("pageerror", (error) => {
pageErrors.push(sanitizedPageError(error, [owner.email, sourceText, suffix]));
});
await page.goto(`/employer/needs?organization_id=${encodeURIComponent(organization.id)}`);
await expect(
page.getByRole("status").getByText("Потребностей пока нет", { exact: true }),
).toBeVisible();
await page.getByRole("link", { name: "Создать потребность" }).first().click();
await expect(page.getByLabel("Название потребности")).toBeVisible();
await expect(page.getByText("Вакансия для сохранения потребности не требуется.")).toBeVisible();
await expect(page.getByLabel("Грейд")).toHaveValue("");
await expect(page.getByLabel("База суммы")).toHaveValue("");
await expect(
page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."),
).toBeVisible();
await page.getByLabel("Название потребности").fill(`Payments backend ${suffix}`);
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
await page.getByLabel("Описание работы").fill(sourceText);
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
const organizationNeedsPath = needCollectionPath(organization.id);
const createResponsePromise = page.waitForResponse((response) =>
isResponse(response, "POST", organizationNeedsPath, 201),
);
await page.getByRole("button", { name: "Создать потребность" }).click();
const createResponse = await createResponsePromise;
const createRequest = createResponse.request();
expect(createRequest.headers()["x-csrf-token"]).toBeTruthy();
expect(createRequest.headers()["idempotency-key"]).toBeTruthy();
const created = (await createResponse.json()) as NeedResponse;
expect(created.version).toBe(1);
expect(created.requirements_version).toBe(1);
expect(created.requirements.grade.status).toBe("unknown");
expect(created.requirements.grade.value).toBeNull();
expect(created.readiness.missing_fields.map((field) => field.field)).toContain("salary");
expect(created.recommendations.status).toBe("not_available");
const requiredSkills = page
.getByRole("heading", { name: "Обязательные навыки" })
.locator("xpath=..");
await expect(requiredSkills.getByRole("listitem")).toHaveCount(3);
const goRow = await findSkillRow(requiredSkills, "Go");
const postgresRow = await findSkillRow(requiredSkills, "PostgreSQL");
const temporalRow = await findSkillRow(requiredSkills, "Temporal");
await goRow.getByRole("button", { name: "Подтвердить", exact: true }).click();
await temporalRow.locator("input").fill("TemporalDB");
await postgresRow.getByRole("button", { name: "Удалить", exact: true }).click();
const needId = created.id;
const itemPath = needPath(organization.id, needId);
const firstSavePromise = page.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const firstSave = (await firstSavePromise).json() as Promise<NeedResponse>;
const saved = await firstSave;
expect(saved.version).toBe(2);
expect(saved.requirements.required_skills.map((skill) => skill.name)).toEqual([
"Go",
"TemporalDB",
]);
expect(saved.recommendations.status).toBe("pending");
expect(saved.recommendations.categories).toEqual([]);
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const reloadResponsePromise = page.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await page.reload();
const reloaded = (await reloadResponsePromise).json() as Promise<NeedResponse>;
const reloadedNeed = await reloaded;
expect(reloadedNeed.requirements.required_skills.map((skill) => skill.name)).not.toContain(
"PostgreSQL",
);
await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText);
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const secondPage = await secondContext.newPage();
try {
await signInEmployer(secondPage, owner.email);
await secondPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(
`Payments backend ${suffix}`,
);
const firstWindowTitle = `Payments backend first ${suffix}`;
await page.getByLabel("Название потребности").fill(firstWindowTitle);
const firstWindowSave = page.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const firstWindowResponse = await firstWindowSave;
const firstWindowSaved = (await firstWindowResponse.json()) as NeedResponse;
expect(firstWindowSaved.title).toBe(firstWindowTitle);
await expect(page.getByLabel("Название потребности")).toHaveValue(firstWindowTitle);
const secondWindowDraft = `Payments backend second ${suffix}`;
await secondPage.getByLabel("Название потребности").fill(secondWindowDraft);
const conflictResponsePromise = secondPage.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 412),
);
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
expect((await conflictResponsePromise).status()).toBe(412);
await expect(secondPage.getByRole("heading", { name: "Версия изменилась" })).toBeVisible();
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
const latestResponsePromise = secondPage.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await secondPage.getByRole("button", { name: "Загрузить и применить мой черновик" }).click();
await latestResponsePromise;
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
await expect(
secondPage.getByRole("heading", { name: "Проверьте объединенный черновик" }),
).toBeVisible();
await secondPage.getByRole("button", { name: "Продолжить сохранение" }).click();
const rebasedSavePromise = secondPage.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
const rebasedSaveResponse = await rebasedSavePromise;
const rebased = (await rebasedSaveResponse.json()) as NeedResponse;
expect(rebased.title).toBe(secondWindowDraft);
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
await page.setViewportSize({ width: 360, height: 900 });
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow).toBe(false);
await page.screenshot({
path: `${artifactsDirectory}/need-editor-mobile.png`,
animations: "disabled",
});
await page.setViewportSize({ width: 1280, height: 900 });
await page.screenshot({
path: `${artifactsDirectory}/need-editor-desktop.png`,
animations: "disabled",
});
const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
try {
const successorPage = await successorContext.newPage();
const successor = await registerVerifiedEmployer(successorPage);
await successorPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await expect(
successorPage.getByText("Потребность недоступна", { exact: true }),
).toBeVisible();
await expect(successorPage.getByLabel("Название потребности")).toHaveCount(0);
const beforeTransferStatus = await successorPage.evaluate(
async ({ orgId, id }) => {
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
cache: "no-store",
});
return response.status;
},
{ orgId: organization.id, id: needId },
);
expect(beforeTransferStatus).toBe(404);
await revokeMembership(organization.id, owner.userId, successor.userId);
async function expectOwnerAccessRemoved(targetPage: Page): Promise<void> {
await test.step("Refresh directory after owner access is revoked", async () => {
const directoryResponsePromise = targetPage.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/organizations" &&
response.status() === 200,
{ timeout: 10_000 },
);
await targetPage.bringToFront();
await targetPage.evaluate(() => {
window.dispatchEvent(new Event("visibilitychange"));
});
await directoryResponsePromise;
await expect(
targetPage.getByText("Потребность недоступна", { exact: true }),
).toBeVisible();
await expect(targetPage.getByLabel("Название потребности")).toHaveCount(0);
await expect(targetPage.getByLabel("Описание работы")).toHaveCount(0);
await expect(targetPage.getByText(sourceText, { exact: true })).toHaveCount(0);
});
}
await expectOwnerAccessRemoved(page);
await expectOwnerAccessRemoved(secondPage);
const revokedStatus = await page.evaluate(
async ({ orgId, id }) => {
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
cache: "no-store",
});
return response.status;
},
{ orgId: organization.id, id: needId },
);
expect(revokedStatus).toBe(404);
const successorNeedResponse = successorPage.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await successorPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await successorNeedResponse;
await expect(successorPage.getByLabel("Название потребности")).toHaveValue(
secondWindowDraft,
);
} finally {
await successorContext.close();
}
} finally {
await secondContext.close();
}
});
test("creates a manual need without source text and keeps recommendations pending", async ({
page,
}) => {
await registerVerifiedEmployer(page);
const suffix = crypto.randomUUID().slice(0, 8);
const organization = await createOrganization(page, `Manual need ${suffix}`);
const collectionPath = needCollectionPath(organization.id);
await page.goto(`/employer/needs/new?organization_id=${encodeURIComponent(organization.id)}`);
await expect(page.getByLabel("Название потребности")).toBeVisible();
await page.getByLabel("Название потребности").fill(`Manual Go developer ${suffix}`);
await expect(page.getByLabel("Описание работы")).toHaveValue("");
await page.getByLabel("Специализация").selectOption("backend");
await page.getByLabel("Грейд").selectOption("junior");
const requiredSkills = page
.getByRole("heading", { name: "Обязательные навыки" })
.locator("xpath=..");
await requiredSkills.getByLabel("Добавить навык").fill("Go");
await requiredSkills.getByRole("button", { name: "Добавить", exact: true }).click();
const tasks = page.getByRole("heading", { name: "Задачи команды" }).locator("xpath=..");
await tasks.getByLabel("Добавить задачу").fill("Развивать сервис уведомлений");
await tasks.getByRole("button", { name: "Добавить", exact: true }).click();
await page.getByLabel("От, рублей в месяц").fill("100000");
await page.getByLabel("До, рублей в месяц").fill("130000");
await page.getByLabel("База суммы").selectOption("net");
const createResponsePromise = page.waitForResponse((response) =>
isResponse(response, "POST", collectionPath, 201),
);
await page.getByRole("button", { name: "Создать потребность" }).click();
const createResponse = await createResponsePromise;
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
expect(createBody).not.toHaveProperty("source_text");
expect(createBody).not.toHaveProperty("vacancy_id");
const created = (await createResponse.json()) as NeedResponse;
expect(created.source_text).toBeNull();
expect(created.requirements.specialization).toMatchObject({
status: "confirmed",
value: "backend",
source: { origin: "manual" },
});
expect(created.requirements.grade).toMatchObject({
status: "confirmed",
value: "junior",
source: { origin: "manual" },
});
expect(created.requirements.required_skills).toHaveLength(1);
expect(created.requirements.required_skills[0]).toMatchObject({
name: "Go",
status: "confirmed",
source: { origin: "manual" },
});
expect(created.requirements.tasks).toHaveLength(1);
expect(created.requirements.tasks[0]).toMatchObject({
text: "Развивать сервис уведомлений",
status: "confirmed",
source: { origin: "manual" },
});
expect(created.requirements.salary).toMatchObject({
status: "confirmed",
value: { tax_basis: "net" },
source: { origin: "manual" },
});
expect(created.recommendations).toMatchObject({ status: "pending", categories: [] });
expect(created.readiness.status).toBe("incomplete");
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const detailPath = needPath(organization.id, created.id);
const reloadResponsePromise = page.waitForResponse((response) =>
isResponse(response, "GET", detailPath, 200),
);
await page.reload();
const reloadResponse = await reloadResponsePromise;
const persisted = (await reloadResponse.json()) as NeedResponse;
expect(persisted.source_text).toBeNull();
expect(persisted.requirements.grade.source?.origin).toBe("manual");
expect(persisted.requirements.required_skills[0]?.source?.origin).toBe("manual");
expect(persisted.requirements.salary.source?.origin).toBe("manual");
expect(persisted.recommendations).toMatchObject({ status: "pending", categories: [] });
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
});
});
+445
View File
@@ -0,0 +1,445 @@
import { expect, test, type Locator, type Page } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type SupportCaseResponse = {
id: string;
number: string;
type: string;
status: string;
description: string;
assessment_target: { specialization: string; grade: string } | null;
rubric_version: number | null;
response_target: { business_days: number; kind: string; due_at: string };
decision: unknown;
};
type SupportCaseListResponse = {
items: Pick<SupportCaseResponse, "id" | "number" | "type">[];
};
type ConsentList = {
items: { purpose: string; state: string }[];
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
const testPassword = "correct horse battery staple 2026";
test.use({ trace: "off", screenshot: "off", video: "off" });
function baseURL(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local end-to-end base URL is not configured.");
return value;
}
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured.");
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
function tokenFromMessage(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function registerCandidate(page: Page, prefix: string): Promise<string> {
const email = `${prefix}-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(testPassword);
await page.getByRole("radio", { name: /Кандидат/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseURL());
verificationUrl.hash = `token=${tokenFromMessage(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
expect(await page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(testPassword);
const confirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
expect((await confirmation).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/login");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(testPassword);
const login = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.request().method() === "POST",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await login).status()).toBe(201);
return email;
}
async function replaySupportCaseCreate(
page: Page,
originalResponse: Awaited<ReturnType<Page["waitForResponse"]>>,
): Promise<SupportCaseResponse> {
const originalRequest = originalResponse.request();
const body = originalRequest.postData();
const idempotencyKey = originalRequest.headers()["idempotency-key"];
expect(body).toBeTruthy();
expect(idempotencyKey).toBeTruthy();
const replay = await page.evaluate(
async ({ body, idempotencyKey }) => {
const sessionResponse = await fetch("/api/v1/identity/sessions/current", {
credentials: "include",
});
if (!sessionResponse.ok) throw new Error("Could not read the current local session.");
const session = (await sessionResponse.json()) as { csrf_token?: string };
if (!session.csrf_token) throw new Error("The current local session has no CSRF token.");
const response = await fetch("/api/v1/me/support-cases", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
"X-CSRF-Token": session.csrf_token,
},
body,
});
return {
status: response.status,
body: (await response.json()) as SupportCaseResponse,
};
},
{ body: body ?? "", idempotencyKey: idempotencyKey ?? "" },
);
expect(replay.status).toBe(201);
return replay.body;
}
async function focusByKeyboard(page: Page, target: Locator): Promise<void> {
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 80; attempt += 1) {
await page.keyboard.press("Tab");
if (await target.evaluate((element) => element === document.activeElement)) {
const hasVisibleFocus = await target.evaluate((element) => {
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
const style = getComputedStyle(element);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus).toBe(true);
return;
}
}
throw new Error("Keyboard navigation did not reach the requested control.");
}
async function checkResponsiveForm(
page: Page,
target: Locator,
widths = [360, 768, 1280],
): Promise<void> {
for (const width of widths) {
await page.setViewportSize({ width, height: 900 });
await focusByKeyboard(page, target);
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
}
}
test.describe("candidate support cases and manual assessment", () => {
test.skip(
!mailFixtureEnabled || !questionnaireFixtureEnabled,
"Requires the isolated local mail and published-bank fixtures.",
);
test("creates and reloads a support case from an unavailable assessment and hides it from another account", async ({
page,
}) => {
await registerCandidate(page, "support-author");
await page.goto("/candidate/assessment");
await expect(page.getByRole("link", { name: "Поддержка", exact: true })).toBeVisible();
await page.getByRole("link", { name: "Поддержка", exact: true }).click();
await expect(page).toHaveURL(/\/candidate\/support\/cases$/);
await page.getByRole("link", { name: "Написать в поддержку" }).click();
await expect(page).toHaveURL(/\/candidate\/support\/cases\/new$/);
const description = "Не удается открыть оценку для выбранной категории.";
const textarea = page.getByLabel("Что произошло или какая помощь нужна");
await textarea.fill(description);
await checkResponsiveForm(page, textarea);
await page.setViewportSize({ width: 360, height: 900 });
const submitButton = page.getByRole("button", { name: "Отправить обращение" });
await focusByKeyboard(page, submitButton);
const createResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
response.request().method() === "POST",
);
await page.keyboard.press("Enter");
const createResponse = await createResponsePromise;
expect(createResponse.status()).toBe(201);
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
expect(createBody).toMatchObject({ type: "support", description });
expect("assessment_target" in createBody).toBe(false);
const created = (await createResponse.json()) as SupportCaseResponse;
expect(created.type).toBe("support");
expect(created.description).toBe(description);
expect(created.response_target.kind).toBe("operational_goal");
const casePath = `/candidate/support/cases/${created.id}`;
await expect(page).toHaveURL(new RegExp(`${created.id}$`));
await expect(page.getByText(description, { exact: true })).toBeVisible();
await expect(page.getByText("Операционная цель", { exact: true })).toBeVisible();
await expect(page.getByText(/рабочих дней/)).toBeVisible();
const detailResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
response.request().method() === "GET",
);
await page.reload();
expect((await detailResponsePromise).status()).toBe(200);
await expect(page.getByText(description, { exact: true })).toBeVisible();
const replayed = await replaySupportCaseCreate(page, createResponse);
expect(replayed.id).toBe(created.id);
const supportList = await page.evaluate(async () => {
const response = await fetch("/api/v1/me/support-cases?limit=100", {
credentials: "include",
});
if (!response.ok) throw new Error("Could not read the local support case list.");
return (await response.json()) as SupportCaseListResponse;
});
expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1);
await page.getByRole("link", { name: "Мои обращения" }).click();
await expect(page.getByRole("link", { name: created.number })).toBeVisible();
const logoutStatus = await page.evaluate(async () => {
const current = await fetch("/api/v1/identity/sessions/current", {
credentials: "include",
});
if (!current.ok) return current.status;
const session = (await current.json()) as { csrf_token?: string };
if (!session.csrf_token) return 0;
const response = await fetch("/api/v1/identity/sessions/current", {
method: "DELETE",
credentials: "include",
headers: { "X-CSRF-Token": session.csrf_token },
});
return response.status;
});
expect(logoutStatus).toBe(204);
await registerCandidate(page, "support-reader");
await page.goto(casePath);
const foreignDetail = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
response.request().method() === "GET",
);
await page.reload();
expect((await foreignDetail).status()).toBe(404);
await expect(page.getByText("Обращение не найдено или недоступно")).toBeVisible();
await expect(page.getByText(description, { exact: true })).toHaveCount(0);
});
test("allows a manual request after C3 revocation without an attempt or an automatic grant", async ({
page,
}) => {
await registerCandidate(page, "manual-author");
await page.goto("/candidate/privacy");
await expect(
page.getByRole("heading", { name: "Согласия и настройки приватности" }),
).toBeVisible();
const c3Text = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consent-texts/c3" &&
response.request().method() === "GET",
);
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
expect((await c3Text).status()).toBe(200);
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
const grantList = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents" &&
response.request().method() === "GET",
);
const grantResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents/c3" &&
response.request().method() === "PUT",
);
await page.getByRole("button", { name: "Дать согласие C3" }).click();
expect((await grantResponse).status()).toBe(200);
const activeC3List = (await (await grantList).json()) as ConsentList;
expect(
activeC3List.items.some((record) => record.purpose === "c3" && record.state === "active"),
).toBe(true);
await page.getByRole("button", { name: "Отозвать C3", exact: true }).click();
await page.getByLabel("Я понимаю последствия отзыва C3.").check();
const revokeList = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents" &&
response.request().method() === "GET",
);
const revokeResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents/c3" &&
response.request().method() === "DELETE",
);
await page.getByRole("button", { name: "Подтвердить отзыв" }).click();
expect((await revokeResponse).status()).toBe(204);
const revokedC3List = (await (await revokeList).json()) as ConsentList;
expect(
revokedC3List.items.some((record) => record.purpose === "c3" && record.state === "active"),
).toBe(false);
const attemptRequests: string[] = [];
page.on("request", (request) => {
const url = new URL(request.url());
if (url.pathname === "/api/v1/me/assessment-attempts") attemptRequests.push(request.method());
});
await page.goto("/candidate/support/cases/manual-assessment");
const specialization = page.getByLabel("Специальность");
await expect(specialization.locator("option[value='frontend']")).toHaveCount(1);
await specialization.selectOption("frontend");
await expect(page.getByText(/Запрос ручной оценки остается доступен/)).toBeVisible();
await page.getByLabel("Желаемый грейд").selectOption("junior");
const reason = "Прошу эксперта оценить эту категорию вручную.";
const description = page.getByLabel("Почему вы просите ручную оценку");
await description.fill(reason);
await expect(page.getByText(/не требует C3/)).toBeVisible();
await checkResponsiveForm(page, specialization);
await page.setViewportSize({ width: 360, height: 900 });
const submitButton = page.getByRole("button", { name: "Отправить запрос эксперту" });
await focusByKeyboard(page, submitButton);
const createResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
response.request().method() === "POST",
);
await page.keyboard.press("Enter");
const createResponse = await createResponsePromise;
expect(createResponse.status()).toBe(201);
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
expect(createBody).toMatchObject({
type: "manual_assessment",
description: reason,
assessment_target: { specialization: "frontend", grade: "junior" },
});
expect("object" in createBody).toBe(false);
const created = (await createResponse.json()) as SupportCaseResponse;
expect(created.type).toBe("manual_assessment");
expect(created.status).toBe("waiting_expert");
expect(created.assessment_target).toEqual({ specialization: "frontend", grade: "junior" });
expect(created.rubric_version).toBeNull();
expect(created.decision).toBeNull();
expect(attemptRequests).toEqual([]);
await expect(
page.getByText(
"Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась.",
),
).toBeVisible();
const detailResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
response.request().method() === "GET",
);
await page.reload();
expect((await detailResponsePromise).status()).toBe(200);
await expect(page.getByText(reason, { exact: true })).toBeVisible();
const replayed = await replaySupportCaseCreate(page, createResponse);
expect(replayed.id).toBe(created.id);
const supportList = await page.evaluate(async () => {
const response = await fetch("/api/v1/me/support-cases?limit=100", {
credentials: "include",
});
if (!response.ok) throw new Error("Could not read the local support case list.");
return (await response.json()) as SupportCaseListResponse;
});
expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1);
const activeC3AfterRequest = await page.evaluate(async () => {
const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" });
if (!response.ok) return null;
const body = (await response.json()) as ConsentList;
return body.items.some((record) => record.purpose === "c3" && record.state === "active");
});
expect(activeC3AfterRequest).toBe(false);
await page.goto("/candidate/support/cases/manual-assessment");
await page.getByLabel("Специальность").selectOption("backend");
await page.getByLabel("Желаемый грейд").selectOption("junior");
const backendReason = "Прошу эксперта оценить Backend на уровне Junior.";
await page.getByLabel("Почему вы просите ручную оценку").fill(backendReason);
const backendCreatePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
response.request().method() === "POST",
);
await page.getByRole("button", { name: "Отправить запрос эксперту" }).click();
const backendCreateResponse = await backendCreatePromise;
expect(backendCreateResponse.status()).toBe(201);
expect(backendCreateResponse.request().postDataJSON()).toMatchObject({
type: "manual_assessment",
description: backendReason,
assessment_target: { specialization: "backend", grade: "junior" },
});
const backendCase = (await backendCreateResponse.json()) as SupportCaseResponse;
expect(backendCase.type).toBe("manual_assessment");
expect(backendCase.status).toBe("waiting_expert");
expect(backendCase.assessment_target).toEqual({ specialization: "backend", grade: "junior" });
expect(backendCase.rubric_version).toEqual(expect.any(Number));
expect(backendCase.rubric_version).toBeGreaterThan(0);
expect(backendCase.decision).toBeNull();
expect(attemptRequests).toEqual([]);
const activeC3AfterPublishedManualRequest = await page.evaluate(async () => {
const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" });
if (!response.ok) return null;
const body = (await response.json()) as ConsentList;
return body.items.some((record) => record.purpose === "c3" && record.state === "active");
});
expect(activeC3AfterPublishedManualRequest).toBe(false);
});
});