Files
lincodex/frontend/e2e/privacy-visibility.spec.ts
T

972 lines
45 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { expect, test, type Locator, type Page, type Response, type Route } from "@playwright/test";
// Two groups share this file. The first runs against the real backend: the
// isolated privacy fixture candidate (E2E_CONSENT_FIXTURE) and a freshly
// registered candidate (E2E_MAIL_FIXTURE). The second answers every API call
// from a small stateful fake, so it checks how the screen renders states that
// the isolated stand cannot produce yet, such as a confirmed category next to
// unconfirmed ones. Neither group reads the card as an employer: the
// organization read path needs search results, which do not exist yet.
const consentFixtureEnabled = process.env.E2E_CONSENT_FIXTURE === "1";
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const fixtureEmail = "privacy-browser@example.test";
const fixturePassword = "browser privacy fixture 2026";
const registeredPassword = "correct horse battery staple 2026";
const firstCompany = "Приватная компания А";
const secondCompany = "Приватная компания Б";
test.use({ trace: "off", screenshot: "off", video: "off" });
type InboxMessage = { text?: string; html?: string };
function apiResponse(method: string, pathname: string | RegExp) {
return (response: Response) => {
const url = new URL(response.url());
const matches =
typeof pathname === "string" ? url.pathname === pathname : pathname.test(url.pathname);
return matches && response.request().method() === method;
};
}
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
for (const width of [360, 768, 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);
}
}
async function hasVisibleFocusRing(element: Locator): Promise<boolean> {
return element.evaluate((node) => {
if (!(node instanceof HTMLElement) || !node.matches(":focus-visible")) return false;
const style = getComputedStyle(node);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
}
// Moves focus with Tab only, so the check proves that a keyboard user reaches
// the control in a sensible order and sees where the focus is.
async function focusByTab(page: Page, target: Locator): Promise<void> {
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 120; attempt += 1) {
await page.keyboard.press("Tab");
if (await target.evaluate((element) => element === document.activeElement)) {
expect(await hasVisibleFocusRing(target)).toBe(true);
return;
}
}
throw new Error("Keyboard navigation did not reach the requested control.");
}
async function expectKeyboardFocusAtEveryWidth(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await page.keyboard.press("Tab");
const active = page.locator(":focus");
expect(await hasVisibleFocusRing(active), `visible keyboard focus at ${width}px`).toBe(true);
}
}
async function captureReview(page: Page, name: string): Promise<void> {
const directory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
for (const width of [360, 1280]) {
await page.setViewportSize({ width, height: 1400 });
await page.screenshot({
path: `${directory}/${name}-${width}.png`,
animations: "disabled",
fullPage: true,
});
}
}
async function signIn(page: Page, email: string, password: string): Promise<void> {
await page.goto("/login");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponse = page.waitForResponse(apiResponse("POST", "/api/v1/identity/sessions"));
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
}
function publicationSection(page: Page): Locator {
return page.getByRole("region", { name: "Публикация карточки", exact: true });
}
function previewSection(page: Page): Locator {
return page.getByRole("region", { name: "Предварительный просмотр карточки", exact: true });
}
function organizationSection(page: Page): Locator {
return page.getByRole("region", { name: "Компании и скрытие профиля", exact: true });
}
// Drives the keyboard-only path: the radio group, a checkbox and the save
// button are reached with Tab and operated with arrows, Space and Enter.
async function publishFromKeyboard(page: Page, checkboxName: string): Promise<void> {
const publication = publicationSection(page);
const closedChoice = publication.getByRole("radio", { name: "Оставить карточку закрытой" });
await focusByTab(page, closedChoice);
await page.keyboard.press("ArrowDown");
await expect(
publication.getByRole("radio", { name: "Опубликовать выбранные поля" }),
).toBeChecked();
const field = publication.getByRole("checkbox", { name: checkboxName });
await focusByTab(page, field);
await page.keyboard.press("Space");
await expect(field).toBeChecked();
const save = publication.getByRole("button", { name: "Сохранить публикацию" });
await focusByTab(page, save);
const saved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/privacy/publication"));
await page.keyboard.press("Enter");
expect((await saved).status()).toBe(200);
}
test.describe("candidate visibility with the real backend", () => {
test.skip(!consentFixtureEnabled, "Requires the isolated privacy fixture.");
test("publishes only after an explicit C2, hides one company and keeps closed access closed", async ({
page,
}) => {
test.setTimeout(150_000);
await signIn(page, fixtureEmail, fixturePassword);
const previewLoaded = page.waitForResponse(apiResponse("GET", "/api/v1/me/privacy/preview"));
await page.goto("/candidate/privacy");
await expect(
page.getByRole("heading", { name: "Публикация карточки", exact: true }),
).toBeVisible();
expect((await previewLoaded).status()).toBe(200);
const publication = publicationSection(page);
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(
publication.getByText("Согласие C2 действует. Оно само по себе не включает публикацию."),
).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
// The search status is its own setting: confirming it publishes nothing.
const search = page.getByRole("region", { name: "Статус поиска", exact: true });
const statusSaved = page.waitForResponse(
apiResponse("PUT", "/api/v1/me/privacy/search-status"),
);
await search.getByRole("button", { name: "Подтвердить статус «Ищу»" }).click();
expect((await statusSaved).status()).toBe(200);
await expect(search.getByText("Вы подтвердили, что ищете работу.")).toBeVisible();
await expect(
search.getByText("Статус поиска обновлен. Настройки публикации не изменены."),
).toBeVisible();
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
const afterStatus = await page.request.get("/api/v1/me/privacy");
expect(
((await afterStatus.json()) as { publication: { state: string } }).publication.state,
).toBe("closed");
// Publication is a separate, explicit save with the chosen groups.
await publication.getByRole("radio", { name: "Опубликовать выбранные поля" }).check();
await publication.getByRole("checkbox", { name: "Подтвержденная категория и уровень" }).check();
await publication.getByRole("checkbox", { name: "Самооценка по направлениям" }).check();
const published = page.waitForResponse(apiResponse("PUT", "/api/v1/me/privacy/publication"));
const previewAfterPublish = page.waitForResponse(
apiResponse("GET", "/api/v1/me/privacy/preview"),
);
await publication.getByRole("button", { name: "Сохранить публикацию" }).click();
const publishedBody = (await (await published).json()) as {
state: string;
fields: string[];
};
expect(publishedBody.state).toBe("published");
expect(publishedBody.fields).toEqual(["categories", "self_assessment"]);
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
// The owner preview shows what the API returned, and nothing else.
const previewBody = (await (await previewAfterPublish).json()) as {
state: string;
card: { pseudonym: string } | null;
};
expect(previewBody.state).toBe("published");
expect(previewBody.card).not.toBeNull();
await expect(previewSection(page).getByText(previewBody.card?.pseudonym ?? "")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toHaveCount(0);
// Who read the card, when, and at which detail. Organizations appear by
// name only because the server names them.
const access = page.getByRole("region", { name: "История доступа к карточке", exact: true });
await expect(access.getByText(firstCompany)).toHaveCount(2);
await expect(access.getByText(secondCompany)).toHaveCount(1);
await expect(access.getByText("Открыты контактные данные")).toBeVisible();
await expect(access.getByText("Просмотрена карточка профиля")).toHaveCount(2);
await expect(access.locator("time")).toHaveCount(3);
await expect(access.getByText("Показана вся история.")).toBeVisible();
// Hide the profile from company A only.
const organizations = organizationSection(page);
const hideList = organizations.getByRole("region", {
name: "Скрыть профиль от организации",
exact: true,
});
const hidden = page.waitForResponse(
apiResponse("PUT", /^\/api\/v1\/me\/privacy\/hidden-organizations\/[0-9a-f-]{36}$/),
);
await hideList
.getByRole("listitem")
.filter({ hasText: firstCompany })
.getByRole("button", { name: "Скрыть профиль" })
.click();
expect((await hidden).status()).toBe(200);
await expect(
organizations.getByText(
`Профиль скрыт от компании «${firstCompany}». Ее будущие чтения карточки закрыты.`,
{ exact: false },
),
).toBeVisible();
await expect(
organizations.getByText("новое приглашение и новое согласие C4", { exact: false }).first(),
).toBeVisible();
const hiddenList = organizations.getByRole("region", {
name: "Профиль скрыт от компаний",
exact: true,
});
await expect(hiddenList.getByText(firstCompany)).toBeVisible();
await expect(hiddenList.getByText(secondCompany)).toHaveCount(0);
await expect(
page
.getByRole("region", { name: "История настроек приватности", exact: true })
.getByText("Профиль скрыт от компании"),
).toBeVisible();
await expect(
access.getByText("Сейчас профиль скрыт от этой организации").first(),
).toBeVisible();
await expect(
page.getByText(
"Профиль скрыт от этой компании. Запись C4 остается в журнале, но не возвращает доступ к контактам",
),
).toBeVisible();
// The preview is not organization-specific, so hiding leaves it as it was.
const previewAfterHide = await page.request.get("/api/v1/me/privacy/preview");
expect(((await previewAfterHide.json()) as { state: string }).state).toBe("published");
// Bringing the company back does not restore any earlier contact grant.
const unhidden = page.waitForResponse(
apiResponse("DELETE", /^\/api\/v1\/me\/privacy\/hidden-organizations\/[0-9a-f-]{36}$/),
);
await hiddenList.getByRole("button", { name: "Снова разрешить просмотр" }).click();
expect((await unhidden).status()).toBe(204);
await expect(
organizations.getByText("Прежний доступ к контактам не восстановлен", { exact: false }),
).toBeVisible();
await expect(organizations.getByText("Скрытых компаний нет")).toBeVisible();
await expect(page.getByText("Профиль скрыт от этой компании. Запись C4")).toHaveCount(0);
await expect(access.getByText("Сейчас профиль скрыт от этой организации")).toHaveCount(0);
await expect(
page
.getByRole("region", { name: "История настроек приватности", exact: true })
.getByText("Профиль снова доступен компании"),
).toBeVisible();
await captureReview(page, "privacy-published");
// Revoking C2 closes the card at once and explains what that means.
await page.setViewportSize({ width: 1280, height: 900 });
const c2Block = page.locator("#consent-purpose-c2");
const revoked = page.waitForResponse(apiResponse("DELETE", "/api/v1/me/consents/c2"));
await c2Block.getByRole("button", { name: "Отозвать C2", exact: true }).click();
await c2Block.getByLabel("Я понимаю последствия отзыва C2.").check();
await c2Block.getByRole("button", { name: "Подтвердить отзыв" }).click();
expect((await revoked).status()).toBe(204);
await expect(page.getByText("C2 отозвано. Карточка закрыта", { exact: false })).toBeVisible();
await expect(publication.getByText("Согласие C2 отозвано, карточка закрыта")).toBeVisible();
await expect(publication.getByText("Будущие чтения карточки компаниями закрыты")).toBeVisible();
await expect(
publication.getByText("Компании, которая уже получала контакты, нужны новое приглашение"),
).toBeVisible();
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
await expect(
publication.getByText("Для публикации сначала отдельно примите согласие C2"),
).toBeVisible();
const afterRevoke = await page.request.get("/api/v1/me/privacy");
const afterRevokeBody = (await afterRevoke.json()) as {
publication: { state: string; closed_reason: string };
};
expect(afterRevokeBody.publication.state).toBe("closed");
expect(afterRevokeBody.publication.closed_reason).toBe("consent_revoked");
// The step only moves the reader to the consent block; it grants nothing.
await publication.getByRole("button", { name: "Перейти к согласию C2" }).click();
await expect(c2Block).toBeFocused();
const consentGets = await page.request.get("/api/v1/me/consents?state=active&limit=100");
const activeAfterStep = (await consentGets.json()) as { items: { purpose: string }[] };
expect(activeAfterStep.items.some((record) => record.purpose === "c2")).toBe(false);
// A new C2 is a separate, explicit action and still does not reopen the card.
await c2Block.getByRole("button", { name: "Прочитать текущий текст C2" }).click();
await c2Block.getByLabel("Я прочитал(а) и принимаю только это согласие C2.").check();
const regranted = page.waitForResponse(apiResponse("PUT", "/api/v1/me/consents/c2"));
await c2Block.getByRole("button", { name: "Дать согласие C2" }).click();
expect((await regranted).status()).toBe(200);
await expect(
publication.getByText("Согласие C2 действует. Оно само по себе не включает публикацию."),
).toBeVisible();
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(publication.getByText("Новое согласие C2 не откроет карточку само")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
// Publishing again is the explicit step, done here with the keyboard only.
await page.setViewportSize({ width: 1280, height: 900 });
await publishFromKeyboard(page, "Подтвержденная категория и уровень");
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
await page.reload();
await expect(
page.getByRole("heading", { name: "Публикация карточки", exact: true }),
).toBeVisible();
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
await expectNoHorizontalOverflow(page);
await expectKeyboardFocusAtEveryWidth(page);
});
});
test.describe("candidate without a confirmed grade with the real backend", () => {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token) {
throw new Error("The local registration mailbox fixture is not configured.");
}
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as { messages: InboxMessage[] }).messages;
}
async function verificationToken(email: string): Promise<string> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(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 local registration message had no verification link.");
return token;
}
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
async function registerCandidate(page: Page): Promise<string> {
const email = `privacy-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(registeredPassword);
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 base = process.env.E2E_BASE_URL;
if (!base) throw new Error("The local end-to-end base URL is not configured.");
const verificationUrl = new URL("/verify-email", base);
verificationUrl.hash = `token=${await verificationToken(email)}`;
await page.goto(verificationUrl.toString());
await page.getByLabel("Пароль, выбранный при регистрации").fill(registeredPassword);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
return email;
}
test("publishes without a test and shows each specialization as not confirmed", async ({
page,
}) => {
test.setTimeout(180_000);
const email = await registerCandidate(page);
await signIn(page, email, registeredPassword);
// Two declared specializations in the profile, none confirmed by a test.
await page.goto("/candidate/profile");
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат");
// The profile is a form in steps: roles are the second step.
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Роли$/ })).toBeFocused();
await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByLabel("Специализация").nth(0).selectOption("backend");
await page.getByLabel("Специализация").nth(1).selectOption("network_engineer");
await page.getByLabel("Моя оценка уровня").nth(0).selectOption("middle");
await page.getByLabel("Моя оценка уровня").nth(1).selectOption("junior");
for (const heading of ["Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
).toBeFocused();
}
const profileSaved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile"));
await page.getByRole("button", { name: "Сохранить профиль" }).click();
expect((await profileSaved).status()).toBe(200);
await page.goto("/candidate/privacy");
const publication = publicationSection(page);
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
// Without C2 the save stays unavailable and the page grants nothing itself.
await publication.getByRole("radio", { name: "Опубликовать выбранные поля" }).check();
await publication.getByRole("checkbox", { name: "Самооценка по направлениям" }).check();
await expect(
publication.getByText("Для публикации сначала отдельно примите согласие C2"),
).toBeVisible();
await expect(publication.getByRole("button", { name: "Сохранить публикацию" })).toBeDisabled();
// The C2 step is explicit: read the current text, accept it, grant it.
await publication.getByRole("button", { name: "Перейти к согласию C2" }).click();
const c2Block = page.locator("#consent-purpose-c2");
await expect(c2Block).toBeFocused();
await c2Block.getByRole("button", { name: "Прочитать текущий текст C2" }).click();
await c2Block.getByLabel("Я прочитал(а) и принимаю только это согласие C2.").check();
const granted = page.waitForResponse(apiResponse("PUT", "/api/v1/me/consents/c2"));
await c2Block.getByRole("button", { name: "Дать согласие C2" }).click();
expect((await granted).status()).toBe(200);
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
const published = page.waitForResponse(apiResponse("PUT", "/api/v1/me/privacy/publication"));
await publication.getByRole("button", { name: "Сохранить публикацию" }).click();
expect((await published).status()).toBe(200);
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
const preview = previewSection(page);
await expect(preview.getByText("Backend", { exact: true })).toBeVisible();
await expect(preview.getByText("Сетевое администрирование", { exact: true })).toBeVisible();
await expect(preview.getByText("Грейд не подтвержден")).toHaveCount(2);
await expect(preview.getByText("Грейд подтвержден")).toHaveCount(0);
await expect(preview.getByText("Заявлено: Middle")).toBeVisible();
await expect(preview.getByText("Заявлено: Junior")).toBeVisible();
await captureReview(page, "privacy-unconfirmed-grade");
await expectNoHorizontalOverflow(page);
});
});
type FakeEvent = {
id: string;
kind: string;
occurred_at: string;
fields?: string[];
consent_id?: string;
organization?: { id: string; name: string } | null;
};
type FakeAccess = {
id: string;
kind: "card_viewed" | "contact_read";
occurred_at: string;
organization: { id: string; name: string } | null;
};
type FakePublication = {
state: "closed" | "published";
closed_reason: "never_published" | "closed_by_candidate" | "consent_revoked" | null;
fields: string[];
consent_id: string | null;
published_at: string | null;
version: number;
};
type FakeState = {
c2Active: boolean;
publication: FakePublication;
searchStatus: {
value: "looking" | "not_looking";
lapsed: boolean;
confirmed_at: string | null;
lapses_at: string | null;
version: number;
};
events: FakeEvent[];
access: FakeAccess[];
hidden: { organization: { id: string; name: string }; hidden_at: string }[];
failPublication: boolean;
calls: string[];
};
const accountId = "01928f7a-0000-7000-8000-000000000001";
const c2RecordId = "01928f7a-0000-7000-8000-0000000000c2";
const orgA = { id: "01928f7a-0000-7000-8000-00000000a001", name: "Компания А" };
const orgB = { id: "01928f7a-0000-7000-8000-00000000b001", name: "Компания Б" };
function closedPublication(
reason: FakePublication["closed_reason"] = "never_published",
version = 0,
): FakePublication {
return {
state: "closed",
closed_reason: reason,
fields: [],
consent_id: null,
published_at: null,
version,
};
}
function freshState(overrides: Partial<FakeState> = {}): FakeState {
return {
c2Active: true,
publication: closedPublication(),
searchStatus: {
value: "not_looking",
lapsed: false,
confirmed_at: null,
lapses_at: null,
version: 0,
},
events: [],
access: [],
hidden: [],
failPublication: false,
calls: [],
...overrides,
};
}
function consentRecord(
id: string,
purpose: "c1" | "c2",
state: "active" | "revoked",
): Record<string, unknown> {
return {
id,
purpose,
state,
text_version: `${purpose}-2026-10-01`,
source: purpose === "c1" ? "registration" : "consent_settings",
granted_at: "2026-10-01T09:00:00Z",
revoked_at: state === "revoked" ? "2026-10-02T09:00:00Z" : null,
revocation_source: state === "revoked" ? "consent_settings" : null,
organization: null,
fields: null,
invitation_id: null,
invitation_terms_version: null,
};
}
const pseudonym = `cv1_${"a".repeat(43)}`;
// Preview of a candidate whose Backend is confirmed and whose network and QA
// specializations are only declared. The fields follow the publication.
function previewFor(state: FakeState): Record<string, unknown> {
if (state.publication.state === "closed") {
return {
state: "closed",
fields: [],
card: null,
evidence: null,
generated_at: "2026-10-08T12:00:00Z",
};
}
const fields = state.publication.fields;
return {
state: "published",
fields,
card: {
pseudonym,
categories: fields.includes("categories")
? [{ specialization: "backend", grade: "middle", strength: "standard" }]
: null,
stack: null,
self_assessment: fields.includes("self_assessment")
? [
{
specialization: "backend",
confirmation_status: "confirmed",
declared_grade: "middle",
},
{
specialization: "network_engineer",
confirmation_status: "unconfirmed",
declared_grade: "junior",
},
{ specialization: "qa", confirmation_status: "unconfirmed", declared_grade: null },
]
: null,
experience_band: null,
work_formats: null,
salary_compatibility: null,
projects: fields.includes("projects")
? [
{
title: "Платежный шлюз",
description: "Проводки и сверки платежей.",
stack: ["Go", "PostgreSQL"],
repository_verified: true,
},
{ title: "Каталог", description: null, stack: [], repository_verified: false },
]
: null,
},
evidence: fields.includes("categories")
? {
items: [
{
skill: "backend",
grade: "middle",
trust: 1,
basis: "synthetic_demo",
calibration_status: "uncalibrated",
observed_year: 2026,
},
],
}
: { items: [] },
generated_at: "2026-10-08T12:00:00Z",
};
}
function problemBody(status: number, code: string): string {
return JSON.stringify({ type: `urn:lincodex:problem:${code}`, title: code, status, code });
}
async function installFakeApi(page: Page, state: FakeState): Promise<void> {
await page.route("**/api/v1/**", async (route: Route) => {
const request = route.request();
const { pathname, searchParams } = new URL(request.url());
const method = request.method();
state.calls.push(`${method} ${pathname}`);
const json = (status: number, body: unknown) =>
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
const problem = (status: number, code: string) =>
route.fulfill({
status,
contentType: "application/problem+json",
body: problemBody(status, code),
});
const bodyOf = () => JSON.parse(request.postData() ?? "{}") as Record<string, unknown>;
const page100 = (items: unknown[]) => ({ items, page: { has_more: false, next_cursor: null } });
if (method === "GET" && pathname === "/api/v1/identity/sessions/current") {
return json(200, {
account: {
id: accountId,
email: "person@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "candidate_assessment",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
});
}
if (method === "GET" && pathname === "/api/v1/me/privacy") {
return json(200, {
publication: state.publication,
search_status: state.searchStatus,
hidden_organizations_total: state.hidden.length,
});
}
if (method === "PUT" && pathname === "/api/v1/me/privacy/publication") {
if (state.failPublication) return problem(500, "internal_error");
const body = bodyOf();
if (body.state === "published" && !state.c2Active) return problem(409, "state_conflict");
const version = state.publication.version + 1;
state.publication =
body.state === "published"
? {
state: "published",
closed_reason: null,
fields: body.fields as string[],
consent_id: c2RecordId,
published_at: "2026-10-08T12:30:00Z",
version,
}
: closedPublication("closed_by_candidate", version);
state.events.unshift({
id: crypto.randomUUID(),
kind: body.state === "published" ? "publication_opened" : "publication_closed",
occurred_at: "2026-10-08T12:30:00Z",
fields: state.publication.fields,
consent_id: c2RecordId,
});
return json(200, state.publication);
}
if (method === "GET" && pathname === "/api/v1/me/privacy/preview") {
return json(200, previewFor(state));
}
if (method === "PUT" && pathname === "/api/v1/me/privacy/search-status") {
const body = bodyOf();
state.searchStatus = {
value: body.value as "looking" | "not_looking",
lapsed: false,
confirmed_at: body.value === "looking" ? "2026-10-08T12:31:00Z" : null,
lapses_at: body.value === "looking" ? "2099-11-07T12:31:00Z" : null,
version: state.searchStatus.version + 1,
};
return json(200, state.searchStatus);
}
if (method === "GET" && pathname === "/api/v1/me/privacy/hidden-organizations") {
return json(200, page100(state.hidden));
}
const hiddenMatch = /^\/api\/v1\/me\/privacy\/hidden-organizations\/([0-9a-f-]{36})$/.exec(
pathname,
);
if (hiddenMatch && method === "PUT") {
const organization = [orgA, orgB].find((item) => item.id === hiddenMatch[1]);
if (!organization) return problem(404, "not_found");
const entry = { organization, hidden_at: "2026-10-08T12:32:00Z" };
state.hidden = [
entry,
...state.hidden.filter((item) => item.organization.id !== organization.id),
];
state.events.unshift({
id: crypto.randomUUID(),
kind: "organization_hidden",
occurred_at: entry.hidden_at,
organization,
});
return json(200, entry);
}
if (hiddenMatch && method === "DELETE") {
state.hidden = state.hidden.filter((item) => item.organization.id !== hiddenMatch[1]);
return route.fulfill({ status: 204 });
}
if (method === "GET" && pathname === "/api/v1/me/privacy/history") {
return json(200, page100(state.events));
}
if (method === "GET" && pathname === "/api/v1/me/privacy/access-history") {
return json(200, page100(state.access));
}
if (method === "GET" && pathname === "/api/v1/me/consents") {
const records = [
consentRecord("01928f7a-0000-7000-8000-0000000000c1", "c1", "active"),
consentRecord(c2RecordId, "c2", state.c2Active ? "active" : "revoked"),
];
const wanted = searchParams.get("state");
return json(200, page100(wanted ? records.filter((item) => item.state === wanted) : records));
}
if (method === "GET" && pathname === "/api/v1/me/consent-texts/c2") {
return json(200, {
purpose: "c2",
text_version: "c2-2026-10-01",
text: "Тестовый текст согласия C2.",
published_at: "2026-10-01T00:00:00Z",
});
}
if (method === "PUT" && pathname === "/api/v1/me/consents/c2") {
state.c2Active = true;
return json(200, consentRecord(c2RecordId, "c2", "active"));
}
if (method === "DELETE" && pathname === "/api/v1/me/consents/c2") {
state.c2Active = false;
state.publication = closedPublication("consent_revoked", state.publication.version + 1);
return route.fulfill({ status: 204 });
}
return problem(404, "not_found");
});
}
test.describe("candidate visibility states with a stubbed API", () => {
test("shows a confirmed Backend apart from unconfirmed specializations", async ({ page }) => {
const state = freshState({
publication: {
state: "published",
closed_reason: null,
fields: ["categories", "self_assessment"],
consent_id: c2RecordId,
published_at: "2026-10-08T10:00:00Z",
version: 1,
},
});
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const preview = previewSection(page);
await expect(preview.getByText(`Предварительный псевдоним`)).toBeVisible();
await expect(preview.getByText("Backend: Middle, стандартное подтверждение")).toBeVisible();
await expect(preview.getByText("Грейд подтвержден")).toHaveCount(1);
await expect(preview.getByText("Грейд не подтвержден")).toHaveCount(2);
// Different marks, not only different words and colors.
await expect(preview.locator('[data-level="confirmed"]')).toHaveCount(1);
await expect(preview.locator('[data-level="none"]')).toHaveCount(2);
await expect(preview.getByText("Уровень не указан")).toBeVisible();
await expect(preview.getByText("Заявлено: Junior")).toBeVisible();
await expect(
preview.getByRole("heading", { name: "Подтверждающие факты оценки" }),
).toBeVisible();
await expect(preview.getByText("Результат теста")).toBeVisible();
await expect(preview.getByText(/демонстрац|откалиброван|Калибровка/)).toHaveCount(0);
await expect(preview.getByText("Онлайн-результат без подтверждения личности")).toBeVisible();
await captureReview(page, "privacy-confirmed-and-unconfirmed");
await expectNoHorizontalOverflow(page);
});
test("warns before the projects are published and shows them in the preview without an address", async ({
page,
}) => {
const state = freshState({
publication: {
state: "published",
closed_reason: null,
fields: ["categories", "projects"],
consent_id: c2RecordId,
published_at: "2026-10-08T10:00:00Z",
version: 1,
},
});
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const publication = page.getByRole("region", { name: "Публикация карточки", exact: true });
const projects = publication.getByRole("checkbox", {
name: "Проекты: название, описание и технологии",
});
await expect(projects).toBeChecked();
await expect(publication.getByText(/по ним вас могут узнать/)).toBeVisible();
await expect(
publication.getByText(/Адрес репозитория и его владелец компаниям не показываются никогда/),
).toBeVisible();
const preview = previewSection(page);
await expect(preview.getByRole("heading", { name: "Проекты" })).toBeVisible();
await expect(preview.getByText("Платежный шлюз")).toBeVisible();
await expect(preview.getByText("PostgreSQL", { exact: true })).toBeVisible();
await expect(preview.getByText("Подтвержден публичным репозиторием")).toHaveCount(1);
await expect(preview.locator('a[href*="github"]')).toHaveCount(0);
await expect(preview.getByText(/github\.com/)).toHaveCount(0);
await captureReview(page, "privacy-projects");
await expectNoHorizontalOverflow(page);
});
test("a changed search status never publishes the card", async ({ page }) => {
const state = freshState();
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const publication = publicationSection(page);
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
const search = page.getByRole("region", { name: "Статус поиска", exact: true });
await search.getByRole("button", { name: "Подтвердить статус «Ищу»" }).click();
await expect(search.getByText("Вы подтвердили, что ищете работу.")).toBeVisible();
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
expect(state.calls).toContain("PUT /api/v1/me/privacy/search-status");
expect(state.calls).not.toContain("PUT /api/v1/me/privacy/publication");
expect(state.publication.state).toBe("closed");
});
test("keeps the draft when saving fails and publishes on retry", async ({ page }) => {
const state = freshState({ failPublication: true });
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const publication = publicationSection(page);
await publication.getByRole("radio", { name: "Опубликовать выбранные поля" }).check();
const field = publication.getByRole("checkbox", { name: "Самооценка по направлениям" });
await field.check();
await publication.getByRole("button", { name: "Сохранить публикацию" }).click();
await expect(publication.getByRole("alert")).toContainText("Не удалось сохранить изменение");
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(field).toBeChecked();
await expect(publication.getByRole("button", { name: "Сохранить публикацию" })).toBeEnabled();
state.failPublication = false;
await publication.getByRole("button", { name: "Сохранить публикацию" }).click();
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
await expect(previewSection(page).getByText("Грейд не подтвержден")).toHaveCount(2);
});
test("shows empty histories and an empty list of hidden companies without an error", async ({
page,
}) => {
await installFakeApi(page, freshState());
await page.goto("/candidate/privacy");
await expect(page.getByText("История доступа пока пуста")).toBeVisible();
await expect(page.getByText("История настроек пока пуста")).toBeVisible();
await expect(page.getByText("Скрытых компаний нет")).toBeVisible();
await expect(page.getByText("Нет доступных компаний для скрытия")).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
});
test("names a company only when the server names it and offers hiding only for named ones", async ({
page,
}) => {
const state = freshState({
access: [
{
id: crypto.randomUUID(),
kind: "contact_read",
occurred_at: "2026-10-08T11:00:00Z",
organization: orgA,
},
{
id: crypto.randomUUID(),
kind: "card_viewed",
occurred_at: "2026-10-08T10:00:00Z",
organization: null,
},
],
});
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const access = page.getByRole("region", { name: "История доступа к карточке", exact: true });
await expect(access.getByText("Открыты контактные данные")).toBeVisible();
await expect(access.getByText(orgA.name)).toBeVisible();
await expect(access.getByText("Организация не раскрывается")).toBeVisible();
await expect(access.locator("time")).toHaveCount(2);
const hideList = organizationSection(page).getByRole("region", {
name: "Скрыть профиль от организации",
});
await expect(hideList.getByRole("listitem")).toHaveCount(1);
await hideList.getByRole("button", { name: "Скрыть профиль" }).click();
await expect(
organizationSection(page)
.getByText("Профиль скрыт от компании «Компания А»", { exact: false })
.first(),
).toBeVisible();
await expect(access.getByText("Сейчас профиль скрыт от этой организации")).toBeVisible();
});
test("explains a revoked C2 and does not reopen the card by itself", async ({ page }) => {
const state = freshState({
publication: {
state: "published",
closed_reason: null,
fields: ["categories"],
consent_id: c2RecordId,
published_at: "2026-10-08T10:00:00Z",
version: 1,
},
});
await installFakeApi(page, state);
await page.goto("/candidate/privacy");
const publication = publicationSection(page);
await expect(publication.getByText("Текущее состояние: опубликована.")).toBeVisible();
const c2Block = page.locator("#consent-purpose-c2");
await c2Block.getByRole("button", { name: "Отозвать C2", exact: true }).click();
await c2Block.getByLabel("Я понимаю последствия отзыва C2.").check();
await c2Block.getByRole("button", { name: "Подтвердить отзыв" }).click();
await expect(publication.getByText("Согласие C2 отозвано, карточка закрыта")).toBeVisible();
await expect(publication.getByText("Будущие чтения карточки компаниями закрыты")).toBeVisible();
await expect(publication.getByText("новое приглашение и новое согласие C4")).toBeVisible();
await expect(publication.getByText("Текущее состояние: закрыта.")).toBeVisible();
await expect(previewSection(page).getByText("Карточка закрыта")).toBeVisible();
await publication.getByRole("button", { name: "Перейти к согласию C2" }).click();
await expect(c2Block).toBeFocused();
expect(state.c2Active).toBe(false);
expect(state.calls).not.toContain("PUT /api/v1/me/consents/c2");
await expectNoHorizontalOverflow(page);
await expectKeyboardFocusAtEveryWidth(page);
});
});