import { expect, test, type Browser, type BrowserContext, type Page } from "@playwright/test"; // The minimal path end to end on the real core, without an FSP ID: email // confirmation from the local mail fixture, profile, questionnaire, the full // Backend Junior test, the synthetic demonstration category, publication, // a need, the search and its explanation, an invitation, the acceptance with // C4, and the contact read by the company. The same run checks that reloads, // history navigation, and two concurrent acceptances add no second record, // that another company uses none of these objects, and that C2 revocation // closes the reads while a new publication does not reopen the grant. // // A card is shown only in a group of at least five identical cards, so five // candidates go through the same steps in the browser and each one solves the // full test. The isolated registration stand opens the reviewed fixture bank // (rate-limit items whose answer follows from the statement), enables // synthetic demonstration categories, and attests the opening; no other stand // assigns a category this way. const enabled = process.env.E2E_MAIL_FIXTURE === "1" && process.env.E2E_QUESTIONNAIRE_FIXTURE === "1" && process.env.E2E_DEMO_CATEGORIES === "1"; const password = "correct horse battery staple 2026"; // The same pause as the assessment spec: one client address shares the API // budget of the stand, and a person reads each item before answering. const answerPauseMs = 250; const publishedFields = ["categories", "self_assessment", "stack", "work_formats"]; test.use({ trace: "off", screenshot: "off", video: "off", actionTimeout: 15_000 }); type ApiResult = { status: number; body: unknown }; type InboxMessage = { text?: string; html?: string }; type Candidate = { context: BrowserContext; page: Page; email: string; phone: string; fullName: string; }; type MatchEntry = { candidate_handle: string; specialization: string; confirmation_status: string; declared_grade: string | null; category: { specialization: string; grade: string; basis: string } | null; components: Record; }; type MatchResult = { source: { kind: string; need_id?: string; requirements_version?: number }; groups: { main: MatchEntry[]; near: MatchEntry[]; unconfirmed: MatchEntry[] }; truncated: boolean; }; type CandidateInvitation = { id: string; state: string; version: number; terms_version: number; organization: { id: string }; contact_grant: { id: string; fields: string[]; status: string } | null; contact_consent: { text: { text_version: string }; available_fields: string[] } | null; }; type ConsentRecord = { id: string; purpose: string; state: string; organization?: { id: 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 { 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 { 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 through the form, confirms with the link from the received // message, and signs in. The message is never printed. 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); const confirmed = 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 confirmed).status()).toBe(200); 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 signedIn = page.waitForResponse( (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/identity/sessions", ); await page.getByRole("button", { name: "Войти" }).click(); expect((await signedIn).status()).toBe(201); } // 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 }, ); } // Sends the same command twice at once, each under its own Idempotency-Key, // from the page of the signed-in account. async function concurrently(page: Page, path: string, body: unknown): Promise { return page.evaluate( async ({ path, body }) => { const session = await fetch("/api/v1/identity/sessions/current", { credentials: "include" }); const csrf = ((await session.json()) as { csrf_token: string }).csrf_token; const send = () => fetch(path, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf, "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify(body), }).then(async (response) => ({ status: response.status, body: (await response.json().catch(() => null)) as unknown, })); return Promise.all([send(), send()]); }, { path, body }, ); } function apiResponse(method: string, path: string | RegExp) { return (response: { url(): string; request(): { method(): string } }) => { const pathname = new URL(response.url()).pathname; return ( response.request().method() === method && (typeof path === "string" ? pathname === path : path.test(pathname)) ); }; } // The answer of a rate-limit fixture item follows from its statement: count // the requests that find `limit` accepted ones in (t - window, t]. function rejectedRequests(statement: string): number { const limit = Number(/fewer than (\d+) previously accepted/.exec(statement)?.[1]); const window = Number(/\(t - (\d+), t\]/.exec(statement)?.[1]); const times = /arrival times: ([\d ]+)\./.exec(statement)?.[1]?.trim().split(/\s+/).map(Number); if (!Number.isInteger(limit) || !Number.isInteger(window) || !times?.length) { throw new Error("The item statement is not a rate-limit fixture item."); } const accepted: number[] = []; let rejected = 0; for (const moment of times) { const inWindow = accepted.filter((time) => time > moment - window).length; if (inWindow < limit) accepted.push(moment); else rejected += 1; } return rejected; } async function saveProfile(candidate: Candidate): Promise { const { page } = candidate; await page.goto("/candidate/profile"); await page.getByLabel("Имя и фамилия").fill(candidate.fullName); await page.getByLabel("Контактный email").fill(candidate.email); await page.getByLabel("Телефон").fill(candidate.phone); for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) { await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); } const saved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile")); await page.getByRole("button", { name: "Сохранить профиль" }).click(); expect((await saved).status()).toBe(200); } async function saveQuestionnaire(page: Page): Promise { await page.goto("/candidate/questionnaire"); await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); await page.getByLabel("Моя оценка уровня").selectOption("junior"); await page.getByRole("checkbox", { name: "Go", exact: true }).check(); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); const saved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/questionnaire")); await page.getByRole("button", { name: "Сохранить анкету" }).click(); expect((await saved).status()).toBe(200); } async function grantC3(page: Page): Promise { await page.goto("/candidate/privacy"); await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); const granted = page.waitForResponse(apiResponse("PUT", "/api/v1/me/consents/c3")); await page.getByRole("button", { name: "Дать согласие C3" }).click(); expect((await granted).status()).toBe(200); } // Takes the full Backend Junior test in the browser and answers every item // from its statement. With `reloadAfter` the page is reloaded after that many // answers: the same attempt and item come back and nothing is answered twice. async function passFullTest(page: Page, reloadAfter?: number): Promise { await page.goto("/candidate/assessment"); await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); // The questionnaire names Go only, so the page offers no language choice. const created = page.waitForResponse(apiResponse("POST", "/api/v1/me/assessment-attempts")); await page.getByRole("button", { name: "Начать полную проверку" }).click(); await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click(); const createdResponse = await created; expect(createdResponse.status()).toBe(201); expect(createdResponse.request().postDataJSON()).toMatchObject({ kind: "root", specialization: "backend", target_grade: "junior", task_language: "go", }); const attemptId = ((await createdResponse.json()) as { id: string }).id; const attemptPath = `/api/v1/me/assessment-attempts/${attemptId}`; const started = page.waitForResponse(apiResponse("POST", `${attemptPath}/sessions`)); await page.getByRole("button", { name: "Начать или продолжить" }).click(); const snapshot = (await (await started).json()) as { progress: { answered_items: number; max_items: number }; }; const total = snapshot.progress.max_items; expect(total).toBeGreaterThan(0); for (let sequence = 1; sequence <= total; sequence += 1) { await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible({ timeout: 20_000, }); const statement = await page .getByText(/^A gateway applies a sliding-window limiter/) .innerText(); await page .getByRole("textbox", { name: /^Числовой ответ/ }) .fill(String(rejectedRequests(statement))); const answered = page.waitForResponse(apiResponse("POST", `${attemptPath}/answers`)); await page.getByRole("button", { name: "Отправить ответ" }).click(); expect((await answered).status()).toBe(200); await page.waitForTimeout(answerPauseMs); if (sequence === reloadAfter) { const reread = page.waitForResponse(apiResponse("GET", attemptPath)); await page.reload(); const reloaded = (await (await reread).json()) as { id: string; progress: { answered_items: number }; }; expect(reloaded.id).toBe(attemptId); expect(reloaded.progress.answered_items).toBe(sequence); const resumed = page.waitForResponse(apiResponse("POST", `${attemptPath}/sessions`)); await page.getByRole("button", { name: "Начать или продолжить" }).click(); expect((await resumed).status()).toBe(200); } } const finalized = page.waitForResponse(apiResponse("POST", `${attemptPath}/finalize`)); await page.getByRole("button", { name: "Завершить проверку" }).click(); expect((await finalized).status()).toBe(200); await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); return attemptId; } async function publishCard(page: Page): Promise { 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 privacy = await api(page, "GET", "/api/v1/me/privacy"); expect(privacy.status).toBe(200); const published = await api(page, "PUT", "/api/v1/me/privacy/publication", { expected_version: (privacy.body as { publication: { version: number } }).publication.version, state: "published", fields: publishedFields, }); expect(published.status).toBe(200); } // A candidate who confirmed the email, filled the profile and the // questionnaire without an FSP ID, passed the full test, and published. async function preparedCandidate(browser: Browser, index: number): 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 candidate: Candidate = { context, page, email: `path-${index}-${suffix}@example.test`, phone: `+7901${String(1_000_000 + Math.floor(Math.random() * 8_999_999))}`, fullName: `Кандидат пути ${suffix}`, }; await createAccount(page, "candidate", candidate.email); await saveProfile(candidate); await saveQuestionnaire(page); await grantC3(page); await passFullTest(page); await publishCard(page); return candidate; } async function myInvitation(candidate: Candidate, id: string): Promise { const read = await api(candidate.page, "GET", `/api/v1/me/invitations/${id}`); expect(read.status).toBe(200); return read.body as CandidateInvitation; } async function c4Records(candidate: Candidate, organizationId: string): Promise { const list = await api(candidate.page, "GET", "/api/v1/me/consents"); expect(list.status).toBe(200); return (list.body as { items: ConsentRecord[] }).items.filter( (record) => record.purpose === "c4" && record.organization?.id === organizationId, ); } const terms = { role_title: "Backend-разработчик сервиса платежей", specialization: "backend", grade: "junior", offer_type: "full_time", tasks: ["Развивать сервис платежей на Go"], team: "Команда платежей: пять разработчиков и тимлид.", tech_stack: ["Go", "PostgreSQL"], work_formats: ["remote"], location: null, communication_method: { channel: "video_call", details: null }, salary: { salary_from: 120000, salary_to: 150000, 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" }, }, }; test.describe("minimal path from registration to disclosed contacts on the real core", () => { test.skip(!enabled, "Requires the registration stand with the fixture bank and categories."); test("confirms, tests, publishes, matches, invites, accepts once, and closes the reads", async ({ browser, page, }) => { test.setTimeout(1_200_000); const candidates: Candidate[] = []; const contexts: BrowserContext[] = []; try { // --- Candidate: confirmed email, profile, questionnaire, test, category. const mainContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); contexts.push(mainContext); const mainPage = await mainContext.newPage(); const mainSuffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); const main: Candidate = { context: mainContext, page: mainPage, email: `path-main-${mainSuffix}@example.test`, phone: `+7902${String(1_000_000 + Math.floor(Math.random() * 8_999_999))}`, fullName: `Основной кандидат ${mainSuffix}`, }; await test.step("a confirmed email opens the profile, the questionnaire, and the test", async () => { await createAccount(mainPage, "candidate", main.email); await saveProfile(main); // A reload and a step back in the history keep one stored profile. await mainPage.reload(); await expect(mainPage.getByLabel("Имя и фамилия")).toHaveValue(main.fullName); const profile = await api(mainPage, "GET", "/api/v1/me/profile"); expect(profile.status).toBe(200); expect(profile.body).toMatchObject({ full_name: { value: main.fullName }, contacts: { email: { value: main.email }, phone: { value: main.phone } }, }); await saveQuestionnaire(mainPage); await mainPage.goBack(); await mainPage.goForward(); const questionnaire = await api(mainPage, "GET", "/api/v1/me/questionnaire"); expect(questionnaire.status).toBe(200); await grantC3(mainPage); }); let mainAttemptId = ""; await test.step("the full test passes and assigns the synthetic category once", async () => { mainAttemptId = await passFullTest(mainPage, 5); const result = await api( mainPage, "GET", `/api/v1/me/assessment-attempts/${mainAttemptId}/result`, ); expect(result.status).toBe(200); expect(result.body).toMatchObject({ attempt_id: mainAttemptId, kind: "root", mode: "demo_basic", outcome: "confirmed", confirmed_grade: "junior", category_decision: { status: "assigned", current_confirmed_grade: "junior", method: "demo_basic_pass_mark", source: "synthetic_demo", }, }); // The history holds one result after a reload and a history step. await mainPage.goto("/candidate/results"); await mainPage.reload(); await mainPage.goBack(); await mainPage.goForward(); const history = await api(mainPage, "GET", "/api/v1/me/assessment-results"); expect(history.status).toBe(200); const items = (history.body as { items: { attempt_id: string }[] }).items; expect(items.map((item) => item.attempt_id)).toEqual([mainAttemptId]); }); await test.step("the card is published after an explicit C2 and shows the category", async () => { await publishCard(mainPage); const preview = await api(mainPage, "GET", "/api/v1/me/privacy/preview"); expect(preview.status).toBe(200); const previewText = JSON.stringify(preview.body); expect(previewText).toContain("synthetic_demo"); for (const secret of [main.email, main.phone, main.fullName]) { expect(previewText).not.toContain(secret); } }); candidates.push(main); // Four more candidates make a group of five identical cards. for (let index = 1; index < 5; index += 1) { const other = await preparedCandidate(browser, index); contexts.push(other.context); candidates.push(other); } // --- Employer A: need, search, explanation, filter, snapshot. const employerEmail = `path-company-${crypto.randomUUID().slice(0, 8)}@example.test`; await createAccount(page, "employer", employerEmail); const organization = await api(page, "POST", "/api/v1/organizations", { name: `Путь ${crypto.randomUUID().slice(0, 6)}`, }); expect(organization.status).toBe(201); const organizationId = (organization.body as { id: string }).id; const need = await api(page, "POST", `/api/v1/organizations/${organizationId}/needs`, { title: "Backend-разработчик платежей", specialization: { value: "backend", status: "confirmed" }, grade: { value: "junior", status: "confirmed" }, required_skills: [{ name: "Go", status: "confirmed" }], }); expect(need.status).toBe(201); const needBody = need.body as { id: string; version: number; requirements_version: number; recommendations: { status: string; categories: unknown[] }; }; const needId = needBody.id; const firstRequirements = needBody.requirements_version; let firstSearch: MatchResult | null = null; const handles: string[] = []; await test.step("the need search lists the five confirmed cards with an explanation", async () => { await page.goto(`/employer/candidates?organization_id=${organizationId}&need_id=${needId}`); await expect(page.getByRole("radio", { name: "По потребности" })).toBeChecked(); await expect(page.getByText(`Версия требований: ${firstRequirements}`)).toBeVisible(); const searched = page.waitForResponse( apiResponse("POST", `/api/v1/organizations/${organizationId}/matches`), ); await page.getByRole("button", { name: "Найти кандидатов" }).click(); const response = await searched; expect(response.status()).toBe(200); firstSearch = (await response.json()) as MatchResult; expect(firstSearch.source).toEqual({ kind: "need", need_id: needId, requirements_version: firstRequirements, }); const confirmed = [...firstSearch.groups.main, ...firstSearch.groups.near]; expect(confirmed).toHaveLength(5); for (const entry of confirmed) { expect(entry).toMatchObject({ specialization: "backend", confirmation_status: "confirmed", category: { specialization: "backend", grade: "junior", basis: "synthetic_demo" }, }); handles.push(entry.candidate_handle); } expect(new Set(handles).size).toBe(5); // The explanation on the screen repeats the components of the server. const group = firstSearch.groups.main.length > 0 ? "Подтвержденные" : "Близкие варианты"; const card = page.getByRole("region", { name: group, exact: true }).getByRole("article"); await expect(card).toHaveCount(5); const toggle = card.first().getByRole("button", { name: /объяснение/ }); await toggle.click(); await expect(toggle).toHaveAttribute("aria-expanded", "true"); const explanation = card.first().getByRole("region", { name: "Объяснение позиции" }); await expect(explanation.locator('[data-component="coverage"]')).toBeVisible(); await expect(explanation.locator('[data-component="semantics"]')).toContainText( "смысловой анализ недоступен", ); // Nothing identifying or any contact reaches the employer before an answer. const resultText = `${JSON.stringify(firstSearch)}\n${await page.locator("main").innerText()}`; for (const candidate of candidates) { for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { expect(resultText).not.toContain(secret); } } }); await test.step("a filter narrows the result and an edited need keeps the old snapshot", async () => { const filtered = await api( page, "POST", `/api/v1/organizations/${organizationId}/matches`, { need_id: needId, requirements_version: firstRequirements, filters: { declared_grade: "senior" }, }, ); expect(filtered.status).toBe(200); // Other specs of the same stand publish unconfirmed cards with other // declared grades, so the check is that the five junior cards of this // run and every other junior card are filtered out. const narrowed = filtered.body as MatchResult; const remaining = [ ...narrowed.groups.main, ...narrowed.groups.near, ...narrowed.groups.unconfirmed, ]; expect(narrowed.groups.main.length + narrowed.groups.near.length).toBe(0); for (const entry of remaining) { expect(handles).not.toContain(entry.candidate_handle); expect(entry.declared_grade).toBe("senior"); } const edited = await api( page, "PATCH", `/api/v1/organizations/${organizationId}/needs/${needId}`, { expected_version: needBody.version, required_skills: [ { name: "Go", status: "confirmed" }, { name: "Kafka", status: "confirmed" }, ], }, ); expect(edited.status).toBe(200); expect( (edited.body as { requirements_version: number }).requirements_version, ).toBeGreaterThan(firstRequirements); const again = await api(page, "POST", `/api/v1/organizations/${organizationId}/matches`, { need_id: needId, requirements_version: firstRequirements, }); expect(again.status).toBe(200); expect(again.body).toEqual(firstSearch); }); // Which candidate stands behind which handle is learned from the inboxes. const invitationOf = new Map(); await test.step("each invitation is delivered once and holds no contact", async () => { for (const handle of handles.slice(0, 3)) { const draft = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations`, { candidate_handle: handle, // The invitation keeps the first requirements snapshot of the need. need: { need_id: needId, requirements_version: firstRequirements }, response_period_days: 7, terms, }, ); expect(draft.status, JSON.stringify(draft.body)).toBe(201); const draftBody = draft.body as { id: string; version: number }; const sent = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations/${draftBody.id}/send`, { expected_version: draftBody.version }, ); expect(sent.status, JSON.stringify(sent.body)).toBe(200); } for (const candidate of candidates) { const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); expect(inbox.status).toBe(200); const items = (inbox.body as { items: CandidateInvitation[] }).items.filter( (item) => item.organization.id === organizationId, ); expect(items.length).toBeLessThanOrEqual(1); if (items[0]) invitationOf.set(candidate, items[0].id); } expect(invitationOf.size).toBe(3); const list = await api(page, "GET", `/api/v1/organizations/${organizationId}/invitations`); expect(list.status).toBe(200); const listText = JSON.stringify(list.body); expect((list.body as { items: unknown[] }).items).toHaveLength(3); for (const candidate of candidates) { for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { expect(listText).not.toContain(secret); } } }); const [accepting, racing, declining] = [...invitationOf.entries()]; if (!accepting || !racing || !declining) throw new Error("Three invitations are needed."); await test.step("the candidate accepts in the browser and a reload or history step adds nothing", async () => { const [candidate, invitationId] = accepting; const candidatePage = candidate.page; await candidatePage.goto("/candidate/invitations"); await candidatePage.goto(`/candidate/invitations/${invitationId}`); await expect( candidatePage.getByRole("heading", { level: 1, name: "Приглашение" }), ).toBeVisible(); await candidatePage .getByRole("checkbox", { name: "Электронная почта", exact: true }) .check(); await candidatePage .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) .check(); const accepted = candidatePage.waitForResponse( apiResponse("POST", `/api/v1/me/invitations/${invitationId}/accept`), ); await candidatePage.getByRole("button", { name: "Принять и передать контакты" }).click(); expect((await accepted).status()).toBe(200); await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); await candidatePage.reload(); await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); await candidatePage.goBack(); await candidatePage.goForward(); await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); await expect( candidatePage.getByRole("button", { name: "Принять и передать контакты" }), ).toHaveCount(0); const read = await myInvitation(candidate, invitationId); expect(read).toMatchObject({ state: "accepted", contact_grant: { fields: ["email"], status: "active" }, }); expect(await c4Records(candidate, organizationId)).toHaveLength(1); const contacts = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, ); expect(contacts.status).toBe(200); expect(contacts.body).toMatchObject({ email: candidate.email, phone: null, full_name: null, }); }); await test.step("two concurrent acceptances make one transition, one C4, and one grant", async () => { const [candidate, invitationId] = racing; const before = await myInvitation(candidate, invitationId); // C4 has no settings text: the offer of the invitation carries it. const offer = before.contact_consent; if (!offer) throw new Error("The delivered invitation offers no C4 consent."); expect([...offer.available_fields].sort()).toEqual(["email", "full_name", "phone"]); const answers = await concurrently( candidate.page, `/api/v1/me/invitations/${invitationId}/accept`, { expected_version: before.version, terms_version: before.terms_version, consent_c4: { text_version: offer.text.text_version, accepted: true, fields: ["email", "phone"], }, }, ); expect(answers.map((answer) => answer.status)).toEqual([200, 200]); expect(answers[0]?.body).toEqual(answers[1]?.body); const after = await myInvitation(candidate, invitationId); expect(after.state).toBe("accepted"); expect([...(after.contact_grant?.fields ?? [])].sort()).toEqual(["email", "phone"]); expect(after.contact_grant?.id).toBe( (answers[0]?.body as CandidateInvitation).contact_grant?.id, ); expect(await c4Records(candidate, organizationId)).toHaveLength(1); const contacts = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, ); expect(contacts.status).toBe(200); expect(contacts.body).toMatchObject({ email: candidate.email, phone: candidate.phone }); }); await test.step("a decline gives no access and pauses a new invitation", async () => { const [candidate, invitationId] = declining; const declined = await api( candidate.page, "POST", `/api/v1/me/invitations/${invitationId}/decline`, { expected_version: (await myInvitation(candidate, invitationId)).version, reason: "other", }, ); expect(declined.status).toBe(200); const contacts = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, ); expect(contacts.status).toBe(404); expect((await myInvitation(candidate, invitationId)).contact_grant).toBeNull(); // A new invitation for the same pair is refused at the send for 30 days. const sentRead = await api( page, "GET", `/api/v1/organizations/${organizationId}/invitations/${invitationId}`, ); expect(sentRead.status).toBe(200); const handle = (sentRead.body as { candidate_handle: string }).candidate_handle; const draft = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations`, { candidate_handle: handle, response_period_days: 7, terms, }, ); expect(draft.status, JSON.stringify(draft.body)).toBe(201); const draftBody = draft.body as { id: string; version: number }; const resent = await api( page, "POST", `/api/v1/organizations/${organizationId}/invitations/${draftBody.id}/send`, { expected_version: draftBody.version }, ); expect(resent.status, JSON.stringify(resent.body)).toBe(409); expect(resent.body).toMatchObject({ code: "state_conflict" }); const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); expect( (inbox.body as { items: CandidateInvitation[] }).items.filter( (item) => item.organization.id === organizationId, ), ).toHaveLength(1); }); await test.step("the organization inbox names no contact before or after the answers", async () => { const notifications = await api( page, "GET", `/api/v1/organizations/${organizationId}/notifications`, ); expect(notifications.status).toBe(200); const text = JSON.stringify(notifications.body); for (const candidate of candidates) { for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { expect(text).not.toContain(secret); } } }); // --- Company B uses none of the objects of company A. await test.step("another company reads no need, card, invitation, or contact of the first", async () => { const otherContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); contexts.push(otherContext); const other = await otherContext.newPage(); await createAccount( other, "employer", `path-other-${crypto.randomUUID().slice(0, 8)}@example.test`, ); const otherOrganization = await api(other, "POST", "/api/v1/organizations", { name: `Чужая ${crypto.randomUUID().slice(0, 6)}`, }); expect(otherOrganization.status).toBe(201); const otherId = (otherOrganization.body as { id: string }).id; const [, acceptedId] = accepting; // A foreign handle in a draft is a field error; every read is not found // or forbidden. No answer carries a value of a candidate. const denied: [string, ApiResult, number[]][] = [ [ "need of A in its own path", await api(other, "GET", `/api/v1/organizations/${organizationId}/needs/${needId}`), [403, 404], ], [ "need of A under B", await api(other, "GET", `/api/v1/organizations/${otherId}/needs/${needId}`), [404], ], [ "search by the need of A", await api(other, "POST", `/api/v1/organizations/${otherId}/matches`, { need_id: needId, requirements_version: firstRequirements, }), [404], ], [ "card by a handle of A", await api( other, "GET", `/api/v1/organizations/${otherId}/candidate-cards/${handles[0]}`, ), [404], ], [ "invitation of A", await api( other, "GET", `/api/v1/organizations/${organizationId}/invitations/${acceptedId}`, ), [403, 404], ], [ "contacts of A in its own path", await api( other, "GET", `/api/v1/organizations/${organizationId}/invitations/${acceptedId}/contacts`, ), [403, 404], ], [ "contacts of A under B", await api( other, "GET", `/api/v1/organizations/${otherId}/invitations/${acceptedId}/contacts`, ), [404], ], [ "draft for a handle of A", await api(other, "POST", `/api/v1/organizations/${otherId}/invitations`, { candidate_handle: handles[0], response_period_days: 7, terms, }), [400, 404], ], ]; for (const [name, answer, allowed] of denied) { expect(allowed, `${name}: ${answer.status} ${JSON.stringify(answer.body)}`).toContain( answer.status, ); for (const candidate of candidates) { for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { expect(JSON.stringify(answer.body)).not.toContain(secret); } } } const draftRefusal = denied.at(-1)?.[1]; if (draftRefusal?.status === 400) { expect(JSON.stringify(draftRefusal.body)).toContain("/candidate_handle"); } const otherList = await api(other, "GET", `/api/v1/organizations/${otherId}/invitations`); expect(otherList.status).toBe(200); expect((otherList.body as { items: unknown[] }).items).toHaveLength(0); }); // --- Revocation of C2 closes the reads; a new publication does not reopen them. await test.step("C2 revocation closes contacts, the card, and the old search; republishing keeps them closed", async () => { const [candidate, invitationId] = racing; const contactsPath = `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`; const revoked = await api(candidate.page, "DELETE", "/api/v1/me/consents/c2"); expect(revoked.status).toBe(204); const closedRead = await api(page, "GET", contactsPath); expect(closedRead.status, JSON.stringify(closedRead.body)).not.toBe(200); expect(JSON.stringify(closedRead.body)).not.toContain(candidate.email); const grant = (await myInvitation(candidate, invitationId)).contact_grant; expect(grant?.status).not.toBe("active"); // The handles of the earlier result no longer open the cards: the // revoked card is closed, and the four left fall below the group of // five, so they are suppressed as well. A new search lists none. const searchByNeed = async (): Promise => { const result = await api( page, "POST", `/api/v1/organizations/${organizationId}/matches`, { need_id: needId, requirements_version: firstRequirements, }, ); expect(result.status).toBe(200); return result.body as MatchResult; }; const cardStatuses = async (): Promise => { const statuses: number[] = []; for (const handle of handles) { const card = await api( page, "GET", `/api/v1/organizations/${organizationId}/candidate-cards/${handle}`, ); statuses.push(card.status); } return statuses; }; expect(await cardStatuses()).toEqual([404, 404, 404, 404, 404]); const closed = await searchByNeed(); expect(closed.groups.main.length + closed.groups.near.length).toBe(0); // A new C2 and a new publication make the group of five again, but the // grant of the accepted invitation stays closed until a new C4. await publishCard(candidate.page); expect(await cardStatuses()).toEqual([200, 200, 200, 200, 200]); const reopened = await searchByNeed(); expect(reopened.groups.main.length + reopened.groups.near.length).toBe(5); const reread = await api(page, "GET", contactsPath); expect(reread.status).not.toBe(200); expect(JSON.stringify(reread.body)).not.toContain(candidate.email); const after = await myInvitation(candidate, invitationId); expect(after.state).toBe("accepted"); expect(after.contact_grant?.status).not.toBe("active"); // The other accepted invitation keeps its own grant. const [acceptedCandidate, acceptedId] = accepting; expect((await myInvitation(acceptedCandidate, acceptedId)).contact_grant?.status).toBe( "active", ); }); } finally { await Promise.all(contexts.map((context) => context.close())); } }); });