feat(privacy): complete the publication, hiding and preview settings screen

This commit is contained in:
shira committed 2026-10-09 12:47:26 +03:00
1 parent c2a8d17195
commit 5edff21d2d
28 files changed
+2230 -428

No files matched your search

+113 -4
View File
@@ -26,7 +26,14 @@ const (
fixturePassword = "browser consent fixture 2026"
firstOwnerEmail = "consent-owner-one@example.test"
secondOwnerEmail = "consent-owner-two@example.test"
fixtureTimeout = 90 * time.Second
// The privacy candidate has its own organizations so that the privacy and
// consent browser suites can run side by side without sharing any state.
privacyEmail = "privacy-browser@example.test"
privacyPassword = "browser privacy fixture 2026"
privacyFirstOwnerMail = "privacy-owner-one@example.test"
privacySecondOwnerMail = "privacy-owner-two@example.test"
fixtureTimeout = 90 * time.Second
)
func main() {
@@ -88,6 +95,10 @@ type fixtureUsers struct {
candidate domain.User
firstOwner domain.User
secondOwner domain.User
privacyCandidate domain.User
privacyFirstOwner domain.User
privacySecondOwner domain.User
}
func newFixtureUsers(
@@ -107,7 +118,22 @@ func newFixtureUsers(
if err != nil {
return fixtureUsers{}, err
}
return fixtureUsers{candidate: candidate, firstOwner: firstOwner, secondOwner: secondOwner}, nil
privacyCandidate, err := newFixtureUser(ctx, hasher, privacyEmail, privacyPassword, domain.ScenarioCandidate, registeredAt)
if err != nil {
return fixtureUsers{}, err
}
privacyFirstOwner, err := newFixtureOwner(ctx, hasher, privacyFirstOwnerMail, registeredAt)
if err != nil {
return fixtureUsers{}, err
}
privacySecondOwner, err := newFixtureOwner(ctx, hasher, privacySecondOwnerMail, registeredAt)
if err != nil {
return fixtureUsers{}, err
}
return fixtureUsers{
candidate: candidate, firstOwner: firstOwner, secondOwner: secondOwner,
privacyCandidate: privacyCandidate, privacyFirstOwner: privacyFirstOwner, privacySecondOwner: privacySecondOwner,
}, nil
}
func newFixtureOwner(
@@ -164,7 +190,10 @@ func seedFixture(
now time.Time,
) error {
return transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
for _, user := range []domain.User{users.candidate, users.firstOwner, users.secondOwner} {
for _, user := range []domain.User{
users.candidate, users.firstOwner, users.secondOwner,
users.privacyCandidate, users.privacyFirstOwner, users.privacySecondOwner,
} {
if err := unit.Users().Create(ctx, user); err != nil {
return err
}
@@ -230,10 +259,90 @@ func seedFixture(
if err := grantFixtureContactConsent(ctx, service, unit, users.candidate.ID, secondOrganization, c4Text.Version(), domain.ContactFieldPhone); err != nil {
return err
}
return nil
return seedPrivacyCandidate(ctx, unit, service, users, now)
})
}
// seedPrivacyCandidate gives the privacy browser suite a candidate whose
// publication consent is active, with one company that holds a contact consent
// and read the card and one company that only read the card. The reads are
// recorded the way an authorized organization read leaves them, because the
// organization read path needs search results that do not exist yet.
func seedPrivacyCandidate(
ctx context.Context,
unit outbound.UnitOfWork,
service *consent.Service,
users fixtureUsers,
now time.Time,
) error {
firstOrganization, err := createOrganization(ctx, unit, users.privacyFirstOwner.ID, "Приватная компания А", now)
if err != nil {
return err
}
secondOrganization, err := createOrganization(ctx, unit, users.privacySecondOwner.ID, "Приватная компания Б", now)
if err != nil {
return err
}
c1Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now)
if err != nil {
return err
}
if _, err := service.GrantAtRegistration(
ctx, unit, users.privacyCandidate.ID, users.privacyCandidate.RegistrationVersion, c1Text.Version(),
); err != nil {
return err
}
c2Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePublication, now)
if err != nil {
return err
}
if _, err := service.GrantInSettings(ctx, unit, consent.SettingsGrantInput{
SubjectID: users.privacyCandidate.ID,
Purpose: domain.ConsentPurposePublication,
TextVersion: c2Text.Version(),
}); err != nil {
return err
}
c4Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now)
if err != nil {
return err
}
if err := grantFixtureContactConsent(
ctx, service, unit, users.privacyCandidate.ID, firstOrganization, c4Text.Version(), domain.ContactFieldEmail,
); err != nil {
return err
}
reads := []domain.CandidateCardAccessInput{
{
CandidateID: users.privacyCandidate.ID, OrganizationID: firstOrganization.ID(), ActorID: users.privacyFirstOwner.ID,
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories},
OccurredAt: now.Add(-3 * time.Hour),
},
{
CandidateID: users.privacyCandidate.ID, OrganizationID: firstOrganization.ID(), ActorID: users.privacyFirstOwner.ID,
Kind: domain.CandidateCardAccessContactRead, ContactFields: []domain.ContactField{domain.ContactFieldEmail},
OccurredAt: now.Add(-2 * time.Hour),
},
{
CandidateID: users.privacyCandidate.ID, OrganizationID: secondOrganization.ID(), ActorID: users.privacySecondOwner.ID,
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories},
OccurredAt: now.Add(-1 * time.Hour),
},
}
for _, input := range reads {
access, err := domain.NewCandidateCardAccess(input)
if err != nil {
return err
}
if err := unit.PrivacyView().RecordCandidateCardAccess(ctx, access); err != nil {
return err
}
}
return nil
}
func createOrganization(
ctx context.Context,
unit outbound.UnitOfWork,
+2
View File
@@ -75,6 +75,8 @@ The registration-mode suite additionally runs `frontend/e2e/auth-registration.sp
In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data.
The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser.
`frontend/e2e/profile-edit.spec.ts` fills the manual profile at 360px after real registration, acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step.
`frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data.
+2
View File
@@ -75,6 +75,8 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f
В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные.
Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется.
`frontend/e2e/profile-edit.spec.ts` заполняет ручной профиль на 360 px после реальной регистрации, подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля.
`frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные.
+12 -1
View File
@@ -81,7 +81,18 @@ On the attempt screen only the phrase "Result received" is a live message; the r
## Privacy settings
`/candidate/privacy` currently shows consent management and a link to request manual assessment. Publication, search status, hidden organizations, preview, and history are available through the backend API, but a dedicated UI for these settings is not implemented. The employer candidate directory is also a placeholder; the server-side anonymous-card read API does not imply that this screen exists.
`pages/privacy` (`/candidate/privacy`) shows separate visibility settings. No action enables another: consent, publication, search status, and hiding an organization are saved by their own requests, each with its own version and its own saving state.
- Consents (`features/consent-management`): C1-C5 are granted and revoked separately, with the text and version shown before a grant. The block of each purpose has an anchor that the "Go to the C2 consent" button moves focus to.
- Publication (`features/profile-visibility`): step 1 shows whether C2 is active from the complete active consent history; an unknown or partly loaded state is not treated as consent, and saving stays unavailable. The step button only moves focus to the C2 block and grants nothing. The card state and fields are chosen next, and the publication is saved by a separate action (`SetMyPublication`, `expected_version` in the body). A 412 conflict keeps the draft on screen and offers an explicit reload of the current settings; a failed save does not reset the draft. Revoking C2 closes the card, and a new C2 does not reopen it.
- Closure explanation: from `closed_reason` the screen says that future reads are closed at once, that a new C2 does not reopen the card by itself, and that a former company needs a new invitation and a new C4 to read contacts. The same words appear after revoking C2, hiding an organization, unhiding it, and republishing: an earlier contact access is not restored. Hiding does not change the C4 record in the consent ledger, so next to the C4 of a hidden company a note says that the record does not bring contact access back.
- Search status (`SetMySearchStatus`) is its own request and its own text. It does not change the publication and grants no consent.
- Employer preview (`EmployerCardPreview` from `entities/candidate-view`) is built only from the `GET /me/privacy/preview` response. The preview alias is separate from organization aliases. Confirmed categories and self-assessment are shown apart; each specialization has its own "Grade confirmed" or "Grade not confirmed" status (the Russian labels are "Грейд подтвержден" and "Грейд не подтвержден"), told apart by the shape of the mark and by text, not by color. A candidate without a confirmed grade sees the declared level (or "Level not specified") and the not-confirmed status for each specialization separately; a confirmed Backend is not carried over to a network specialization. The evidence block shows the skill, grade, confirmation level, year, basis, and calibration as the server returned them (`synthetic_demo` and `uncalibrated` are shown as a synthetic demonstration, not a validated measurement, and as thresholds that are not calibrated). A closed card is shown as an empty state. The preview creates no access record and ignores organization filters.
- Hiding organizations: the hide button is offered only for organizations in the candidate's own access history (the server answers 404 for the rest), and only after the list of hidden organizations is fully loaded. Unhiding does not restore contact access.
- Histories: the settings history and the card access history are paginated; a partial page is never presented as complete. An access record shows the kind of access, the time, and the organization when the server names it (otherwise "Organization is not disclosed"); it carries no employees, queries, filters, or search position. An empty history and a load error are separate states.
- A link to request a manual assessment stays below.
An employer reading the card and the employer candidate directory remain placeholders: the server-side anonymous-card read API does not imply that such a screen exists, so the effect of hiding on a particular employer cannot be checked in a browser.
## Company profile
+12 -1
View File
@@ -81,7 +81,18 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
## Настройки приватности
`/candidate/privacy` сейчас показывает управление согласиями и переход к запросу ручной оценки. Публикация карточки, статус поиска, список скрытых организаций, предпросмотр и история доступны через backend API, но отдельный интерфейс для этих настроек еще не реализован. Каталог кандидатов работодателя также остается заглушкой; наличие серверного API чтения анонимной карточки не означает наличия такого экрана.
`pages/privacy` (`/candidate/privacy`) показывает отдельные настройки видимости. Ни одно действие не включает другое: согласие, публикация, статус поиска и скрытие организации сохраняются своими запросами, у каждого своя версия и свое состояние сохранения.
- Согласия (`features/consent-management`): C1-C5 выдаются и отзываются по отдельности, текст и версия показаны до выдачи. Блок каждой цели имеет якорь, на который переводит фокус кнопка "Перейти к согласию C2".
- Публикация (`features/profile-visibility`): шаг 1 показывает, действует ли C2 по полной активной истории согласий; неизвестное или частично загруженное состояние не считается согласием, сохранение недоступно. Кнопка шага только переносит фокус к блоку C2 и ничего не выдает. Далее выбираются состояние карточки и поля, а публикация сохраняется отдельным действием (`SetMyPublication`, `expected_version` в теле). Конфликт 412 оставляет черновик на экране и предлагает явно загрузить актуальные настройки; ошибка сохранения не сбрасывает черновик. Отзыв C2 закрывает карточку, а новое C2 ее не открывает.
- Объяснение закрытия: по `closed_reason` экран говорит, что будущие чтения закрыты сразу, что новое C2 не откроет карточку само, и что бывшей компании для контактов нужны новое приглашение и новое согласие C4. Те же слова выводятся после отзыва C2, скрытия организации, снятия скрытия и повторной публикации: прежний доступ к контактам не восстанавливается. Скрытие не меняет запись C4 в журнале согласий, поэтому рядом с C4 скрытой компании выведено пояснение, что запись не возвращает доступ к контактам.
- Статус поиска (`SetMySearchStatus`) - отдельный запрос и отдельный текст. Он не меняет публикацию и не выдает согласие.
- Предпросмотр для работодателя (`EmployerCardPreview` из `entities/candidate-view`) строится только из ответа `GET /me/privacy/preview`. Псевдоним предпросмотра отделен от псевдонимов организаций. Подтвержденные категории и самооценка выведены раздельно; у каждой специализации свой статус "Грейд подтвержден" или "Грейд не подтвержден", различимый по форме значка и тексту, а не по цвету. Кандидат без подтвержденного грейда видит заявленный уровень (или "Уровень не указан") и статус "Грейд не подтвержден" для каждой специализации отдельно; подтвержденный Backend не переносится на сетевую специализацию. Блок подтверждающих фактов показывает навык, грейд, уровень подтверждения, год, основу и калибровку так, как их вернул сервер (`synthetic_demo` и `uncalibrated` выведены как "Синтетическая демонстрация, не проверенное измерение" и "Пороги не откалиброваны"). Закрытая карточка показана пустым состоянием. Предпросмотр не создает записи доступа и не учитывает фильтры организаций.
- Скрытие организаций: кнопка скрытия предлагается только организациям из собственной истории доступа (сервер отвечает 404 на остальные) и только после полной загрузки списка скрытых организаций. Снятие скрытия не восстанавливает контактный доступ.
- Истории: история настроек и история доступа к карточке постраничные; частичная страница не выдается за полную. Запись доступа показывает вид обращения, время и организацию, если сервер ее назвал (иначе "Организация не раскрывается"); сотрудников, запросов, фильтров и места в выдаче в ней нет. Пустая история и ошибка загрузки показаны отдельными состояниями.
- Ниже остается переход к запросу ручной оценки.
Чтение карточки работодателем и каталог кандидатов на стороне работодателя остаются заглушкой: наличие серверного API чтения анонимной карточки не означает наличия такого экрана, поэтому влияние скрытия на конкретного работодателя в браузере проверить нельзя.
## Профиль компании
+4
View File
@@ -140,6 +140,10 @@ async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
}
async function focusWithKeyboard(page: Page, target: Locator): Promise<void> {
// The control appears only after the previous answer is saved and the attempt
// is read again. On a loaded stand that takes longer than the default 5 s
// expectation, so wait for it explicitly before walking the tab order.
await expect(target).toBeVisible({ timeout: 20_000 });
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 80; attempt += 1) {
await page.keyboard.press("Tab");
+5 -1
View File
@@ -24,8 +24,12 @@ function consentListResponse(response: {
url(): string;
request(): { method(): string };
}): boolean {
// The privacy screen also reads the active-only list to check C2, so only the
// full history (no state filter) is the list this suite compares.
const url = new URL(response.url());
return (
new URL(response.url()).pathname === "/api/v1/me/consents" &&
url.pathname === "/api/v1/me/consents" &&
!url.searchParams.has("state") &&
response.request().method() === "GET"
);
}
+916
View File
@@ -0,0 +1,916 @@
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("Тестовый кандидат");
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");
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,
},
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("Пороги не откалиброваны")).toBeVisible();
await expect(preview.getByText("Онлайн-результат без подтверждения личности")).toBeVisible();
await captureReview(page, "privacy-confirmed-and-unconfirmed");
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);
});
});
+2 -2
View File
@@ -346,7 +346,7 @@ test.describe("candidate support cases and manual assessment", () => {
const reason = "Прошу эксперта оценить эту категорию вручную.";
const description = page.getByLabel("Почему вы просите ручную оценку");
await description.fill(reason);
await expect(page.getByText(/не требует C3/)).toBeVisible();
await expect(page.getByText(/Отправка не включает и не меняет C3/)).toBeVisible();
await checkResponsiveForm(page, specialization);
await page.setViewportSize({ width: 360, height: 900 });
@@ -376,7 +376,7 @@ test.describe("candidate support cases and manual assessment", () => {
expect(attemptRequests).toEqual([]);
await expect(
page.getByText(
"Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась.",
"Опубликованной рубрики для этой цели на момент запроса не было. Автоматическая оценка не выполнялась, категория не присвоена. Запрос ожидает эксперта.",
),
).toBeVisible();
@@ -1,6 +1,11 @@
export {
cardAccessLabels,
cardFieldLabels,
contactAccessAfterVisibilityChange,
describeAccessOrganization,
describePublicationClosure,
evidenceBasisLabels,
evidenceCalibrationLabels,
buildSearchStatusSubmission,
buildPublicationSubmission,
currentC2State,
@@ -16,9 +21,13 @@ export {
specializationLabels,
} from "./model/presentation";
export { candidateViewQueryKeys } from "./model/query-keys";
export { EmployerCardPreview } from "./ui/employer-card-preview";
export type {
C2State,
CandidateViewPresentation,
EvidencePresentation,
PublicationClosureNotice,
SelfAssessmentPresentation,
PublicationDraft,
PublicationSubmission,
PublishableCardField,
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vitest";
import type { CardField, CardPreview } from "../../../shared/api/schemas";
import { editableCardFields, presentCandidatePreview, publishableCardFields } from "./presentation";
import {
contactAccessAfterVisibilityChange,
describeAccessOrganization,
describePublicationClosure,
editableCardFields,
presentCandidatePreview,
publishableCardFields,
} from "./presentation";
function preview(card: NonNullable<CardPreview["card"]>): CardPreview {
return {
@@ -43,11 +50,99 @@ describe("candidate card presentation", () => {
{
specialization: "Сетевое администрирование",
declaredGrade: "Middle",
confirmed: false,
confirmation: "Грейд не подтвержден",
},
]);
});
it("states the confirmation of every specialization on its own", () => {
const result = presentCandidatePreview(
preview({
pseudonym: `cv1_${"b".repeat(43)}`,
categories: [{ specialization: "backend", grade: "middle", strength: "strong" }],
stack: null,
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 },
],
experience_band: null,
work_formats: null,
salary_compatibility: null,
}),
);
expect(
result?.selfAssessments?.map((item) => [
item.specialization,
item.confirmed,
item.confirmation,
]),
).toEqual([
["Backend", true, "Грейд подтвержден"],
["Сетевое администрирование", false, "Грейд не подтвержден"],
["Тестирование", false, "Грейд не подтвержден"],
]);
expect(result?.selfAssessments?.[2]?.declaredGrade).toBeNull();
});
it("restates the evidence basis and calibration the server reports", () => {
const result = presentCandidatePreview({
...preview({
pseudonym: `cv1_${"c".repeat(43)}`,
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
stack: null,
self_assessment: null,
experience_band: null,
work_formats: null,
salary_compatibility: null,
}),
evidence: {
items: [
{
skill: "backend",
grade: "middle",
trust: 1,
basis: "synthetic_demo",
calibration_status: "uncalibrated",
observed_year: 2026,
},
],
},
});
expect(result?.evidence).toEqual([
{
title: "Backend: Middle",
trust: "partial",
trustLabel: "Онлайн-результат без подтверждения личности",
observedYear: 2026,
basisLabel: "Синтетическая демонстрация, не проверенное измерение",
calibrationLabel: "Пороги не откалиброваны",
},
]);
});
it("keeps an empty evidence list apart from a closed card", () => {
const published = presentCandidatePreview(
preview({
pseudonym: `cv1_${"d".repeat(43)}`,
categories: null,
stack: null,
self_assessment: null,
experience_band: null,
work_formats: null,
salary_compatibility: null,
}),
);
expect(published?.evidence).toEqual([]);
});
it("does not present a closed preview as an empty published card", () => {
expect(
presentCandidatePreview({
@@ -82,3 +177,42 @@ describe("editable card fields", () => {
expect(editableCardFields(stored)).toEqual(["categories", "work_formats"]);
});
});
describe("publication closure explanation", () => {
it("explains a revoked C2 as closed future reads and a new C4 for a former company", () => {
const notice = describePublicationClosure({
state: "closed",
closed_reason: "consent_revoked",
});
const text = [notice?.title, ...(notice?.points ?? [])].join(" ");
expect(text).toContain("Будущие чтения карточки компаниями закрыты");
expect(text).toContain("Новое согласие C2 не откроет карточку само");
expect(text).toContain("новое приглашение и новое согласие C4");
});
it("explains a closing by the candidate and says nothing about a published or new card", () => {
expect(
describePublicationClosure({
state: "closed",
closed_reason: "closed_by_candidate",
})?.points.join(" "),
).toContain("не восстанавливает прежний доступ к контактам");
expect(describePublicationClosure({ state: "published", closed_reason: null })).toBeNull();
expect(
describePublicationClosure({ state: "closed", closed_reason: "never_published" }),
).toBeNull();
});
it("never promises that an unhide or a republish restores a contact grant", () => {
expect(contactAccessAfterVisibilityChange).toContain("не восстанавливают прежний доступ");
expect(contactAccessAfterVisibilityChange).toContain("новое согласие C4");
});
});
describe("card access organization", () => {
it("does not invent a name for an organization the server cannot present", () => {
expect(describeAccessOrganization(null)).toBe("Организация не раскрывается");
expect(describeAccessOrganization({ name: "Компания А" })).toBe("Компания А");
});
});
@@ -5,14 +5,20 @@ import type {
CardPreview,
CardSelfAssessment,
CandidateExperienceBand,
EvidenceBasis,
EvidenceCalibrationStatus,
EvidenceSkillCode,
CandidateSalaryCompatibility,
CandidateWorkFormat,
ConsentRecord,
HiddenOrganization,
OrganizationEvidenceFact,
PrivacySettings,
Publication,
PublicationUpdate,
SearchStatusUpdate,
} from "../../../shared/api/schemas";
import type { TrustLevelValue } from "../../../shared/ui";
export const publishableCardFields = [
"categories",
@@ -196,9 +202,21 @@ export type CategoryPresentation = {
export type SelfAssessmentPresentation = {
specialization: string;
declaredGrade: string | null;
/** True only when the server says this specialization has a confirmed grade. */
confirmed: boolean;
confirmation: string;
};
export type EvidencePresentation = {
/** Skill and passed grade, for example "Backend: Middle". */
title: string;
trust: TrustLevelValue;
trustLabel: string;
observedYear: number;
basisLabel: string;
calibrationLabel: string;
};
export type CandidateViewPresentation = {
pseudonym: string;
categories: readonly CategoryPresentation[] | null;
@@ -207,6 +225,11 @@ export type CandidateViewPresentation = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
/**
* Supporting assessment facts as an organization reads them. Null while the
* card is closed; an empty list when no visible fact supports a category.
*/
evidence: readonly EvidencePresentation[] | null;
};
function categoryPresentation(category: CardCategory): CategoryPresentation {
@@ -222,11 +245,53 @@ function selfAssessmentPresentation(item: CardSelfAssessment): SelfAssessmentPre
return {
specialization: specializationLabels[item.specialization],
declaredGrade: item.declared_grade ? gradeLabels[item.declared_grade] : null,
confirmed: item.confirmation_status === "confirmed",
confirmation:
item.confirmation_status === "confirmed" ? "Грейд подтвержден" : "Грейд не подтвержден",
};
}
const evidenceSkillLabels: Readonly<Record<EvidenceSkillCode, string>> = {
...specializationLabels,
...stackLabels,
};
// The shape of a mark follows the strength of the confirmation, and the label
// always names the exact meaning of the level so it never depends on the shape.
type EvidenceTrustView = { level: TrustLevelValue; label: string };
const claimedEvidence: EvidenceTrustView = {
level: "claimed",
label: "Заявлено, не подтверждено отдельно",
};
const evidenceTrust: Readonly<Record<number, EvidenceTrustView>> = {
0: claimedEvidence,
1: { level: "partial", label: "Онлайн-результат без подтверждения личности" },
2: { level: "confirmed", label: "Результат привязан к подтвержденной личности" },
3: { level: "confirmed", label: "Очная проверка" },
};
export const evidenceBasisLabels: Readonly<Record<EvidenceBasis, string>> = {
synthetic_demo: "Синтетическая демонстрация, не проверенное измерение",
};
export const evidenceCalibrationLabels: Readonly<Record<EvidenceCalibrationStatus, string>> = {
uncalibrated: "Пороги не откалиброваны",
};
function evidencePresentation(fact: OrganizationEvidenceFact): EvidencePresentation {
const trust = evidenceTrust[fact.trust] ?? claimedEvidence;
return {
title: `${evidenceSkillLabels[fact.skill]}: ${gradeLabels[fact.grade]}`,
trust: trust.level,
trustLabel: trust.label,
observedYear: fact.observed_year,
basisLabel: evidenceBasisLabels[fact.basis],
calibrationLabel: evidenceCalibrationLabels[fact.calibration_status],
};
}
export function presentCandidatePreview(preview: CardPreview): CandidateViewPresentation | null {
const card = preview.card;
if (!card) return null;
@@ -241,6 +306,7 @@ export function presentCandidatePreview(preview: CardPreview): CandidateViewPres
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
evidence: preview.evidence ? preview.evidence.items.map(evidencePresentation) : null,
};
}
@@ -269,3 +335,49 @@ export const cardAccessLabels = {
card_viewed: "Просмотрена карточка профиля",
contact_read: "Открыты контактные данные",
} as const;
export type PublicationClosureNotice = {
title: string;
points: readonly string[];
};
/**
* Explains a closed card to its owner. The text restates the server reason and
* the contract rules: a closed card is unreadable at once, and neither a new
* C2 nor an unhide reopens an earlier contact grant. A former company reads
* contacts again only after a new invitation and a new C4. The notice is
* absent while the card is published and for a card that was never published.
*/
export function describePublicationClosure(
publication: Pick<Publication, "state" | "closed_reason">,
): PublicationClosureNotice | null {
if (publication.state === "published") return null;
if (publication.closed_reason === "consent_revoked") {
return {
title: "Согласие C2 отозвано, карточка закрыта",
points: [
"Будущие чтения карточки компаниями закрыты сразу, без ожидания обновления поиска.",
"Новое согласие C2 не откроет карточку само: выберите поля и включите публикацию отдельным действием.",
"Прежний доступ к контактам не возвращается. Компании, которая уже получала контакты, нужны новое приглашение и новое согласие C4.",
],
};
}
if (publication.closed_reason === "closed_by_candidate") {
return {
title: "Вы закрыли карточку",
points: [
"Будущие чтения карточки компаниями закрыты.",
"Повторная публикация не восстанавливает прежний доступ к контактам: компании, которая уже получала контакты, нужны новое приглашение и новое согласие C4.",
],
};
}
return null;
}
/** Wording about contact access that follows a hide, an unhide or a republish. */
export const contactAccessAfterVisibilityChange =
"Скрытие закрывает будущие чтения этой компании. Снятие скрытия и повторная публикация не восстанавливают прежний доступ к контактам: бывшей компании нужны новое приглашение и новое согласие C4.";
export function describeAccessOrganization(organization: { name: string } | null): string {
return organization ? organization.name : "Организация не раскрывается";
}
@@ -0,0 +1,123 @@
.preview {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.alias {
margin: 0;
font-size: 1.05rem;
overflow-wrap: anywhere;
}
.note,
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: 0.925rem;
line-height: 1.55;
}
.hint {
margin-block-start: var(--space-3);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-4);
}
.grid section {
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.grid h3 {
margin: 0 0 var(--space-3);
font-size: 1rem;
}
.grid p {
margin: 0;
}
.grid .hint {
margin-block-start: var(--space-3);
}
.list {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
/* A declared grade and a confirmed grade differ by mark shape and text, not by color. */
.assessment,
.evidence {
display: grid;
gap: 0.3rem;
min-width: 0;
padding-block-end: var(--space-3);
border-block-end: var(--line-thin) solid var(--color-divider);
}
.list > li:last-child {
padding-block-end: 0;
border-block-end: 0;
}
.assessment-name {
overflow-wrap: anywhere;
}
.declared {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.evidence-facts,
.facts {
display: grid;
grid-template-columns: minmax(7.5rem, auto) minmax(0, 1fr);
gap: 0.35rem 1rem;
margin: 0;
}
.evidence-facts dt,
.facts dt {
color: var(--color-text-secondary);
}
.evidence-facts dd,
.facts dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.facts {
grid-template-columns: minmax(9rem, auto) minmax(0, 1fr);
}
@media (width < 48rem) {
.grid {
grid-template-columns: minmax(0, 1fr);
}
.evidence-facts,
.facts {
grid-template-columns: minmax(0, 1fr);
gap: 0.25rem;
}
.evidence-facts dd + dt,
.facts dd + dt {
margin-block-start: 0.6rem;
}
}
@@ -0,0 +1,148 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import type { CardPreview } from "../../../shared/api/schemas";
import { EmployerCardPreview } from "./employer-card-preview";
const pseudonym = `cv1_${"a".repeat(43)}`;
function published(overrides: Partial<CardPreview> = {}): CardPreview {
return {
state: "published",
fields: ["categories", "self_assessment"],
card: {
pseudonym,
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
stack: null,
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 },
],
experience_band: null,
work_formats: null,
salary_compatibility: null,
},
evidence: {
items: [
{
skill: "backend",
grade: "middle",
trust: 1,
basis: "synthetic_demo",
calibration_status: "uncalibrated",
observed_year: 2026,
},
],
},
generated_at: "2026-10-03T10:00:00Z",
...overrides,
};
}
function render(
preview: CardPreview | undefined,
extra: { isLoading?: boolean; error?: unknown } = {},
) {
return renderToStaticMarkup(
<EmployerCardPreview
preview={preview}
isLoading={extra.isLoading ?? false}
error={extra.error ?? null}
onRetry={vi.fn()}
/>,
);
}
describe("employer card preview", () => {
it("keeps the owner alias apart from organization aliases", () => {
const markup = render(published());
expect(markup).toContain("Предварительный псевдоним");
expect(markup).toContain(pseudonym);
expect(markup).toContain("Это отдельный псевдоним предпросмотра");
});
it("states the confirmation of each specialization separately", () => {
const markup = render(published());
expect(markup).toContain("Backend: Middle, стандартное подтверждение");
expect(markup.match(/Грейд подтвержден/g)).toHaveLength(1);
expect(markup.match(/Грейд не подтвержден/g)).toHaveLength(2);
expect(markup).toContain("Заявлено: Junior");
expect(markup).toContain("Уровень не указан");
// The mark of a confirmed grade and the mark of an unconfirmed one differ in markup.
expect(markup).toContain('data-level="confirmed"');
expect(markup).toContain('data-level="none"');
expect(markup).toContain("неудачные попытки компании не видят");
});
it("shows the unconfirmed state per specialization when no category exists", () => {
const markup = render(
published({
fields: ["self_assessment"],
card: {
pseudonym,
categories: null,
stack: null,
self_assessment: [
{
specialization: "backend",
confirmation_status: "unconfirmed",
declared_grade: "middle",
},
{
specialization: "network_engineer",
confirmation_status: "unconfirmed",
declared_grade: "junior",
},
],
experience_band: null,
work_formats: null,
salary_compatibility: null,
},
evidence: { items: [] },
}),
);
expect(markup).toContain("Подтвержденных категорий в карточке нет.");
expect(markup.match(/Грейд не подтвержден/g)).toHaveLength(2);
expect(markup).not.toContain("Грейд подтвержден");
expect(markup).toContain("Для опубликованных категорий нет видимого подтверждающего факта.");
});
it("labels the evidence basis and calibration the way the server states them", () => {
const markup = render(published());
expect(markup).toContain("Подтверждающие факты оценки");
expect(markup).toContain("Онлайн-результат без подтверждения личности");
expect(markup).toContain("Синтетическая демонстрация, не проверенное измерение");
expect(markup).toContain("Пороги не откалиброваны");
expect(markup).toContain("2026");
});
it("explains a closed card without offering to open it", () => {
const markup = render({
state: "closed",
fields: [],
card: null,
evidence: null,
generated_at: "2026-10-03T10:00:00Z",
});
expect(markup).toContain("Карточка закрыта");
expect(markup).toContain("Новый C2 не откроет ее автоматически");
expect(markup).not.toContain("Подтверждающие факты оценки");
});
it("renders the loading, error and missing states", () => {
expect(render(undefined, { isLoading: true })).toContain("Загружаем предварительный просмотр");
expect(render(undefined, { error: new Error("failed") })).toContain(
"Не удалось загрузить предварительный просмотр",
);
expect(render(undefined)).toContain("Предварительный просмотр пока недоступен");
});
});
@@ -0,0 +1,178 @@
import type { CardPreview } from "../../../shared/api/schemas";
import { EmptyState, ErrorState, LoadingState, TrustLevel } from "../../../shared/ui";
import {
presentCandidatePreview,
type CandidateViewPresentation,
type EvidencePresentation,
type SelfAssessmentPresentation,
} from "../model/presentation";
import styles from "./employer-card-preview.module.css";
type EmployerCardPreviewProps = {
preview: CardPreview | undefined;
isLoading: boolean;
error: unknown;
onRetry: () => void;
};
function SelfAssessmentItem({ item }: { item: SelfAssessmentPresentation }) {
return (
<li className={styles.assessment} data-confirmed={item.confirmed}>
<strong className={styles["assessment-name"]}>{item.specialization}</strong>
<span className={styles.declared}>
{item.declaredGrade ? `Заявлено: ${item.declaredGrade}` : "Уровень не указан"}
</span>
<TrustLevel level={item.confirmed ? "confirmed" : "none"} label={item.confirmation} />
</li>
);
}
function EvidenceItem({ item }: { item: EvidencePresentation }) {
return (
<li className={styles.evidence}>
<strong>{item.title}</strong>
<TrustLevel level={item.trust} label={item.trustLabel} />
<dl className={styles["evidence-facts"]}>
<dt>Год оценки</dt>
<dd>{item.observedYear}</dd>
<dt>Основа</dt>
<dd>{item.basisLabel}</dd>
<dt>Калибровка</dt>
<dd>{item.calibrationLabel}</dd>
</dl>
</li>
);
}
function OtherGroups({ card }: { card: CandidateViewPresentation }) {
const hasValues = card.stack || card.experience || card.workFormats || card.salaryCompatibility;
return (
<section aria-labelledby="preview-other-title">
<h3 id="preview-other-title">Другие выбранные группы</h3>
{hasValues ? (
<dl className={styles.facts}>
{card.stack ? (
<>
<dt>Технологии</dt>
<dd>{card.stack.join(", ") || "Нет данных"}</dd>
</>
) : null}
{card.experience ? (
<>
<dt>Общий опыт</dt>
<dd>{card.experience}</dd>
</>
) : null}
{card.workFormats ? (
<>
<dt>Форматы работы</dt>
<dd>{card.workFormats.join(", ") || "Нет данных"}</dd>
</>
) : null}
{card.salaryCompatibility ? (
<>
<dt>Совместимость ожиданий</dt>
<dd>{card.salaryCompatibility}</dd>
</>
) : null}
</dl>
) : (
<p>Другие группы не содержат значений.</p>
)}
</section>
);
}
/**
* The anonymous card the way the owner's private preview returns it. It shows
* each specialization on its own: a confirmed category and a declared grade
* that is still unconfirmed are never merged or ranked together, and the
* evidence block restates the basis and calibration the server reports.
*/
export function EmployerCardPreview({
preview,
isLoading,
error,
onRetry,
}: EmployerCardPreviewProps) {
if (isLoading && !preview) return <LoadingState label="Загружаем предварительный просмотр..." />;
if (error) {
return (
<ErrorState
error={error}
onRetry={onRetry}
title="Не удалось загрузить предварительный просмотр"
/>
);
}
if (!preview) return <EmptyState title="Предварительный просмотр пока недоступен" />;
const card = presentCandidatePreview(preview);
if (!card) {
return (
<EmptyState
title="Карточка закрыта"
description="Компании не видят карточку. Новый C2 не откроет ее автоматически: публикацию нужно включить отдельно."
/>
);
}
return (
<div className={styles.preview}>
<p className={styles.alias}>
Предварительный псевдоним: <strong>{card.pseudonym}</strong>
</p>
<p className={styles.note}>
Это отдельный псевдоним предпросмотра. В каждой организации используется свой псевдоним, а
ее фильтры и проверка размера группы могут дополнительно скрыть или обобщить данные.
</p>
<div className={styles.grid}>
<section aria-labelledby="preview-confirmed-title">
<h3 id="preview-confirmed-title">Подтвержденные категории</h3>
{card.categories?.length ? (
<ul className={styles.list}>
{card.categories.map((category) => (
<li key={`${category.specialization}-${category.grade}`}>
{category.specialization}: {category.grade}, {category.strength.toLowerCase()}
</li>
))}
</ul>
) : (
<p>Подтвержденных категорий в карточке нет.</p>
)}
</section>
<section aria-labelledby="preview-self-title">
<h3 id="preview-self-title">Самооценка по направлениям</h3>
{card.selfAssessments?.length ? (
<ul className={styles.list}>
{card.selfAssessments.map((item) => (
<SelfAssessmentItem key={item.specialization} item={item} />
))}
</ul>
) : (
<p>Самооценка не опубликована или отсутствует.</p>
)}
<p className={styles.hint}>
Статус подтверждения задается для каждой специализации отдельно. Причины его отсутствия
и неудачные попытки компании не видят.
</p>
</section>
{card.evidence ? (
<section aria-labelledby="preview-evidence-title">
<h3 id="preview-evidence-title">Подтверждающие факты оценки</h3>
{card.evidence.length > 0 ? (
<ul className={styles.list}>
{card.evidence.map((item) => (
<EvidenceItem key={item.title} item={item} />
))}
</ul>
) : (
<p>Для опубликованных категорий нет видимого подтверждающего факта.</p>
)}
</section>
) : null}
<OtherGroups card={card} />
</div>
</div>
);
}
@@ -1 +1,2 @@
export { ConsentManagement } from "./ui/consent-management";
export { consentPurposeAnchorId } from "./model/anchors";
@@ -0,0 +1,4 @@
/** Id of the block of one consent purpose, for links that move the reader to it. */
export function consentPurposeAnchorId(purpose: string): string {
return `consent-purpose-${purpose}`;
}
@@ -176,3 +176,7 @@
padding: var(--space-3);
}
}
.purpose-anchor {
scroll-margin-block-start: var(--space-4);
}
@@ -33,10 +33,21 @@ import {
groupOrganizationConsents,
} from "../../../entities/consent";
import type { OrganizationConsentGroup } from "../../../entities/consent";
import { consentPurposeAnchorId } from "../model/anchors";
import styles from "./consent-management.module.css";
const pageSize = 100;
const historyQueryKey = getListMyConsentsQueryKey({ limit: pageSize });
const noOrganizations: ReadonlySet<string> = new Set();
type ConsentManagementProps = {
/**
* Organizations the candidate currently hides the profile from. A C4 record
* of such an organization stays in the ledger, so the list says that it
* does not reopen contact access while the profile is hidden.
*/
hiddenOrganizationIds?: ReadonlySet<string>;
};
type ConsentAction =
| { kind: "account" }
@@ -71,7 +82,8 @@ function actionCopy(action: ConsentAction): {
acknowledgment:
"Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.",
button: "Подтвердить отзыв",
success: "Запрос на отзыв C4 обработан. Проверьте обновленное состояние ниже.",
success:
"Запрос на отзыв C4 обработан. Будущие чтения контактов этой компанией закрыты; для нового доступа нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже.",
};
}
@@ -80,7 +92,10 @@ function actionCopy(action: ConsentAction): {
description: consentPurposeDetails[action.purpose].consequence,
acknowledgment: `Я понимаю последствия отзыва C${action.purpose.slice(1)}.`,
button: "Подтвердить отзыв",
success: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
success:
action.purpose === "c2"
? "C2 отозвано. Карточка закрыта, будущие чтения компаниями закрыты. Новое согласие C2 карточку не откроет: публикацию нужно включить отдельно. Бывшей компании для контактов нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже."
: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
};
}
@@ -317,6 +332,7 @@ function ConsentGrantPanel({
function OrganizationConsent({
group,
records,
isHidden,
confirming,
accepted,
isBusy,
@@ -328,6 +344,7 @@ function OrganizationConsent({
}: {
group: OrganizationConsentGroup;
records: ConsentRecord[];
isHidden: boolean;
confirming: boolean;
accepted: boolean;
isBusy: boolean;
@@ -343,6 +360,12 @@ function OrganizationConsent({
return (
<article className={styles["organization-group"]}>
<h3 className={styles["record-title"]}>{group.displayName}</h3>
{isHidden ? (
<p className={styles.notice} role="status">
Профиль скрыт от этой компании. Запись C4 остается в журнале, но не возвращает доступ к
контактам: он закрыт до нового приглашения и нового согласия C4.
</p>
) : null}
<div className={styles["record-list"]}>
{records.map((record) => (
<ConsentRecordView key={record.id} record={record} />
@@ -368,7 +391,9 @@ function OrganizationConsent({
);
}
export function ConsentManagement() {
export function ConsentManagement({
hiddenOrganizationIds = noOrganizations,
}: ConsentManagementProps) {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const csrfToken = session.data?.csrf_token;
@@ -587,102 +612,109 @@ export function ConsentManagement() {
purpose === "c1" ? Boolean(activeRecord) : Boolean(activeRecord && action);
return (
<Section
<div
key={purpose}
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
description={consentPurposeDetails[purpose].consequence}
id={consentPurposeAnchorId(purpose)}
className={styles["purpose-anchor"]}
tabIndex={-1}
>
{purpose === "c4" ? (
c4Groups.length > 0 ? (
<div className={styles["organization-list"]}>
{c4Groups.map((group) => (
<OrganizationConsent
key={group.organizationId}
group={group}
records={group.records}
confirming={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId
}
accepted={acceptedConfirmation}
isBusy={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId &&
revokeOrganization.isPending
}
isReady={canConfirm}
onBegin={() =>
beginConfirmation({
kind: "organization",
organizationId: group.organizationId,
})
}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
))}
</div>
) : (
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)
) : (
<>
{purposeRecords.length > 0 ? (
<div className={styles["record-list"]}>
{purposeRecords.map((record) => (
<ConsentRecordView key={record.id} record={record} />
<Section
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
description={consentPurposeDetails[purpose].consequence}
>
{purpose === "c4" ? (
c4Groups.length > 0 ? (
<div className={styles["organization-list"]}>
{c4Groups.map((group) => (
<OrganizationConsent
key={group.organizationId}
group={group}
records={group.records}
isHidden={hiddenOrganizationIds.has(group.organizationId)}
confirming={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId
}
accepted={acceptedConfirmation}
isBusy={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId &&
revokeOrganization.isPending
}
isReady={canConfirm}
onBegin={() =>
beginConfirmation({
kind: "organization",
organizationId: group.organizationId,
})
}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
))}
</div>
) : (
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)}
{canRevoke && action && !isConfirmingPurpose ? (
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
{purpose === "c1"
? "Отозвать C1 и запросить удаление"
: `Отозвать C${purpose.slice(1)}`}
</Button>
) : null}
{canRevoke && action && isConfirmingPurpose ? (
<ActionConfirmation
action={action}
accepted={acceptedConfirmation}
isBusy={purpose === "c1" ? deleteAccount.isPending : revoke.isPending}
isReady={canConfirm}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
) : null}
<div className={styles["grant-actions"]}>
{grantPurpose === purpose ? (
<ConsentGrantPanel
key={purpose}
purpose={purpose}
activeRecord={activeRecord}
csrfToken={canMutate ? csrfToken : undefined}
isSubmitting={grant.isPending}
onCancel={() => setGrantPurpose(null)}
onGrant={submitGrant}
/>
)
) : (
<>
{purposeRecords.length > 0 ? (
<div className={styles["record-list"]}>
{purposeRecords.map((record) => (
<ConsentRecordView key={record.id} record={record} />
))}
</div>
) : (
<Button
variant="quiet"
aria-expanded={grantPurpose === purpose}
onClick={() => {
setStatusMessage(null);
setActionError(null);
setGrantPurpose(purpose);
}}
>
Прочитать текущий текст C{purpose.slice(1)}
</Button>
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)}
</div>
</>
)}
</Section>
{canRevoke && action && !isConfirmingPurpose ? (
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
{purpose === "c1"
? "Отозвать C1 и запросить удаление"
: `Отозвать C${purpose.slice(1)}`}
</Button>
) : null}
{canRevoke && action && isConfirmingPurpose ? (
<ActionConfirmation
action={action}
accepted={acceptedConfirmation}
isBusy={purpose === "c1" ? deleteAccount.isPending : revoke.isPending}
isReady={canConfirm}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
) : null}
<div className={styles["grant-actions"]}>
{grantPurpose === purpose ? (
<ConsentGrantPanel
key={purpose}
purpose={purpose}
activeRecord={activeRecord}
csrfToken={canMutate ? csrfToken : undefined}
isSubmitting={grant.isPending}
onCancel={() => setGrantPurpose(null)}
onGrant={submitGrant}
/>
) : (
<Button
variant="quiet"
aria-expanded={grantPurpose === purpose}
onClick={() => {
setStatusMessage(null);
setActionError(null);
setGrantPurpose(purpose);
}}
>
Прочитать текущий текст C{purpose.slice(1)}
</Button>
)}
</div>
</>
)}
</Section>
</div>
);
})}
</div>
@@ -72,6 +72,56 @@
border-inline-start-color: var(--color-danger);
}
.step {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
/* The state is stated in text; the stronger edge only repeats it for sighted users. */
.step[data-c2-state="inactive"] {
border-inline-start: var(--line-strong) solid var(--color-danger);
}
.step[data-c2-state="active"] {
border-inline-start: var(--line-strong) solid var(--color-accent);
}
.step-title {
margin: 0;
font-size: 1rem;
}
.step-text {
margin: 0;
overflow-wrap: anywhere;
}
.closure {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.closure-title {
margin: 0;
font-weight: var(--font-weight-bold);
}
.closure ul {
display: grid;
gap: var(--space-1);
margin: 0;
padding-inline-start: 1.25rem;
overflow-wrap: anywhere;
}
.actions {
display: flex;
flex-wrap: wrap;
@@ -39,6 +39,7 @@ describe("profile visibility controls", () => {
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
const search = renderToStaticMarkup(
@@ -51,7 +52,8 @@ describe("profile visibility controls", () => {
/>,
);
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2 ниже.");
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2");
expect(publication).toContain("Перейти к согласию C2");
expect(publication).toContain("Подтвержденная категория и уровень");
expect(publication).toContain("Самооценка по направлениям");
expect(publication).toContain('aria-disabled="true"');
@@ -77,6 +79,7 @@ describe("profile visibility controls", () => {
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
@@ -85,3 +88,58 @@ describe("profile visibility controls", () => {
expect(markup).toContain("Загрузить актуальные настройки");
});
});
describe("publication closure notice", () => {
const closedByRevocation: PrivacySettings = {
...settings,
publication: {
state: "closed",
closed_reason: "consent_revoked",
fields: [],
consent_id: "00000000-0000-4000-8000-000000000002",
published_at: "2026-10-02T00:00:00Z",
version: 3,
},
};
function render(value: PrivacySettings, c2State: "active" | "inactive") {
return renderToStaticMarkup(
<PublicationControls
settings={value}
c2State={c2State}
draft={{ state: "closed", fields: [], expectedVersion: value.publication.version }}
isDirty={false}
isStale={false}
hasUnsupportedFields={false}
canSave={false}
isSaving={false}
message={null}
error={null}
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
}
it("explains closed future reads and a new C4 after a revocation", () => {
const markup = render(closedByRevocation, "inactive");
expect(markup).toContain("Согласие C2 отозвано, карточка закрыта");
expect(markup).toContain("Будущие чтения карточки компаниями закрыты");
expect(markup).toContain("новое приглашение и новое согласие C4");
});
it("keeps a fresh C2 apart from the publication that it never reopens", () => {
const markup = render(closedByRevocation, "active");
expect(markup).toContain("Согласие C2 действует. Оно само по себе не включает публикацию.");
expect(markup).toContain("Новое согласие C2 не откроет карточку само");
expect(markup).not.toContain("Перейти к согласию C2");
});
it("shows no closure notice for a card that was never published", () => {
expect(render(settings, "inactive")).not.toContain("карточка закрыта");
});
});
@@ -1,6 +1,7 @@
import { useId } from "react";
import {
cardFieldLabels,
describePublicationClosure,
publishableCardFields,
type C2State,
type PublicationDraft,
@@ -23,8 +24,17 @@ type PublicationControlsProps = {
onDraftChange: (draft: PublicationDraft) => void;
onSave: () => void;
onReload: () => void;
/** Moves the reader to the C2 consent block. It never grants anything. */
onOpenConsent: () => void;
};
const c2StepText = {
active: "Согласие C2 действует. Оно само по себе не включает публикацию.",
checking: "Проверяем полную историю согласий C2. До завершения публикация недоступна.",
inactive:
"Для публикации сначала отдельно примите согласие C2 в блоке «C2. Публикация карточки кандидата» выше.",
} as const satisfies Record<C2State, string>;
export function PublicationControls({
settings,
c2State,
@@ -39,10 +49,12 @@ export function PublicationControls({
onDraftChange,
onSave,
onReload,
onOpenConsent,
}: PublicationControlsProps) {
const stateId = useId();
const fieldsId = useId();
const c2Id = useId();
const closure = describePublicationClosure(settings.publication);
function toggleField(field: PublicationDraft["fields"][number], checked: boolean) {
const next = checked
@@ -63,8 +75,33 @@ export function PublicationControls({
Текущее состояние:{" "}
{settings.publication.state === "published" ? "опубликована" : "закрыта"}.
</p>
{closure ? (
<div className={styles.closure} role="status">
<p className={styles["closure-title"]}>{closure.title}</p>
<ul>
{closure.points.map((point) => (
<li key={point}>{point}</li>
))}
</ul>
</div>
) : null}
<div className={styles.step} data-c2-state={c2State}>
<h3 className={styles["step-title"]}>Шаг 1. Согласие C2</h3>
<p id={c2Id} className={styles["step-text"]}>
{c2StepText[c2State]}
</p>
{c2State === "inactive" ? (
<div className={styles.actions}>
<Button variant="secondary" onClick={onOpenConsent}>
Перейти к согласию C2
</Button>
</div>
) : null}
</div>
<fieldset className={styles.group} aria-describedby={stateId}>
<legend>Состояние карточки</legend>
<legend>Шаг 2. Состояние карточки</legend>
<p id={stateId} className={styles.help}>
Закрытая карточка не доступна компаниям. Повторная публикация требует отдельного
действия.
@@ -94,7 +131,7 @@ export function PublicationControls({
</fieldset>
<fieldset className={styles.group} aria-describedby={fieldsId}>
<legend>Поля анонимной карточки</legend>
<legend>Шаг 3. Поля анонимной карточки</legend>
<p id={fieldsId} className={styles.help}>
Имя, контакты, работодатели и суммы зарплаты не публикуются. Подтвержденные категории и
самооценка показываются раздельно.
@@ -118,13 +155,6 @@ export function PublicationControls({
Выберите разрешенные поля или явно закройте публикацию.
</p>
) : null}
<p id={c2Id} className={styles.help}>
{c2State === "active"
? "Согласие C2 активно. Оно само по себе не включает публикацию."
: c2State === "checking"
? "Проверяем полную историю согласий C2. До завершения публикация недоступна."
: "Для публикации сначала отдельно примите согласие C2 ниже."}
</p>
{isStale ? (
<div className={styles.error} role="alert">
Настройки изменились на сервере. Ваш черновик сохранен на экране. Загрузите актуальные
-1
View File
@@ -1 +0,0 @@
export { ConsentsPage } from "./ui/consents-page";
@@ -1,25 +0,0 @@
import { ConsentManagement } from "../../../features/consent-management";
import { paths } from "../../../shared/config";
import { ButtonLink, Page, Section } from "../../../shared/ui";
export function ConsentsPage() {
return (
<Page
title="Согласия и настройки приватности"
eyebrow="Кабинет кандидата"
lead="Здесь можно проверить историю каждого согласия и отдельно изменить его состояние."
width="wide"
>
<ConsentManagement />
<Section title="Ручная оценка">
<p>
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
автоматическую оценку. Запрос не включает согласие обратно.
</p>
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
Запросить ручную оценку
</ButtonLink>
</Section>
</Page>
);
}
@@ -1,12 +1,8 @@
.preview,
.organization-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-5);
}
.preview-alias {
margin: 0;
font-size: 1.05rem;
align-items: start;
}
.note {
@@ -16,13 +12,6 @@
line-height: 1.55;
}
.preview-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-4);
}
.preview-grid section,
.organization-columns section {
min-width: 0;
padding: var(--space-4);
@@ -31,39 +20,11 @@
background: var(--color-surface);
}
.preview-grid h3,
.organization-columns h3 {
margin: 0 0 var(--space-3);
font-size: 1rem;
}
.preview-grid ul {
margin: 0;
padding-inline-start: 1.25rem;
}
.preview-facts {
display: grid;
grid-template-columns: minmax(9rem, auto) minmax(0, 1fr);
gap: 0.45rem 1rem;
margin: 0;
}
.preview-facts dt {
color: var(--color-text-secondary);
}
.preview-facts dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.organization-columns {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
.organization-list,
.history-list {
display: grid;
@@ -110,10 +71,6 @@
overflow-wrap: anywhere;
}
.preview-grid li + li {
margin-block-start: 0.4rem;
}
.pagination {
display: grid;
justify-items: start;
@@ -139,17 +96,7 @@
}
@media (width < 48rem) {
.preview-grid,
.organization-columns {
grid-template-columns: minmax(0, 1fr);
}
.preview-facts {
grid-template-columns: minmax(0, 1fr);
gap: 0.25rem;
}
.preview-facts dd + dt {
margin-block-start: 0.75rem;
}
}
@@ -1,17 +1,7 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import type {
CardAccess,
CardPreview,
HiddenOrganization,
PrivacyEventList,
} from "../../../shared/api/schemas";
import {
CardAccessHistory,
OrganizationVisibility,
PrivacyHistory,
PrivacyPreview,
} from "./privacy-page";
import type { CardAccess, HiddenOrganization, PrivacyEventList } from "../../../shared/api/schemas";
import { CardAccessHistory, OrganizationVisibility, PrivacyHistory } from "./privacy-page";
const orgA = {
id: "00000000-0000-4000-8000-000000000001",
@@ -40,49 +30,56 @@ function hiddenOrganization(organization: typeof orgA): HiddenOrganization {
}
describe("privacy page sections", () => {
it("keeps the owner preview alias separate from organization aliases and category evidence", () => {
const preview: CardPreview = {
state: "published",
fields: ["categories", "self_assessment"],
card: {
pseudonym: `cv1_${"a".repeat(43)}`,
categories: [{ specialization: "backend", grade: "junior", strength: "standard" }],
stack: null,
self_assessment: [
{
specialization: "frontend",
confirmation_status: "unconfirmed",
declared_grade: "middle",
},
],
experience_band: null,
work_formats: null,
salary_compatibility: null,
},
evidence: {
items: [
{
skill: "backend",
grade: "junior",
trust: 1,
basis: "synthetic_demo",
calibration_status: "uncalibrated",
observed_year: 2026,
},
],
},
generated_at: "2026-10-03T10:00:00Z",
};
it("shows who read the card and when, within the permitted detail", () => {
const markup = renderToStaticMarkup(
<PrivacyPreview preview={preview} isLoading={false} error={null} onRetry={vi.fn()} />,
<CardAccessHistory
records={[
accessRecord("00000000-0000-4000-8000-000000000051", orgA, "contact_read"),
accessRecord("00000000-0000-4000-8000-000000000052", null),
]}
hiddenOrganizationIds={new Set([orgA.id])}
isLoading={false}
error={null}
hasMore={false}
isFetching={false}
onLoad={vi.fn()}
/>,
);
expect(markup).toContain("Предварительный псевдоним");
expect(markup).toContain("Это отдельный псевдоним предпросмотра");
expect(markup).toContain("Подтвержденные категории");
expect(markup).toContain("Backend: Junior");
expect(markup).toContain("Самооценка по направлениям");
expect(markup).toContain("Frontend: Middle; грейд не подтвержден");
expect(markup).toContain("Открыты контактные данные");
expect(markup).toContain("Просмотрена карточка профиля");
expect(markup).toContain("Компания А");
expect(markup).toContain('dateTime="2026-10-01T10:00:00Z"');
expect(markup).toContain("Организация не раскрывается");
expect(markup).toContain("Сейчас профиль скрыт от этой организации");
expect(markup).toContain("Сотрудники, запросы, фильтры и место в выдаче здесь не сохраняются");
expect(markup).toContain("Показана вся история");
});
it("shows an empty access history and an empty settings history", () => {
const access = renderToStaticMarkup(
<CardAccessHistory
records={[]}
isLoading={false}
error={null}
hasMore={false}
isFetching={false}
onLoad={vi.fn()}
/>,
);
const settings = renderToStaticMarkup(
<PrivacyHistory
events={[]}
isLoading={false}
error={null}
hasMore={false}
isFetching={false}
onLoad={vi.fn()}
/>,
);
expect(access).toContain("История доступа пока пуста");
expect(settings).toContain("История настроек пока пуста");
});
it("does not offer hide actions until the hidden list is fully loaded", () => {
@@ -114,7 +111,7 @@ describe("privacy page sections", () => {
"Список действий появится после загрузки всех страниц скрытых компаний",
);
expect(markup).not.toContain("Скрыть профиль</button>");
expect(markup).toContain("не восстанавливает C4");
expect(markup).toContain("не восстанавливают прежний доступ к контактам");
});
it("shows only organizations from access history as hide candidates", () => {
@@ -148,7 +145,7 @@ describe("privacy page sections", () => {
expect(markup).toContain("Компания Б");
expect(markup).toContain("Скрыть профиль");
expect(markup).toContain("Загрузить ранние записи");
expect(markup).toContain("Снятие скрытия само по себе не восстанавливает C4");
expect(markup).toContain("новое приглашение и новое согласие C4");
});
it("does not describe a partial history page as the complete history", () => {
+91 -164
View File
@@ -1,18 +1,20 @@
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { ConsentManagement } from "../../../features/consent-management";
import { ConsentManagement, consentPurposeAnchorId } from "../../../features/consent-management";
import { PublicationControls, SearchStatusControl } from "../../../features/profile-visibility";
import {
buildPublicationSubmission,
buildSearchStatusSubmission,
cardAccessLabels,
cardFieldLabels,
contactAccessAfterVisibilityChange,
currentC2State,
describeAccessOrganization,
EmployerCardPreview,
formatPrivacyDate,
hasUnsupportedPublishedFields,
isSamePublicationDraft,
organizationsAvailableToHide,
presentCandidatePreview,
privacyEventLabels,
publicationDraftFromSettings,
type OrganizationReference,
@@ -43,10 +45,10 @@ import {
setMySearchStatus,
unhideOrganization,
} from "../../../shared/api/endpoints/privacy/privacy";
import { paths } from "../../../shared/config";
import type { Session } from "../../../shared/api/schemas";
import type {
CardAccess,
CardPreview,
HiddenOrganization,
PrivacyEventList,
PrivacySettings,
@@ -54,6 +56,7 @@ import type {
import { ApiRequestError } from "../../../shared/api";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
@@ -65,6 +68,7 @@ import { candidateViewQueryKeys } from "../../../entities/candidate-view";
import styles from "./privacy-page.module.css";
const pageSize = 100;
const noOrganizations: ReadonlySet<string> = new Set();
const privateQueryOptions = {
gcTime: 0,
staleTime: 0,
@@ -146,114 +150,6 @@ function useConsentHistoryReady(
return useSyncExternalStore(subscribe, getSnapshot, () => false);
}
export function PrivacyPreview({
preview,
isLoading,
error,
onRetry,
}: {
preview: CardPreview | undefined;
isLoading: boolean;
error: unknown;
onRetry: () => void;
}) {
if (isLoading && !preview) return <LoadingState label="Загружаем предварительный просмотр..." />;
if (error)
return (
<ErrorState
error={error}
onRetry={onRetry}
title="Не удалось загрузить предварительный просмотр"
/>
);
if (!preview) return <EmptyState title="Предварительный просмотр пока недоступен" />;
const card = presentCandidatePreview(preview);
if (!card) {
return (
<EmptyState
title="Карточка закрыта"
description="Компании не видят карточку. Новый C2 не откроет ее автоматически: публикацию нужно включить отдельно."
/>
);
}
return (
<div className={styles.preview}>
<p className={styles["preview-alias"]}>
Предварительный псевдоним: <strong>{card.pseudonym}</strong>
</p>
<p className={styles.note}>
Это отдельный псевдоним предпросмотра. В каждой организации используется свой псевдоним, а
ее фильтры и проверка размера группы могут дополнительно скрыть или обобщить данные.
</p>
<div className={styles["preview-grid"]}>
<section aria-labelledby="preview-confirmed-title">
<h3 id="preview-confirmed-title">Подтвержденные категории</h3>
{card.categories?.length ? (
<ul>
{card.categories.map((category) => (
<li key={`${category.specialization}-${category.grade}`}>
{category.specialization}: {category.grade}, {category.strength.toLowerCase()}
</li>
))}
</ul>
) : (
<p>Подтвержденных категорий пока нет.</p>
)}
</section>
<section aria-labelledby="preview-self-title">
<h3 id="preview-self-title">Самооценка по направлениям</h3>
{card.selfAssessments?.length ? (
<ul>
{card.selfAssessments.map((item) => (
<li key={item.specialization}>
{item.specialization}: {item.declaredGrade ?? "уровень не указан"};{" "}
{item.confirmation.toLowerCase()}
</li>
))}
</ul>
) : (
<p>Самооценка не опубликована или отсутствует.</p>
)}
</section>
<section aria-labelledby="preview-other-title">
<h3 id="preview-other-title">Другие выбранные группы</h3>
<dl className={styles["preview-facts"]}>
{card.stack ? (
<>
<dt>Технологии</dt>
<dd>{card.stack.join(", ") || "Нет данных"}</dd>
</>
) : null}
{card.experience ? (
<>
<dt>Общий опыт</dt>
<dd>{card.experience}</dd>
</>
) : null}
{card.workFormats ? (
<>
<dt>Форматы работы</dt>
<dd>{card.workFormats.join(", ") || "Нет данных"}</dd>
</>
) : null}
{card.salaryCompatibility ? (
<>
<dt>Совместимость ожиданий</dt>
<dd>{card.salaryCompatibility}</dd>
</>
) : null}
{!card.stack && !card.experience && !card.workFormats && !card.salaryCompatibility ? (
<dt>Другие группы не содержат значений.</dt>
) : null}
</dl>
</section>
</div>
</div>
);
}
function PaginationControl({
isLoaded,
hasMore,
@@ -404,11 +300,7 @@ export function OrganizationVisibility({
/>
</section>
</div>
<p className={styles.note}>
Скрытие закрывает будущие чтения этой организации и закрывает действующий контактный доступ
в рамках серверной политики. Снятие скрытия само по себе не восстанавливает C4 или доступ к
контактам: для нового доступа потребуется отдельное действующее согласие.
</p>
<p className={styles.note}>{contactAccessAfterVisibilityChange}</p>
{actionError ? (
<div className={styles.error} role="alert">
{actionError}
@@ -485,6 +377,7 @@ export function PrivacyHistory({
export function CardAccessHistory({
records,
hiddenOrganizationIds = noOrganizations,
isLoading,
error,
hasMore,
@@ -492,6 +385,7 @@ export function CardAccessHistory({
onLoad,
}: {
records: readonly CardAccess[];
hiddenOrganizationIds?: ReadonlySet<string>;
isLoading: boolean;
error: unknown;
hasMore: boolean;
@@ -501,7 +395,7 @@ export function CardAccessHistory({
return (
<Section
title="История доступа к карточке"
description="Здесь нет запросов, фильтров, ранжирования или имен сотрудников компаний."
description="Для каждого обращения показаны его вид, время и организация, если ее можно назвать. Сотрудники, запросы, фильтры и место в выдаче здесь не сохраняются."
>
{isLoading && records.length === 0 ? (
<LoadingState label="Загружаем историю доступа..." />
@@ -515,7 +409,10 @@ export function CardAccessHistory({
<li key={record.id}>
<strong>{cardAccessLabels[record.kind]}</strong>
<time dateTime={record.occurred_at}>{formatPrivacyDate(record.occurred_at)}</time>
<span>{record.organization?.name ?? "Компания недоступна"}</span>
<span>{describeAccessOrganization(record.organization)}</span>
{record.organization && hiddenOrganizationIds.has(record.organization.id) ? (
<span>Сейчас профиль скрыт от этой организации</span>
) : null}
</li>
))}
</ol>
@@ -546,7 +443,8 @@ export function PrivacyPage() {
null,
);
const previousActorId = useRef<string | null>(null);
const previousC2State = useRef<ReturnType<typeof currentC2State>>("checking");
// The last C2 state that was not "checking", so a refetch in between cannot hide a revocation.
const settledC2State = useRef<ReturnType<typeof currentC2State>>("checking");
const handleAuthorizationFailure = useCallback(
(error: unknown, expected: Session) => {
@@ -585,6 +483,7 @@ export function PrivacyPage() {
queryClient.removeQueries({ queryKey: candidateViewQueryKeys.actor(previous) });
queryClient.removeQueries({ queryKey: candidateViewQueryKeys.activeConsents(previous) });
setDraftState(null);
settledC2State.current = "checking";
setPrivateAccessLost(false);
setActionError(null);
setActionMessage(null);
@@ -710,14 +609,19 @@ export function PrivacyPage() {
() => hiddenOrganizationsQuery.data?.pages.flatMap((page) => page.items) ?? [],
[hiddenOrganizationsQuery.data],
);
const hiddenOrganizationIds = useMemo(
() => new Set(hiddenOrganizations.map((entry) => entry.organization.id)),
[hiddenOrganizations],
);
const privacyEvents = useMemo(
() => privacyHistory.data?.pages.flatMap((page) => page.items) ?? [],
[privacyHistory.data],
);
useEffect(() => {
const previous = previousC2State.current;
previousC2State.current = c2State;
if (c2State === "checking") return;
const previous = settledC2State.current;
settledC2State.current = c2State;
if (previous !== "active" || c2State !== "inactive" || !actor) return;
queryClient.removeQueries({ queryKey: previewKey });
@@ -817,6 +721,14 @@ export function PrivacyPage() {
);
}
// Moves focus to the C2 block; granting stays a separate, explicit action there.
function openConsentBlock(): void {
const block = document.getElementById(consentPurposeAnchorId("c2"));
if (!block) return;
block.focus();
block.scrollIntoView({ block: "start" });
}
async function reloadPublicationSettings(): Promise<void> {
if (!actor || !isCurrentCandidateSession(queryClient, actor)) return;
setFeedbackScope("publication");
@@ -866,7 +778,7 @@ export function PrivacyPage() {
(currentActor) =>
hideOrganization(organization.id, { headers: { "X-CSRF-Token": currentActor.csrf_token } }),
undefined,
`Профиль скрыт от компании «${organization.name}». Сервер закрывает действующий доступ к контактам.`,
`Профиль скрыт от компании «${organization.name}». Ее будущие чтения карточки закрыты. Если компания уже получала контакты, новый доступ возможен только после нового приглашения и нового согласия C4.`,
);
}
@@ -883,7 +795,7 @@ export function PrivacyPage() {
headers: { "X-CSRF-Token": currentActor.csrf_token },
}),
undefined,
`Скрытие компании «${organization.name}» снято. Действующий C4 не восстанавливается.`,
`Скрытие компании «${organization.name}» снято. Она читает карточку только пока публикация включена. Прежний доступ к контактам не восстановлен: нужны новое приглашение и новое согласие C4.`,
);
}
@@ -898,8 +810,9 @@ export function PrivacyPage() {
</Page>
);
}
if (session.isPending || session.isFetching)
return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
// A background session refetch (for example after a rejected consent action) must not unmount
// the page and its error message; the queries below pause while the session is refetched.
if (session.isPending) return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
if (session.data?.account.scenario !== "candidate") {
return (
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
@@ -938,52 +851,54 @@ export function PrivacyPage() {
lead="Согласие, публикация карточки, статус поиска и скрытие от компаний - отдельные настройки. Ни одно действие не включает другое автоматически."
>
{canShowConsentManagement ? (
<ConsentManagement key={actorId} />
<>
<Section
title="Согласия и настройки приватности"
description="Каждое согласие хранится и отзывается отдельно. Выдача или отзыв одного не меняет другие, а C2 не включает публикацию без отдельного сохранения ниже."
/>
<ConsentManagement key={actorId} hiddenOrganizationIds={hiddenOrganizationIds} />
</>
) : (
<Section
title="Согласия"
title="Согласия и настройки приватности"
description="Очищаем прежнюю приватную историю перед загрузкой текущего аккаунта."
>
<LoadingState label="Подготавливаем историю согласий..." />
</Section>
)}
<Section
title="Проверка согласия C2"
description="Для публикации проверяется действующая запись C2 из серверной истории согласий. Неизвестное состояние не считается согласием."
>
{c2State === "active" ? (
<p role="status">
Действующее согласие C2 найдено. Публикация все равно требует отдельного сохранения.
</p>
) : c2State === "inactive" ? (
<p role="status">Проверена вся активная история: действующего C2 нет.</p>
) : activeConsents.isError ? (
<ErrorState
error={activeConsents.error}
onRetry={() => void activeConsents.refetch()}
title="Не удалось проверить согласие C2"
/>
) : activeConsents.isPending ? (
<LoadingState label="Проверяем активные согласия..." />
) : (
<p role="status">
Полная история активных согласий еще не загружена. Отсутствие C2 на текущей странице не
означает, что его нет.
</p>
)}
{activeConsents.hasNextPage ? (
<Button
variant="secondary"
isBusy={activeConsents.isFetchingNextPage}
onClick={() => void activeConsents.fetchNextPage()}
>
{activeConsents.isFetchingNextPage
? "Проверяем историю..."
: "Проверить следующую страницу активных согласий"}
</Button>
) : null}
</Section>
{c2State === "checking" ? (
<Section
title="Проверка согласия C2"
description="Для публикации проверяется действующая запись C2 из серверной истории согласий. Неизвестное состояние не считается согласием."
>
{activeConsents.isError ? (
<ErrorState
error={activeConsents.error}
onRetry={() => void activeConsents.refetch()}
title="Не удалось проверить согласие C2"
/>
) : activeConsents.isPending ? (
<LoadingState label="Проверяем активные согласия..." />
) : (
<p role="status">
Полная история активных согласий еще не загружена. Отсутствие C2 на текущей странице
не означает, что его нет.
</p>
)}
{activeConsents.hasNextPage ? (
<Button
variant="secondary"
isBusy={activeConsents.isFetchingNextPage}
onClick={() => void activeConsents.fetchNextPage()}
>
{activeConsents.isFetchingNextPage
? "Проверяем историю..."
: "Проверить следующую страницу активных согласий"}
</Button>
) : null}
</Section>
) : null}
<PublicationControls
settings={settings}
@@ -1001,6 +916,7 @@ export function PrivacyPage() {
}}
onSave={() => void savePublication()}
onReload={() => void reloadPublicationSettings()}
onOpenConsent={openConsentBlock}
/>
<SearchStatusControl
@@ -1015,7 +931,7 @@ export function PrivacyPage() {
title="Предварительный просмотр карточки"
description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации."
>
<PrivacyPreview
<EmployerCardPreview
preview={previewQuery.data}
isLoading={previewQuery.isPending || previewQuery.isFetching}
error={previewQuery.error}
@@ -1054,12 +970,23 @@ export function PrivacyPage() {
<CardAccessHistory
records={accessRecords}
hiddenOrganizationIds={hiddenOrganizationIds}
isLoading={accessHistory.isPending}
error={accessHistory.error}
hasMore={Boolean(accessHistory.hasNextPage)}
isFetching={accessHistory.isFetchingNextPage}
onLoad={() => void accessHistory.fetchNextPage()}
/>
<Section title="Ручная оценка">
<p>
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
автоматическую оценку. Запрос не включает согласие обратно.
</p>
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
Запросить ручную оценку
</ButtonLink>
</Section>
</Page>
);
}
+33 -18
View File
@@ -1,5 +1,5 @@
import { faker } from "@faker-js/faker";
import { describe, expect, it } from "vitest";
import { beforeAll, describe, expect, it } from "vitest";
import type { ZodType } from "zod";
import { fakeFromPattern, type PatternLengthBounds } from "./mock-pattern";
import * as schemas from "./schemas";
@@ -11,7 +11,12 @@ import * as schemas from "./schemas";
// discovered from the generated files, so a new operation is covered without
// editing this test.
// A fixed, bounded set of seeds keeps every run identical. Generating and
// validating the large union mocks takes seconds on a loaded machine, so the
// default 5 s limit of a test would fail on speed, not on an invalid mock.
const seeds = Array.from({ length: 25 }, (_, index) => index + 1);
const mockCaseTimeoutMs = 60_000;
const fixedReferenceDate = new Date("2026-10-09T12:00:00Z");
const mockModules = import.meta.glob<Record<string, unknown>>("./endpoints/*/*.msw.ts", {
eager: true,
@@ -95,6 +100,12 @@ function describeValue(value: unknown): string {
const cases = discoverCases();
describe("generated MSW response mocks", () => {
// Date generators are relative to the current time unless a reference date
// is set, which would make a run depend on the moment it starts.
beforeAll(() => {
faker.setDefaultRefDate(fixedReferenceDate);
});
it("discovers a response factory for every generated mock module", () => {
expect(Object.keys(mockModules).length).toBeGreaterThan(0);
const covered = new Set(cases.map((item) => item.file));
@@ -111,24 +122,28 @@ describe("generated MSW response mocks", () => {
).toBe(true);
});
it.each(cases)("$factoryName returns a valid $schemaName", ({ factory, schema }) => {
const failures: string[] = [];
for (const seed of seeds) {
faker.seed(seed);
const mock = factory();
const result = schema.safeParse(mock);
if (result.success) {
continue;
it.each(cases)(
"$factoryName returns a valid $schemaName",
({ factory, schema }) => {
const failures: string[] = [];
for (const seed of seeds) {
faker.seed(seed);
const mock = factory();
const result = schema.safeParse(mock);
if (result.success) {
continue;
}
for (const issue of result.error.issues) {
const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
failures.push(
`seed ${seed}: ${path}: ${issue.message}; value ${describeValue(valueAt(mock, issue.path))}`,
);
}
}
for (const issue of result.error.issues) {
const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
failures.push(
`seed ${seed}: ${path}: ${issue.message}; value ${describeValue(valueAt(mock, issue.path))}`,
);
}
}
expect(failures).toEqual([]);
});
expect(failures).toEqual([]);
},
mockCaseTimeoutMs,
);
});
describe("fakeFromPattern", () => {