414 lines
20 KiB
TypeScript
414 lines
20 KiB
TypeScript
import {
|
|
expect,
|
|
test,
|
|
type Browser,
|
|
type BrowserContext,
|
|
type Page,
|
|
type Request,
|
|
} from "@playwright/test";
|
|
|
|
// The organization owner invites a candidate from a real search result
|
|
// against the real backend. Five synthetic candidates publish the same card
|
|
// (the card projection needs a group of five), all with a declared
|
|
// information security intern grade that no other spec uses, so the search
|
|
// result holds only them. Each candidate keeps a signed-in browser context,
|
|
// so the spec reads every inbox through the candidate API and proves that
|
|
// the preview and a rejected form send nothing, and that a repeated click on
|
|
// a slow send and a retry after a lost response deliver exactly one
|
|
// invitation under one Idempotency-Key.
|
|
|
|
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
|
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
|
|
const password = "correct horse battery staple 2026";
|
|
|
|
test.use({ trace: "off", screenshot: "off", video: "off" });
|
|
|
|
type ApiResult = { status: number; body: unknown };
|
|
type InboxMessage = { text?: string; html?: string };
|
|
type InboxPage = { items: { state: string; response_deadline_at: string; role_title: string }[] };
|
|
type SentInvitation = { id: string; state: string; response_deadline_at: string | null };
|
|
|
|
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 readMailbox(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 { messages: InboxMessage[] }).messages;
|
|
}
|
|
|
|
async function verificationToken(email: string): Promise<string> {
|
|
const deadline = Date.now() + 20_000;
|
|
while (Date.now() < deadline) {
|
|
const message = (await readMailbox(email)).at(-1);
|
|
if (message) {
|
|
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 registration message had no verification link.");
|
|
return token;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
}
|
|
throw new Error("The local mailbox did not receive the verification message.");
|
|
}
|
|
|
|
// Registers, confirms, and signs in a synthetic account.
|
|
async function createAccount(page: Page, scenario: "candidate" | "employer"): Promise<void> {
|
|
const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8);
|
|
const email =
|
|
scenario === "employer" ? `inviter-${suffix}@example.test` : `invitee-${suffix}@example.test`;
|
|
await page.goto("/register");
|
|
await page.getByLabel("Электронная почта").fill(email);
|
|
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
|
await page
|
|
.getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ })
|
|
.check();
|
|
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
|
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
|
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
|
|
|
const verificationUrl = new URL("/verify-email", baseUrl());
|
|
verificationUrl.hash = `token=${await verificationToken(email)}`;
|
|
await page.goto(verificationUrl.toString());
|
|
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
|
|
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
|
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
|
|
|
await page.goto(scenario === "employer" ? "/employer/company" : "/candidate");
|
|
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" &&
|
|
response.status() === 201,
|
|
);
|
|
await page.getByRole("button", { name: "Войти" }).click();
|
|
await loginResponse;
|
|
}
|
|
|
|
// Calls the API from the page, so the cookie and the origin are the browser's.
|
|
async function api(page: Page, method: string, path: string, body?: unknown): Promise<ApiResult> {
|
|
return page.evaluate(
|
|
async ({ method, path, body }) => {
|
|
const headers: Record<string, string> = {};
|
|
if (method !== "GET") {
|
|
const session = await fetch("/api/v1/identity/sessions/current", {
|
|
credentials: "include",
|
|
});
|
|
headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token;
|
|
headers["Idempotency-Key"] = crypto.randomUUID();
|
|
}
|
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
const response = await fetch(path, {
|
|
method,
|
|
headers,
|
|
credentials: "include",
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
});
|
|
return { status: response.status, body: await response.json().catch(() => null) };
|
|
},
|
|
{ method, path, body },
|
|
);
|
|
}
|
|
|
|
type Candidate = { context: BrowserContext; page: Page };
|
|
|
|
// A candidate with one declared specialization, no test, an active C2, and a
|
|
// published card that holds only the self-assessment.
|
|
async function publishCandidate(browser: Browser): Promise<Candidate> {
|
|
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
|
const page = await context.newPage();
|
|
await createAccount(page, "candidate");
|
|
const profile = await api(page, "PUT", "/api/v1/me/profile", {
|
|
expected_version: 0,
|
|
full_name: { value: "Приглашаемый кандидат", status: "confirmed" },
|
|
contacts: { email: null, phone: null, telegram: null },
|
|
stack: [],
|
|
roles: [
|
|
{
|
|
specialization: "information_security",
|
|
self_assessed_grade: "intern",
|
|
status: "confirmed",
|
|
},
|
|
],
|
|
experience: [],
|
|
soft_skills: [],
|
|
terms: { location: null, relocation: null, salary_minimum: null },
|
|
});
|
|
expect(profile.status).toBe(200);
|
|
const text = await api(page, "GET", "/api/v1/me/consent-texts/c2");
|
|
expect(text.status).toBe(200);
|
|
const granted = await api(page, "PUT", "/api/v1/me/consents/c2", {
|
|
text_version: (text.body as { text_version: string }).text_version,
|
|
accepted: true,
|
|
});
|
|
expect(granted.status).toBe(200);
|
|
const published = await api(page, "PUT", "/api/v1/me/privacy/publication", {
|
|
expected_version: 0,
|
|
state: "published",
|
|
fields: ["self_assessment"],
|
|
});
|
|
expect(published.status).toBe(200);
|
|
return { context, page };
|
|
}
|
|
|
|
/**
|
|
* Every invitation in the inboxes of the given candidates. The reads run one
|
|
* after another: the stand shares one client address for all browser tests,
|
|
* and a burst would spend its request rate.
|
|
*/
|
|
async function inboxItems(candidates: readonly Candidate[]): Promise<InboxPage["items"]> {
|
|
const items: InboxPage["items"] = [];
|
|
for (const candidate of candidates) {
|
|
const result = await api(candidate.page, "GET", "/api/v1/me/invitations");
|
|
expect(result.status).toBe(200);
|
|
items.push(...(result.body as InboxPage).items);
|
|
}
|
|
return items;
|
|
}
|
|
|
|
function isInvitationCommand(request: Request): boolean {
|
|
return (
|
|
request.method() !== "GET" &&
|
|
/\/api\/v1\/organizations\/[0-9a-f-]+\/invitations/.test(new URL(request.url()).pathname)
|
|
);
|
|
}
|
|
|
|
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
|
for (const width of [360, 1280]) {
|
|
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);
|
|
}
|
|
}
|
|
|
|
test.describe("organization invitation with the real backend", () => {
|
|
test.skip(
|
|
!mailFixtureEnabled || !companyFixtureEnabled,
|
|
"Requires the isolated mail and company fixtures.",
|
|
);
|
|
|
|
test("previews all terms, binds errors to fields, and delivers one invitation", async ({
|
|
browser,
|
|
page,
|
|
}) => {
|
|
test.setTimeout(480_000);
|
|
const candidates: Candidate[] = [];
|
|
try {
|
|
for (let index = 0; index < 5; index += 1) candidates.push(await publishCandidate(browser));
|
|
|
|
await createAccount(page, "employer");
|
|
const organization = await api(page, "POST", "/api/v1/organizations", {
|
|
name: `Invite team ${crypto.randomUUID().slice(0, 8)}`,
|
|
});
|
|
expect(organization.status).toBe(201);
|
|
const organizationId = (organization.body as { id: string }).id;
|
|
const organizationName = (organization.body as { name: string }).name;
|
|
|
|
// The invitation starts from an entry of a real search result.
|
|
await page.goto(`/employer/candidates?organization_id=${organizationId}`);
|
|
await page.getByLabel("Специализация", { exact: true }).selectOption("information_security");
|
|
await page.getByLabel("Заявленный кандидатом грейд").selectOption("intern");
|
|
const search = page.waitForResponse(
|
|
(response) =>
|
|
response.request().method() === "POST" &&
|
|
new URL(response.url()).pathname.endsWith("/matches"),
|
|
);
|
|
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
|
const result = (await (await search).json()) as {
|
|
groups: { unconfirmed: { candidate_handle: string }[] };
|
|
};
|
|
expect(result.groups.unconfirmed).toHaveLength(5);
|
|
const invite = page.getByRole("link", { name: /^Пригласить кандидата/ }).first();
|
|
const handle = new URL((await invite.getAttribute("href")) ?? "", baseUrl()).searchParams.get(
|
|
"candidate_handle",
|
|
);
|
|
await invite.click();
|
|
await expect(page).toHaveURL(/\/employer\/invitations\/new\?/);
|
|
await expect(
|
|
page.getByRole("heading", { level: 1, name: "Приглашение кандидату" }),
|
|
).toBeVisible();
|
|
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue(
|
|
"information_security",
|
|
);
|
|
expect(handle).toMatch(/^cv1_/);
|
|
|
|
const commands: Request[] = [];
|
|
page.on("request", (request) => {
|
|
if (isInvitationCommand(request)) commands.push(request);
|
|
});
|
|
|
|
// Step 1: the terms with [100000; 140000] net and a package.
|
|
await page.getByLabel("Название роли", { exact: true }).fill("Аналитик SOC, стажировка");
|
|
await page.getByLabel("Грейд", { exact: true }).selectOption("intern");
|
|
await page.getByLabel("Тип предложения", { exact: true }).selectOption("internship");
|
|
await page
|
|
.getByLabel("Задачи", { exact: true })
|
|
.fill("Разбирать события SIEM\nГотовить отчеты об инцидентах");
|
|
await page
|
|
.getByLabel("Команда", { exact: true })
|
|
.fill("Дежурная смена SOC: четыре аналитика и руководитель.");
|
|
await page.getByLabel("Технологии", { exact: true }).fill("Splunk, Suricata");
|
|
await page.getByRole("checkbox", { name: "Удаленно" }).check();
|
|
await page.getByRole("checkbox", { name: "Гибридно" }).check();
|
|
await page.getByLabel("Место работы", { exact: true }).fill("Казань");
|
|
await page.getByLabel("Канал связи", { exact: true }).selectOption("video_call");
|
|
await page
|
|
.getByLabel("Комментарий (необязательно)")
|
|
.fill("Созвон с руководителем смены в течение трех рабочих дней");
|
|
await page.getByLabel("От, ₽", { exact: true }).fill("100000");
|
|
await page.getByLabel("До, ₽", { exact: true }).fill("140000");
|
|
await page.getByLabel("База суммы", { exact: true }).selectOption("net");
|
|
const bonus = page.getByRole("group", { name: "Премии и бонусы" });
|
|
await bonus.getByRole("radio", { name: "Предусмотрено", exact: true }).check();
|
|
await page.getByLabel("Премии и бонусы: описание").fill("Квартальная премия до 10%");
|
|
const equipment = page.getByRole("group", { name: "Оборудование" });
|
|
await equipment.getByRole("radio", { name: "Предусмотрено", exact: true }).check();
|
|
await page.getByLabel("Оборудование: описание").fill("Ноутбук и второй монитор");
|
|
await page
|
|
.getByRole("group", { name: "Обучение" })
|
|
.getByRole("radio", { name: "Не предусмотрено", exact: true })
|
|
.check();
|
|
await page
|
|
.getByRole("group", { name: "ДМС" })
|
|
.getByRole("radio", { name: "Не предусмотрено", exact: true })
|
|
.check();
|
|
|
|
await page.getByRole("button", { name: "Показать предпросмотр" }).click();
|
|
const preview = page.getByRole("region", { name: "Предпросмотр приглашения" });
|
|
await expect(preview).toBeFocused();
|
|
await expect(preview.getByRole("heading", { name: organizationName })).toBeVisible();
|
|
const terms = preview.getByRole("article", { name: "Условия приглашения" });
|
|
for (const value of [
|
|
"Аналитик SOC, стажировка",
|
|
"Информационная безопасность, Стажер",
|
|
"Стажировка",
|
|
"Разбирать события SIEM",
|
|
"Готовить отчеты об инцидентах",
|
|
"Дежурная смена SOC: четыре аналитика и руководитель.",
|
|
"Splunk, Suricata",
|
|
"Удаленно, Гибридно",
|
|
"Казань",
|
|
"Видеозвонок. Созвон с руководителем смены в течение трех рабочих дней",
|
|
"Квартальная премия до 10%",
|
|
"Ноутбук и второй монитор",
|
|
"7 дней с момента доставки",
|
|
]) {
|
|
await expect(terms).toContainText(value);
|
|
}
|
|
await expect(terms.locator('[data-term="salary"]')).toHaveText(
|
|
/^от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)$/,
|
|
);
|
|
await expect(terms.locator('[data-package="training"] dd')).toHaveText("Не предусмотрено");
|
|
await expect(terms.locator('[data-package="health_insurance"] dd')).toHaveText(
|
|
"Не предусмотрено",
|
|
);
|
|
// The preview is local: no command, nothing in any inbox.
|
|
expect(commands).toEqual([]);
|
|
expect(await inboxItems(candidates)).toEqual([]);
|
|
|
|
// Step 2: without the communication method the form refuses to send.
|
|
const channel = page.getByLabel("Канал связи", { exact: true });
|
|
await channel.selectOption({ index: 0 });
|
|
await page.getByRole("button", { name: "Отправить приглашение" }).click();
|
|
const summary = page.getByRole("alert").filter({ hasText: "Проверьте условия приглашения" });
|
|
await expect(summary).toBeFocused();
|
|
await expect(channel).toHaveAttribute("aria-invalid", "true");
|
|
await expect(channel).toHaveAccessibleDescription(
|
|
"Выберите способ связи после принятия приглашения.",
|
|
);
|
|
await expect(page.getByText("Условия изменены после предпросмотра")).toBeVisible();
|
|
expect(commands).toEqual([]);
|
|
expect(await inboxItems(candidates)).toEqual([]);
|
|
|
|
// Step 3: a slow send whose first response is lost, clicked twice and
|
|
// then retried. The browser keeps the key until the command completes.
|
|
await channel.selectOption("video_call");
|
|
await expect(channel).toHaveAttribute("aria-invalid", "false");
|
|
let sendAttempts = 0;
|
|
let delivered: SentInvitation | null = null;
|
|
await page.route("**/api/v1/organizations/*/invitations/*/send", async (route) => {
|
|
sendAttempts += 1;
|
|
const response = await route.fetch();
|
|
await new Promise((resolve) => setTimeout(resolve, 1_500));
|
|
if (sendAttempts === 1) {
|
|
await route.abort("connectionreset");
|
|
return;
|
|
}
|
|
delivered = (await response.json()) as SentInvitation;
|
|
await route.fulfill({ response });
|
|
});
|
|
const sendButton = page.getByRole("button", { name: "Отправить приглашение" });
|
|
await sendButton.click();
|
|
await expect.poll(() => sendAttempts).toBe(1);
|
|
await expect(sendButton).toHaveAttribute("aria-busy", "true");
|
|
// The second click during the slow request starts nothing.
|
|
await sendButton.click({ force: true });
|
|
await expect(page.getByText("Сервер не подтвердил результат")).toBeVisible();
|
|
await expect(sendButton).not.toHaveAttribute("aria-busy", "true");
|
|
expect(sendAttempts).toBe(1);
|
|
|
|
await sendButton.click();
|
|
await expect.poll(() => sendAttempts).toBe(2);
|
|
await sendButton.click({ force: true });
|
|
const resultHeading = page.getByRole("heading", { level: 2, name: "Приглашение доставлено" });
|
|
await expect(resultHeading).toBeFocused({ timeout: 15_000 });
|
|
await page.unroute("**/api/v1/organizations/*/invitations/*/send");
|
|
|
|
const creates = commands.filter((request) =>
|
|
new URL(request.url()).pathname.endsWith("/invitations"),
|
|
);
|
|
const sends = commands.filter((request) => new URL(request.url()).pathname.endsWith("/send"));
|
|
expect(creates).toHaveLength(1);
|
|
expect(sends).toHaveLength(2);
|
|
const sendKeys = await Promise.all(
|
|
sends.map((request) => request.headerValue("idempotency-key")),
|
|
);
|
|
expect(sendKeys[0]).toBeTruthy();
|
|
expect(sendKeys[1]).toBe(sendKeys[0]);
|
|
expect(await creates[0]?.headerValue("idempotency-key")).not.toBe(sendKeys[0]);
|
|
|
|
const sent = delivered as SentInvitation | null;
|
|
if (!sent?.response_deadline_at) throw new Error("The send returned no deadline.");
|
|
expect(sent.state).toBe("delivered");
|
|
await expect(page.locator('[data-state="delivered"]')).toHaveText("Доставлено");
|
|
const deadline = page.locator('[data-term="deadline"] time');
|
|
await expect(deadline).toHaveAttribute("datetime", sent.response_deadline_at);
|
|
|
|
// One invitation in exactly one inbox, with the deadline the UI shows.
|
|
const inbox = await inboxItems(candidates);
|
|
expect(inbox).toHaveLength(1);
|
|
expect(inbox[0]).toMatchObject({
|
|
state: "delivered",
|
|
role_title: "Аналитик SOC, стажировка",
|
|
response_deadline_at: sent.response_deadline_at,
|
|
});
|
|
|
|
// The address keeps the invitation, so a reload shows the stored deadline.
|
|
await expect(page).toHaveURL(new RegExp(`invitation_id=${sent.id}`));
|
|
await page.reload();
|
|
await expect(page.locator('[data-state="delivered"]')).toHaveText("Доставлено");
|
|
await expect(page.locator('[data-term="deadline"] time')).toHaveAttribute(
|
|
"datetime",
|
|
sent.response_deadline_at,
|
|
);
|
|
await expectNoHorizontalOverflow(page);
|
|
expect(await inboxItems(candidates)).toHaveLength(1);
|
|
} finally {
|
|
await Promise.all(candidates.map((candidate) => candidate.context.close()));
|
|
}
|
|
});
|
|
});
|