import { expect, test, type Browser, type BrowserContext, type Locator, type Page, } from "@playwright/test"; // The candidate side of an invitation with the real backend. Five synthetic // candidates publish the same card, the owner of a new organization finds // them with one search, and three of them receive an invitation through the // organization API. Each candidate keeps a signed-in browser context, so the // spec reads the outcome through the candidate and organization APIs as well // as the screen. The steps run in order and each one leaves the next one a // known state: // // 1. At 360px a candidate accepts with the email only: the grant covers the // email, the phone is not disclosed to the organization. // 2. A stale terms answer (412, the stand has no way to raise a sent // invitation, so the response is intercepted) leaves the new terms in view // with the consent unchosen; nothing is granted on the backend. // 3. Another candidate declines with the neutral reason and no comment; a // reload keeps the decline, and no contact is readable by the organization. const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; const password = "correct horse battery staple 2026"; // The declared grade is unique to this spec, so the search returns only the // candidates it publishes and never those of another spec. const declaredSpecialization = "information_security"; const declaredGrade = "junior"; test.use({ trace: "off", screenshot: "off", video: "off" }); type ApiResult = { status: number; body: unknown }; type InboxPage = { items: { id: string; state: string; organization: { id: string } }[] }; type Invitation = { id: string; state: string; version: number; terms_version: number; response_deadline_at: string; decline: { reason: string; comment: string | null } | null; contact_grant: { fields: string[]; status: string } | null; }; type Candidate = { context: BrowserContext; page: Page; email: string; phone: string }; 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<{ text?: string; html?: string }[]> { 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: { text?: string; html?: string }[] }).messages; } async function verificationToken(email: string): Promise { 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", email: string, ): Promise { 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 { return page.evaluate( async ({ method, path, body }) => { const headers: Record = {}; 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 }, ); } // A candidate with a declared information security junior, an active C2, a // published card, and two contact channels: the offer then lists four kinds // that the profile holds (full name, email, phone, and the first two). async function publishCandidate(browser: Browser): Promise { const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); const page = await context.newPage(); const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); const email = `invitee-${suffix}@example.test`; const phone = `+7900${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`; await createAccount(page, "candidate", email); const profile = await api(page, "PUT", "/api/v1/me/profile", { expected_version: 0, full_name: { value: "Приглашаемый кандидат", status: "confirmed" }, contacts: { email: { value: email, status: "confirmed" }, phone: { value: phone, status: "confirmed" }, telegram: null, }, stack: [], roles: [ { specialization: declaredSpecialization, self_assessed_grade: declaredGrade, 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, email, phone }; } // The terms of the invitation: remote only, so the place of work is null. const terms = { role_title: "Аналитик SOC, стажировка", specialization: declaredSpecialization, grade: "junior", offer_type: "internship", tasks: ["Разбирать события SIEM", "Готовить отчеты об инцидентах"], team: "Дежурная смена SOC: четыре аналитика и руководитель.", tech_stack: ["Splunk", "Suricata"], work_formats: ["remote"], location: null, communication_method: { channel: "video_call", details: null }, salary: { salary_from: 100000, salary_to: 140000, currency: "RUB", period: "month", tax_basis: "net", }, package: { bonus: { status: "not_provided" }, equipment: { status: "provided", description: "Ноутбук и второй монитор" }, training: { status: "not_provided" }, health_insurance: { status: "not_provided" }, }, }; async function expectNoHorizontalOverflow(page: Page, width: number): Promise { 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); } // Opens the answer form on the candidate home and waits for its one-time view. async function openHomeInvitation( candidatePage: Page, invitationId: string, organizationName: string, ): Promise { await candidatePage.goto("/candidate"); const card = candidatePage.locator("article").filter({ hasText: organizationName }); await expect(card).toBeVisible(); const viewed = candidatePage.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/invitations/${invitationId}/view` && response.status() === 200, ); await card.getByRole("button", { name: "Ответить на приглашение" }).click(); expect((await viewed).status()).toBe(200); await expect(card.getByRole("heading", { name: "Принять приглашение" })).toBeVisible(); await expect(candidatePage).toHaveURL(/\/candidate\/?$/); return card; } test.describe("candidate invitations with the real backend", () => { test.skip(!mailFixtureEnabled, "Requires the isolated mail fixture."); test("accepts with the email only, keeps a stale answer unchanged, and declines without a comment", async ({ browser, page, }) => { test.setTimeout(600_000); const candidates: Candidate[] = []; try { for (let index = 0; index < 5; index += 1) candidates.push(await publishCandidate(browser)); const ownerSuffix = crypto.randomUUID().slice(0, 8); await createAccount(page, "employer", `inviter-${ownerSuffix}@example.test`); const organizationName = `Компания ${ownerSuffix}`; const organization = await api(page, "POST", "/api/v1/organizations", { name: organizationName, }); expect(organization.status).toBe(201); const organizationId = (organization.body as { id: string }).id; // One search returns the five cards; three handles receive an invitation. const search = await api(page, "POST", `/api/v1/organizations/${organizationId}/matches`, { filters: { specialization: declaredSpecialization, declared_grade: declaredGrade }, }); expect(search.status).toBe(200); const handles = ( search.body as { groups: { unconfirmed: { candidate_handle: string }[] } } ).groups.unconfirmed.map((entry) => entry.candidate_handle); expect(handles.length).toBeGreaterThanOrEqual(3); for (const handle of handles.slice(0, 3)) { const draft = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations`, { candidate_handle: handle, response_period_days: 7, terms, }, ); expect(draft.status).toBe(201); const draftId = (draft.body as { id: string; version: number }).id; const version = (draft.body as { version: number }).version; const sent = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations/${draftId}/send`, { expected_version: version }, ); expect(sent.status).toBe(200); } // Which candidates received them: read each inbox, one request at a time. const received: { candidate: Candidate; invitationId: string }[] = []; for (const candidate of candidates) { const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); expect(inbox.status).toBe(200); for (const item of (inbox.body as InboxPage).items) { if (item.organization.id === organizationId) { received.push({ candidate, invitationId: item.id }); } } } expect(received).toHaveLength(3); const [accepting, stale, declining] = received; if (!accepting || !stale || !declining) throw new Error("Three invitations are needed."); await test.step("accepts with the email only at 360px, and the organization reads the email only", async () => { const candidatePage = accepting.candidate.page; await candidatePage.setViewportSize({ width: 360, height: 900 }); const card = await openHomeInvitation( candidatePage, accepting.invitationId, organizationName, ); await expectNoHorizontalOverflow(candidatePage, 360); // Nothing is preselected: every kind and the confirmation start unchecked. for (const label of ["ФИО", "Электронная почта", "Телефон"]) { await expect( candidatePage.getByRole("checkbox", { name: label, exact: true }), ).not.toBeChecked(); } await expect(candidatePage.getByRole("checkbox", { name: "Telegram" })).toHaveCount(0); const submit = card.getByRole("button", { name: "Принять и передать контакты" }); await expect(submit).toHaveAttribute("aria-disabled", "true"); await candidatePage .getByRole("checkbox", { name: "Электронная почта", exact: true }) .check(); await candidatePage .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) .check(); await expect(submit).not.toHaveAttribute("aria-disabled", "true"); await expectNoHorizontalOverflow(candidatePage, 360); const accepted = candidatePage.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/invitations/${accepting.invitationId}/accept`, ); await submit.click(); expect((await accepted).status()).toBe(200); const confirmation = candidatePage .getByRole("status") .filter({ hasText: "Приглашение принято" }); await expect(confirmation).toBeVisible(); await expect(confirmation.getByRole("listitem")).toHaveText(["Электронная почта"]); await expectNoHorizontalOverflow(candidatePage, 360); // The candidate's read: exactly one granted kind. const mine = await api( candidatePage, "GET", `/api/v1/me/invitations/${accepting.invitationId}`, ); expect(mine.status).toBe(200); expect(mine.body).toMatchObject({ state: "accepted", contact_grant: { fields: ["email"], status: "active" }, }); // The organization's read: the email, and no phone or name. const disclosed = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${accepting.invitationId}/contacts`, ); expect(disclosed.status).toBe(200); expect(disclosed.body).toMatchObject({ email: accepting.candidate.email, phone: null }); expect((disclosed.body as { full_name: unknown }).full_name).toBeNull(); }); await test.step("keeps a stale terms answer unchanged and asks for a new confirmation", async () => { const staleId = stale.invitationId; const candidatePage = stale.candidate.page; await candidatePage.setViewportSize({ width: 360, height: 900 }); const card = await openHomeInvitation(candidatePage, staleId, organizationName); await candidatePage.getByRole("checkbox", { name: "Телефон", exact: true }).check(); await candidatePage .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) .check(); // The company changed the terms after the candidate read them. A sent // invitation cannot be changed on this stand, so the first acceptance is // answered 412 by the route, and the re-read returns the raised bound. let staleAnswers = 0; const acceptBodies: unknown[] = []; const acceptPath = new RegExp(`/api/v1/me/invitations/${staleId}/accept$`); const detailPath = new RegExp(`/api/v1/me/invitations/${staleId}$`); await candidatePage.route(acceptPath, async (route) => { acceptBodies.push(route.request().postDataJSON()); staleAnswers += 1; await route.fulfill({ status: 412, contentType: "application/problem+json", body: JSON.stringify({ type: "urn:lincodex:problem:version_conflict", title: "Version conflict", status: 412, code: "version_conflict", }), }); }); await candidatePage.route(detailPath, async (route) => { if (route.request().method() !== "GET" || staleAnswers === 0) { await route.continue(); return; } const real = await route.fetch(); const body = (await real.json()) as { version: number; terms_version: number; terms: { salary: { salary_to: number } }; }; await route.fulfill({ response: real, json: { ...body, version: body.version + 1, terms_version: body.terms_version + 1, terms: { ...body.terms, salary: { ...body.terms.salary, salary_to: 150000 } }, }, }); }); await card.getByRole("button", { name: "Принять и передать контакты" }).click(); await expect( candidatePage.getByRole("status").filter({ hasText: "Приглашение изменилось" }), ).toBeVisible(); await expect(candidatePage.locator('[data-term="salary"]')).toHaveText( /от 100\s000 ₽ до 150\s000 ₽/, ); // The new version starts with nothing chosen, so a new confirmation is needed. await expect( candidatePage.getByRole("checkbox", { name: "Телефон", exact: true }), ).not.toBeChecked(); await expect( candidatePage.getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }), ).not.toBeChecked(); await expect( candidatePage.getByRole("button", { name: "Принять и передать контакты" }), ).toHaveAttribute("aria-disabled", "true"); expect(staleAnswers).toBe(1); expect(acceptBodies).toEqual([ { expected_version: expect.any(Number), terms_version: 1, consent_c4: expect.objectContaining({ accepted: true, fields: ["phone"] }), }, ]); await expectNoHorizontalOverflow(candidatePage, 360); // The backend itself recorded no acceptance and no grant. await candidatePage.unroute(acceptPath); await candidatePage.unroute(detailPath); const current = await api(candidatePage, "GET", `/api/v1/me/invitations/${staleId}`); expect(current.status).toBe(200); expect(current.body).toMatchObject({ contact_grant: null }); expect(["delivered", "viewed"]).toContain((current.body as Invitation).state); }); await test.step("declines without a comment, keeps the decline after a reload, and discloses nothing", async () => { const candidatePage = declining.candidate.page; await candidatePage.setViewportSize({ width: 360, height: 900 }); const card = await openHomeInvitation( candidatePage, declining.invitationId, organizationName, ); await candidatePage.getByRole("radio", { name: "Другая причина", exact: true }).check(); // No comment is written: the neutral reason never asks for one. const declined = candidatePage.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/v1/me/invitations/${declining.invitationId}/decline` && response.status() === 200, ); await card.getByRole("button", { name: "Отклонить приглашение" }).click(); expect((await declined).status()).toBe(200); await expect( candidatePage.getByRole("status").filter({ hasText: "Приглашение отклонено" }), ).toBeVisible(); await expect(candidatePage).toHaveURL(/\/candidate\/?$/); await expectNoHorizontalOverflow(candidatePage, 360); const declinedInvitation = await api( candidatePage, "GET", `/api/v1/me/invitations/${declining.invitationId}`, ); expect(declinedInvitation.body).toMatchObject({ state: "declined", decline: { reason: "other", comment: null }, contact_grant: null, }); const mine = await api( candidatePage, "GET", `/api/v1/me/invitations/${declining.invitationId}`, ); expect(mine.body).toMatchObject({ state: "declined", contact_grant: null, decline: { reason: "other", comment: null }, }); // The organization reads no contact: the endpoint answers not found. const disclosed = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${declining.invitationId}/contacts`, ); expect(disclosed.status).toBe(404); }); } finally { await Promise.all(candidates.map((candidate) => candidate.context.close())); } }); });