Files
lincodex/frontend/e2e/support-cases.spec.ts
T

448 lines
20 KiB
TypeScript

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");
// Support sits in the account menu of the header.
await page.getByRole("button", { name: "Аккаунт" }).click();
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);
});
});