diff --git a/backend/Dockerfile.e2e b/backend/Dockerfile.e2e index 92a7146..c3758f2 100644 --- a/backend/Dockerfile.e2e +++ b/backend/Dockerfile.e2e @@ -1,4 +1,4 @@ -# This image is for local registration E2E only. The release path uses +# This image is for local browser E2E only. The release path uses # Dockerfile and never enables the e2e Go build tag. ARG GO_IMAGE=golang:1.26.8-alpine ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot @@ -13,6 +13,7 @@ RUN go mod download COPY . ./ RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/consent-fixture ./cmd/consent-fixture FROM ${RUNTIME_IMAGE} @@ -21,6 +22,7 @@ LABEL org.opencontainers.image.title="Lincodex local E2E backend" \ WORKDIR / COPY --from=build /out/app /app +COPY --from=build /out/consent-fixture /consent-fixture EXPOSE 8080 9090 USER nonroot:nonroot ENTRYPOINT ["/app"] diff --git a/backend/cmd/consent-fixture/main.go b/backend/cmd/consent-fixture/main.go new file mode 100644 index 0000000..cf5d38b --- /dev/null +++ b/backend/cmd/consent-fixture/main.go @@ -0,0 +1,292 @@ +//go:build e2e + +package main + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "os" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" +) + +const ( + fixtureGuardName = "E2E_CONSENT_FIXTURE" + fixtureEmail = "consent-browser@example.test" + fixturePassword = "browser consent fixture 2026" + firstOwnerEmail = "consent-owner-one@example.test" + secondOwnerEmail = "consent-owner-two@example.test" + fixtureTimeout = 90 * time.Second +) + +func main() { + if err := run(); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Fprintln(os.Stdout, "Consent browser fixture seeded.") +} + +func run() error { + if os.Getenv(fixtureGuardName) != "1" { + return errors.New("consent fixture requires the isolated e2e environment") + } + if len(os.Args) != 1 { + return errors.New("consent fixture accepts no arguments") + } + databaseURL := os.Getenv("DATABASE_URL") + if databaseURL == "" { + return errors.New("consent fixture database is not configured") + } + + ctx, cancel := context.WithTimeout(context.Background(), fixtureTimeout) + defer cancel() + + pool, err := postgres.NewSizedPool(ctx, databaseURL, 4) + if err != nil { + return errors.New("consent fixture could not open its database") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("consent fixture database is unavailable") + } + + hasher, err := argon2id.NewHasher(1) + if err != nil { + return errors.New("consent fixture password service is unavailable") + } + now := time.Now().UTC().Truncate(time.Microsecond) + users, err := newFixtureUsers(ctx, hasher, now) + if err != nil { + return errors.New("consent fixture accounts could not be prepared") + } + + transactor := postgres.NewTransactor(pool) + service := consent.NewService(transactor, func() time.Time { return now }) + if err := seedFixture(ctx, transactor, service, users, now); err != nil { + if errors.Is(err, outbound.ErrEmailTaken) { + return errors.New("consent fixture addresses already exist; the database must be fresh") + } + return errors.New("consent fixture could not be seeded") + } + return nil +} + +type fixtureUsers struct { + candidate domain.User + firstOwner domain.User + secondOwner domain.User +} + +func newFixtureUsers( + ctx context.Context, + hasher *argon2id.Hasher, + registeredAt time.Time, +) (fixtureUsers, error) { + candidate, err := newFixtureUser(ctx, hasher, fixtureEmail, fixturePassword, domain.ScenarioCandidate, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + firstOwner, err := newFixtureOwner(ctx, hasher, firstOwnerEmail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + secondOwner, err := newFixtureOwner(ctx, hasher, secondOwnerEmail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + return fixtureUsers{candidate: candidate, firstOwner: firstOwner, secondOwner: secondOwner}, nil +} + +func newFixtureOwner( + ctx context.Context, + hasher *argon2id.Hasher, + email string, + registeredAt time.Time, +) (domain.User, error) { + passwordBytes := make([]byte, 24) + if _, err := rand.Read(passwordBytes); err != nil { + return domain.User{}, errors.New("could not generate an isolated owner password") + } + rawPassword := base64.RawURLEncoding.EncodeToString(passwordBytes) + return newFixtureUser(ctx, hasher, email, rawPassword, domain.ScenarioEmployer, registeredAt) +} + +func newFixtureUser( + ctx context.Context, + hasher *argon2id.Hasher, + emailValue string, + passwordValue string, + scenario domain.Scenario, + registeredAt time.Time, +) (domain.User, error) { + email, err := domain.NewEmailAddress(emailValue) + if err != nil { + return domain.User{}, errors.New("fixture account email is invalid") + } + password, err := domain.NewPassword(passwordValue) + if err != nil { + return domain.User{}, errors.New("fixture account password is invalid") + } + passwordHash, err := hasher.Hash(ctx, password) + if err != nil { + return domain.User{}, errors.New("fixture account password could not be hashed") + } + user, err := domain.NewUser(domain.Registration{ + Email: email, + PasswordHash: passwordHash, + Scenario: scenario, + RegisteredAt: registeredAt, + }) + if err != nil { + return domain.User{}, errors.New("fixture account could not be built") + } + return user, nil +} + +func seedFixture( + ctx context.Context, + transactor outbound.Transactor, + service *consent.Service, + users fixtureUsers, + 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} { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + if _, err := unit.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now); err != nil { + return err + } + } + + firstOrganization, err := createOrganization( + ctx, + unit, + users.firstOwner.ID, + "Первая тестовая компания", + now, + ) + if err != nil { + return err + } + secondOrganization, err := createOrganization( + ctx, + unit, + users.secondOwner.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.candidate.ID, + users.candidate.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.candidate.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.candidate.ID, firstOrganization, c4Text.Version(), domain.ContactFieldEmail); err != nil { + return err + } + if err := grantFixtureContactConsent(ctx, service, unit, users.candidate.ID, secondOrganization, c4Text.Version(), domain.ContactFieldPhone); err != nil { + return err + } + return nil + }) +} + +func createOrganization( + ctx context.Context, + unit outbound.UnitOfWork, + ownerID uuid.UUID, + name string, + now time.Time, +) (domain.Organization, error) { + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: name}) + if err != nil { + return domain.Organization{}, err + } + organization, err := domain.NewOrganization(profile, now) + if err != nil { + return domain.Organization{}, err + } + owner, err := domain.NewOwnerMembership(organization.ID(), ownerID, now) + if err != nil { + return domain.Organization{}, err + } + if err := unit.Organizations().CreateWithOwner(ctx, organization, owner); err != nil { + return domain.Organization{}, err + } + return organization, nil +} + +func grantFixtureContactConsent( + ctx context.Context, + service *consent.Service, + unit outbound.UnitOfWork, + subjectID uuid.UUID, + organization domain.Organization, + textVersion domain.ConsentTextVersion, + field domain.ContactField, +) error { + fields, err := domain.NewContactFieldSet(field) + if err != nil { + return err + } + invitationID, err := uuid.NewV7() + if err != nil { + return err + } + // These synthetic invitation IDs exercise consent history and scoped revocation only. + // They are not evidence of the real invitation acceptance flow. + _, err = service.GrantContact(ctx, unit, consent.ContactGrantInput{ + SubjectID: subjectID, + OrganizationID: organization.ID(), + OrganizationName: organization.Profile().Name(), + Fields: fields, + InvitationID: invitationID, + InvitationTermsVersion: 1, + TextVersion: textVersion, + }) + if err != nil { + return err + } + return nil +} diff --git a/deploy/docker/docker-compose.e2e-mail.yml b/deploy/docker/docker-compose.e2e-mail.yml index da0928f..f76f5d5 100644 --- a/deploy/docker/docker-compose.e2e-mail.yml +++ b/deploy/docker/docker-compose.e2e-mail.yml @@ -12,6 +12,7 @@ services: RESEND_API_KEY: re_fixture_key # Keep real resend coverage bounded within this isolated test stand. VERIFICATION_MAIL_MIN_INTERVAL: 1s + E2E_CONSENT_FIXTURE: "1" depends_on: mail-fixture: condition: service_healthy @@ -23,6 +24,7 @@ services: E2E_MAILBOX_URL: http://mail-fixture:8025/__e2e/inbox E2E_MAILBOX_TOKEN: local-e2e-mailbox-token E2E_MAIL_FIXTURE: "1" + E2E_CONSENT_FIXTURE: "1" mail-fixture: build: diff --git a/deploy/scripts/e2e.sh b/deploy/scripts/e2e.sh index 248e598..858c4a7 100644 --- a/deploy/scripts/e2e.sh +++ b/deploy/scripts/e2e.sh @@ -260,6 +260,9 @@ try { printf '%s\n' 'The local mail fixture transport check failed.' >&2 exit 1 fi + # Seed only synthetic consent scopes in this fresh, isolated database. + # The command exists only in the local E2E image and rejects other modes. + compose exec -T backend /consent-fixture fi playwright_command=(node node_modules/@playwright/test/cli.js test) diff --git a/deploy/scripts/test_e2e_mail.py b/deploy/scripts/test_e2e_mail.py index 45167f6..d936667 100644 --- a/deploy/scripts/test_e2e_mail.py +++ b/deploy/scripts/test_e2e_mail.py @@ -99,6 +99,11 @@ class ComposeMailFixtureTest(unittest.TestCase): self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "disabled") self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1m") self.assertNotIn("RESEND_ENDPOINT", backend["environment"]) + self.assertNotIn("E2E_CONSENT_FIXTURE", backend["environment"]) + self.assertNotIn( + "E2E_CONSENT_FIXTURE", + rendered["services"]["playwright"].get("environment", {}), + ) self.assertNotIn( "E2E_MAIL_FIXTURE", rendered["services"]["playwright"].get("environment", {}), @@ -111,6 +116,7 @@ class ComposeMailFixtureTest(unittest.TestCase): self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "resend") self.assertEqual(backend["environment"]["RESEND_API_KEY"], "re_fixture_key") self.assertEqual(backend["environment"]["VERIFICATION_MAIL_MIN_INTERVAL"], "1s") + self.assertEqual(backend["environment"]["E2E_CONSENT_FIXTURE"], "1") self.assertNotIn("RESEND_ENDPOINT", backend["environment"]) self.assertEqual( services["playwright"]["environment"]["E2E_MAILBOX_URL"], @@ -118,6 +124,7 @@ class ComposeMailFixtureTest(unittest.TestCase): ) self.assertEqual(services["playwright"]["environment"]["E2E_MAILBOX_TOKEN"], FIXTURE_TOKEN) self.assertEqual(services["playwright"]["environment"]["E2E_MAIL_FIXTURE"], "1") + self.assertEqual(services["playwright"]["environment"]["E2E_CONSENT_FIXTURE"], "1") self.assertNotIn("E2E_MAIL_FIXTURE", services["frontend"].get("environment", {})) def test_fixture_has_no_host_port_storage_network_or_outbound_route(self): diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index b4fa96e..772cdb9 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -67,12 +67,14 @@ Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox`, and the synthetic `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. A test requests `GET $E2E_MAILBOX_URL?to=` with `Authorization: Bearer $E2E_MAILBOX_TOKEN`; the response contains `messages` with `id`, `to`, `subject`, `text`, and `html` fields. Registration-only tests should skip unless `E2E_MAIL_FIXTURE=1`, because neither ordinary `test-e2e` nor `release-e2e` sets it. Tests must not print message content or a link containing a one-time token. The runner disables Playwright tracing in this mode. The ordinary `test-e2e` still sets `EMAIL_PROVIDER=disabled`, and `release-e2e` uses release images without the fixture and records no evidence for a mail-fixture image. The registration mode refuses to run with `LINCODEX_RELEASE_TAG`. -The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data. +The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used. The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified. +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. + ## Release manifest tests `make -C deploy check-release` runs `deploy/scripts/test_release_manifest.py` with the Python standard library and without Docker. It fails when go.mod, the `GO_IMAGE` default, and `GOTOOLCHAIN=local` in backend/Dockerfile stop pinning Go 1.26.8, or when a service Dockerfile uses a base image that is not a pinnable `*_IMAGE` build argument, including an external image in `COPY --from` or `RUN --mount=from`. On fake image, Compose, and container data it checks that: diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 0b1121f..371e5ac 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -67,12 +67,14 @@ Deployment smoke проверяет инфраструктурные маршр Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox` и синтетический `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. Тест запрашивает `GET $E2E_MAILBOX_URL?to=` с `Authorization: Bearer $E2E_MAILBOX_TOKEN`; ответ содержит `messages` с полями `id`, `to`, `subject`, `text` и `html`. Registration-only tests должны пропускаться без `E2E_MAIL_FIXTURE=1`, поскольку стандартный `test-e2e` и `release-e2e` его не задают. Тесты не должны выводить содержимое письма или ссылку с одноразовым токеном. В этом режиме runner отключает трассировку Playwright. Обычный `test-e2e` по-прежнему задает `EMAIL_PROVIDER=disabled`, а `release-e2e` использует release-образы без fixture и не пишет evidence для mail-fixture образа. Режим отказывается запускаться с `LINCODEX_RELEASE_TAG`. -Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Будущие бизнес-тесты создают своих синтетических пользователей и записи через публичный API в свежем стеке каждого прогона; общие фикстуры и реальные данные не используются. +Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются. Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись. +В этом же режиме 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 не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные. + ## Тесты манифеста выпуска `make -C deploy check-release` запускает `deploy/scripts/test_release_manifest.py` на стандартной библиотеке Python и без Docker. Тест падает, если go.mod, значение `GO_IMAGE` по умолчанию и `GOTOOLCHAIN=local` в backend/Dockerfile перестают закреплять Go 1.26.8 или если Dockerfile сервиса использует базовый образ не через закрепляемый build-аргумент `*_IMAGE`, в том числе внешний образ в `COPY --from` или `RUN --mount=from`. На подставных данных образов, Compose и контейнеров он проверяет, что: diff --git a/frontend/e2e/consent-management.spec.ts b/frontend/e2e/consent-management.spec.ts new file mode 100644 index 0000000..0f3f60a --- /dev/null +++ b/frontend/e2e/consent-management.spec.ts @@ -0,0 +1,281 @@ +import { expect, test, type Locator, type Page, type Response } from "@playwright/test"; + +type ConsentRecord = { + id: string; + purpose: "c1" | "c2" | "c3" | "c4" | "c5"; + state: "active" | "superseded" | "revoked"; + text_version: string; + organization: { id: string; name: string } | null; + fields: ("full_name" | "email" | "phone" | "telegram")[] | null; +}; + +type ConsentList = { + items: ConsentRecord[]; + page: { has_more: boolean; next_cursor: string | null }; +}; + +const fixtureEnabled = process.env.E2E_CONSENT_FIXTURE === "1"; +const fixtureEmail = "consent-browser@example.test"; +const fixturePassword = "browser consent fixture 2026"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +function consentListResponse(response: { + url(): string; + request(): { method(): string }; +}): boolean { + return ( + new URL(response.url()).pathname === "/api/v1/me/consents" && + response.request().method() === "GET" + ); +} + +async function checkResponsiveKeyboardFlow(page: Page): Promise { + 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 hasVisibleKeyboardFocus = await page.evaluate(() => { + const active = document.activeElement; + if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false; + const style = getComputedStyle(active); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + const hasHorizontalOverflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(hasVisibleKeyboardFocus).toBe(true); + expect(hasHorizontalOverflow).toBe(false); + } +} + +async function focusByTab(page: Page, target: Locator): Promise { + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + for (let attempt = 0; attempt < 80; attempt += 1) { + await page.keyboard.press("Tab"); + if (await target.evaluate((element) => element === document.activeElement)) { + const hasVisibleFocus = await target.evaluate((element) => { + if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false; + const style = getComputedStyle(element); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + expect(hasVisibleFocus).toBe(true); + return; + } + } + throw new Error("Keyboard navigation did not reach the requested consent action."); +} + +async function readConsentList( + responseOrPromise: Response | Promise, +): Promise { + const response = await responseOrPromise; + expect(response.status()).toBe(200); + return (await response.json()) as ConsentList; +} + +test("candidate can review, revoke, and retain independent consent scopes", async ({ page }) => { + test.skip(!fixtureEnabled, "Requires the isolated synthetic consent fixture."); + + await page.goto("/login"); + await page.getByLabel("Электронная почта").fill(fixtureEmail); + await page.getByLabel("Пароль", { exact: true }).fill(fixturePassword); + const loginResponse = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.request().method() === "POST", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await loginResponse).status()).toBe(201); + + const firstListResponsePromise = page.waitForResponse(consentListResponse); + await page.goto("/candidate/privacy"); + const firstListResponse = await firstListResponsePromise; + const initial = await readConsentList(firstListResponse); + const activeC2 = initial.items.find( + (record) => record.purpose === "c2" && record.state === "active", + ); + const activeC4 = initial.items.filter( + (record) => record.purpose === "c4" && record.state === "active", + ); + expect(activeC2).toBeDefined(); + expect(activeC4).toHaveLength(2); + if (!activeC2) throw new Error("The consent fixture is missing active C2."); + expect(activeC4.map((record) => record.organization?.name).sort()).toEqual( + ["Вторая тестовая компания", "Первая тестовая компания"].sort(), + ); + + await expect( + page.getByRole("heading", { name: "Согласия и настройки приватности" }), + ).toBeVisible(); + await expect(page.getByText(`Версия ${activeC2.text_version}`)).toBeVisible(); + await expect(page.getByText("Первая тестовая компания").first()).toBeVisible(); + await expect(page.getByText("Вторая тестовая компания").first()).toBeVisible(); + await expect(page.getByText("Электронная почта", { exact: true })).toBeVisible(); + await expect(page.getByText("Телефон", { exact: true })).toBeVisible(); + await checkResponsiveKeyboardFlow(page); + + const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; + await page.setViewportSize({ width: 1280, height: 900 }); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + await page.screenshot({ + path: `${artifactsDirectory}/consent-history-candidate.png`, + animations: "disabled", + }); + + const c3TextResponse = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consent-texts/c3" && + response.request().method() === "GET", + ); + await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); + expect((await c3TextResponse).status()).toBe(200); + await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); + const c3Grant = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents/c3" && + response.request().method() === "PUT", + ); + const c3Refresh = page.waitForResponse(consentListResponse); + await page.getByRole("button", { name: "Дать согласие C3" }).click(); + expect((await c3Grant).status()).toBe(200); + const afterC3 = await readConsentList(c3Refresh); + expect(afterC3.items.some((record) => record.purpose === "c3" && record.state === "active")).toBe( + true, + ); + expect( + afterC3.items.find((record) => record.purpose === "c1" && record.state === "active"), + ).toBeDefined(); + expect( + afterC3.items.find((record) => record.purpose === "c2" && record.state === "active"), + ).toBeDefined(); + expect( + afterC3.items.filter((record) => record.purpose === "c4" && record.state === "active"), + ).toHaveLength(2); + + const c2Delete = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/consents/c2" && + response.request().method() === "DELETE", + ); + const c2Refresh = page.waitForResponse(consentListResponse); + await page.setViewportSize({ width: 360, height: 900 }); + const c2RevokeButton = page.getByRole("button", { name: "Отозвать C2", exact: true }); + await focusByTab(page, c2RevokeButton); + await page.keyboard.press("Enter"); + const c2Acknowledgment = page.getByLabel("Я понимаю последствия отзыва C2."); + await expect(c2Acknowledgment).toBeVisible(); + await focusByTab(page, c2Acknowledgment); + await page.keyboard.press("Space"); + await expect(c2Acknowledgment).toBeChecked(); + const c2ConfirmButton = page.getByRole("button", { name: "Подтвердить отзыв" }); + await page.keyboard.press("Tab"); + await expect(c2ConfirmButton).toBeFocused(); + const c2ConfirmHasVisibleFocus = await c2ConfirmButton.evaluate((element) => { + if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false; + const style = getComputedStyle(element); + return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0; + }); + expect(c2ConfirmHasVisibleFocus).toBe(true); + await page.keyboard.press("Enter"); + expect((await c2Delete).status()).toBe(204); + const afterC2 = await readConsentList(c2Refresh); + expect(afterC2.items.find((record) => record.id === activeC2?.id)?.state).toBe("revoked"); + const c2Record = page + .getByRole("heading", { name: `Версия ${activeC2.text_version}` }) + .locator("xpath=.."); + await expect(c2Record.getByText("Отозвано", { exact: true }).first()).toBeVisible(); + + const target = activeC4.find( + (record) => record.organization?.name === "Первая тестовая компания", + ); + const other = activeC4.find((record) => record.organization?.name === "Вторая тестовая компания"); + expect(target?.organization?.id).toBeTruthy(); + expect(other?.organization?.id).toBeTruthy(); + if (!target?.organization || !other?.organization) { + throw new Error("The consent fixture is missing the two organization scopes."); + } + + const targetOrganizationId = target.organization.id; + const targetOrganizationName = target.organization.name; + const otherRecordId = other.id; + const deniedUrl = `**/api/v1/me/consents/c4/organizations/${targetOrganizationId}`; + await page.route(deniedUrl, (route) => + route.fulfill({ + status: 403, + contentType: "application/problem+json; charset=utf-8", + body: JSON.stringify({ + type: "urn:lincodex:problem:forbidden", + title: "Forbidden", + status: 403, + code: "forbidden", + }), + }), + ); + const c4RejectedRefresh = page.waitForResponse(consentListResponse); + const targetCompany = page + .getByRole("heading", { name: targetOrganizationName }) + .locator("xpath=.."); + await targetCompany.getByRole("button", { name: "Отозвать C4 для этой компании" }).click(); + await page + .getByLabel("Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.") + .check(); + await page.getByRole("button", { name: "Подтвердить отзыв" }).click(); + const afterRejectedC4 = await readConsentList(c4RejectedRefresh); + expect(afterRejectedC4.items.find((record) => record.id === target.id)?.state).toBe("active"); + expect(afterRejectedC4.items.find((record) => record.id === otherRecordId)?.state).toBe("active"); + await expect(page.getByRole("alert")).toContainText("Сервер отклонил действие"); + await expect(page.getByRole("alert")).toBeFocused(); + await expect(targetCompany.getByText("Действует", { exact: true })).toBeVisible(); + await page.unroute(deniedUrl); + + const c4Delete = page.waitForResponse( + (response) => + new URL(response.url()).pathname === + `/api/v1/me/consents/c4/organizations/${targetOrganizationId}` && + response.request().method() === "DELETE", + ); + const c4Refresh = page.waitForResponse(consentListResponse); + await targetCompany.getByRole("button", { name: "Подтвердить отзыв" }).click(); + expect((await c4Delete).status()).toBe(204); + const afterC4 = await readConsentList(c4Refresh); + expect(afterC4.items.find((record) => record.id === target.id)?.state).toBe("revoked"); + expect(afterC4.items.find((record) => record.id === otherRecordId)?.state).toBe("active"); + + const reloadList = page.waitForResponse(consentListResponse); + await page.reload(); + const afterReload = await readConsentList(reloadList); + expect(afterReload.items.find((record) => record.id === activeC2?.id)?.state).toBe("revoked"); + expect(afterReload.items.find((record) => record.id === target.id)?.state).toBe("revoked"); + expect(afterReload.items.find((record) => record.id === otherRecordId)?.state).toBe("active"); + await expect( + page.getByRole("heading", { name: "Согласия и настройки приватности" }), + ).toBeVisible(); + await checkResponsiveKeyboardFlow(page); + + const deletionResponsePromise = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/me/account-deletion-requests" && + response.request().method() === "POST", + ); + const deletionRefresh = page.waitForResponse(consentListResponse); + await page.getByRole("button", { name: "Отозвать C1 и запросить удаление" }).click(); + await page + .getByLabel( + "Я понимаю, что этот запрос запустит удаление аккаунта и не будет отменен повторным согласием.", + ) + .check(); + await page.getByRole("button", { name: "Запросить удаление" }).click(); + const deletionResponse = await deletionResponsePromise; + expect(deletionResponse.status()).toBe(202); + const deletionRequest = (await deletionResponse.json()) as { + status: "requested" | "processing"; + }; + const afterDeletionRequest = await readConsentList(deletionRefresh); + expect(afterDeletionRequest.items.find((record) => record.purpose === "c1")?.state).toBe( + "revoked", + ); + await expect(page.getByRole("status").filter({ hasText: "Запрос на удаление" })).toContainText( + deletionRequest.status === "processing" ? "передан в обработку" : "ожидает обработки", + ); +}); diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index a383f5a..4c3bf3d 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -2,6 +2,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { renderToString } from "react-dom/server"; import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom"; import { describe, expect, it } from "vitest"; +import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent"; import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity"; import { createQueryClient } from "../providers/query-client"; import { routes } from "./routes"; @@ -40,6 +41,50 @@ async function render(path: string): Promise { csrf_token: "A".repeat(43), }); } + if (path.startsWith("/candidate/privacy")) { + const hasMore = path.includes("history=partial"); + queryClient.setQueryData(getListMyConsentsQueryKey({ limit: 100 }), { + pages: [ + { + items: [ + { + id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80", + purpose: "c2", + state: "active", + text_version: "c2-2026-10-01", + source: "consent_settings", + granted_at: "2026-10-02T09:00:00Z", + revoked_at: null, + revocation_source: null, + organization: null, + fields: null, + invitation_id: null, + invitation_terms_version: null, + }, + { + id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81", + purpose: "c4", + state: "active", + text_version: "c4-2026-10-01", + source: "invitation_acceptance", + granted_at: "2026-10-03T09:00:00Z", + revoked_at: null, + revocation_source: null, + organization: { + id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", + name: "Первая тестовая компания", + }, + fields: ["email"], + invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60", + invitation_terms_version: 1, + }, + ], + page: { has_more: hasMore, next_cursor: hasMore ? "next-page" : null }, + }, + ], + pageParams: [undefined], + }); + } return renderToString( @@ -75,6 +120,7 @@ describe("route groups", () => { ["/candidate", "Главная", "Разделы кабинета кандидата"], ["/candidate/profile", "Профиль", "Разделы кабинета кандидата"], ["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"], + ["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"], ["/employer/company", "Компания и команда", "Разделы кабинета работодателя"], ["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"], ])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => { @@ -101,6 +147,7 @@ describe("route groups", () => { it("marks the active cabinet section with aria-current", async () => { expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]); expect(currentLinkText(await renderHtml("/candidate/results"))).toEqual(["Результаты"]); + expect(currentLinkText(await renderHtml("/candidate/privacy"))).toEqual(["Приватность"]); expect(currentLinkText(await renderHtml("/employer/invitations"))).toEqual(["Приглашения"]); }); @@ -151,8 +198,34 @@ describe("product readiness", () => { expect(html).toContain("Это не показатель готовности продукта"); }); - it("labels every cabinet screen as a placeholder", async () => { - for (const path of ["/candidate", "/candidate/privacy", "/employer/needs"]) { + it("renders the consent settings route with server-backed history", async () => { + const html = await renderHtml("/candidate/privacy"); + + expect(html).toContain("Публикация карточки кандидата"); + expect(html).toContain("c2-2026-10-01"); + expect(html).toContain("Первая тестовая компания"); + expect(html).toContain("Электронная почта"); + }); + + it("does not call a purpose empty while older history pages remain", async () => { + const html = await renderHtml("/candidate/privacy?history=partial"); + + expect(html).toContain("В загруженной части истории записей C3 пока нет"); + expect(html).toContain("Показать более ранние записи"); + expect(html).not.toContain("Записей C3 пока нет."); + }); + + it("links the saved candidate consent step to the same settings screen", async () => { + const html = await renderHtml("/candidate/onboarding"); + + expect(html).toContain("Состояние шага хранится на сервере"); + expect(html).toMatch( + /]*href="\/candidate\/privacy"[^>]*>Открыть согласия и настройки приватности<\/a>/, + ); + }); + + it("labels the remaining cabinet scaffolds as placeholders", async () => { + for (const path of ["/candidate", "/employer/needs"]) { expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач"); } }); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index a504447..98d70f7 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -1,6 +1,7 @@ import { redirect, type RouteObject } from "react-router-dom"; import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; +import { ConsentsPage } from "../../pages/consents"; import { SessionGate } from "../../entities/session"; import { NotFoundPage } from "../../pages/not-found"; import { PlaceholderPage } from "../../pages/placeholder"; @@ -62,7 +63,7 @@ export const routes: RouteObject[] = [ }, { path: paths.candidate.privacy, - element: , + element: , }, { path: "*", diff --git a/frontend/src/entities/consent/index.ts b/frontend/src/entities/consent/index.ts new file mode 100644 index 0000000..dc93c91 --- /dev/null +++ b/frontend/src/entities/consent/index.ts @@ -0,0 +1,14 @@ +export { + consentPurposeDetails, + consentPurposeOrder, + consentSourceLabels, + consentStateLabels, + contactFieldLabels, + deletionRequestStatusMessage, + emptyPurposeHistoryMessage, + formatConsentDate, + groupConsentHistory, + groupOrganizationConsents, + type ConsentPurposeGroup, + type OrganizationConsentGroup, +} from "./model/consent-presentation"; diff --git a/frontend/src/entities/consent/model/consent-presentation.test.ts b/frontend/src/entities/consent/model/consent-presentation.test.ts new file mode 100644 index 0000000..2f8e2a6 --- /dev/null +++ b/frontend/src/entities/consent/model/consent-presentation.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from "vitest"; +import type { ConsentRecord } from "../../../shared/api/schemas"; +import { + consentPurposeDetails, + consentPurposeOrder, + consentStateLabels, + deletionRequestStatusMessage, + emptyPurposeHistoryMessage, + formatConsentDate, + groupConsentHistory, + groupOrganizationConsents, +} from "./consent-presentation"; + +const record = (overrides: Partial = {}): ConsentRecord => ({ + id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80", + purpose: "c2", + state: "active", + text_version: "c2-2026-10-01", + source: "consent_settings", + granted_at: "2026-10-02T09:00:00Z", + revoked_at: null, + revocation_source: null, + organization: null, + fields: null, + invitation_id: null, + invitation_terms_version: null, + ...overrides, +}); + +describe("consent presentation", () => { + it("keeps every purpose independent and gives empty purposes their own groups", () => { + const groups = groupConsentHistory([ + record({ id: "c2-old", state: "superseded" }), + record({ id: "c1", purpose: "c1", text_version: "c1-2026-10-01" }), + record({ id: "c2-new", text_version: "c2-2026-10-02" }), + ]); + + expect(groups.map(({ purpose }) => purpose)).toEqual(consentPurposeOrder); + expect(groups.find(({ purpose }) => purpose === "c1")?.records.map(({ id }) => id)).toEqual([ + "c1", + ]); + expect(groups.find(({ purpose }) => purpose === "c2")?.records.map(({ id }) => id)).toEqual([ + "c2-old", + "c2-new", + ]); + expect(groups.find(({ purpose }) => purpose === "c3")?.records).toEqual([]); + }); + + it("groups C4 actions by organization while preserving each invitation record", () => { + const firstOrganization = { + id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", + name: "Первая тестовая компания", + }; + const secondOrganization = { + id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e02", + name: "Вторая тестовая компания", + }; + const groups = groupOrganizationConsents([ + record({ + id: "first-invitation-new", + purpose: "c4", + organization: firstOrganization, + fields: ["email"], + invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e61", + invitation_terms_version: 2, + }), + record({ + id: "second-company", + purpose: "c4", + organization: secondOrganization, + fields: ["phone"], + invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e62", + invitation_terms_version: 1, + }), + record({ + id: "first-invitation-old", + purpose: "c4", + state: "superseded", + organization: { ...firstOrganization, name: "Первая компания до переименования" }, + fields: ["phone"], + invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e63", + invitation_terms_version: 1, + }), + ]); + + expect(groups).toHaveLength(2); + expect(groups[0]?.displayName).toBe("Первая тестовая компания"); + expect(groups[0]?.records.map(({ id }) => id)).toEqual([ + "first-invitation-new", + "first-invitation-old", + ]); + expect(groups[1]?.records.map(({ id }) => id)).toEqual(["second-company"]); + expect(groups[0]?.records[1]?.organization?.name).toBe("Первая компания до переименования"); + }); + + it("provides distinct state labels and consequence copy for C1-C5", () => { + expect(consentStateLabels).toEqual({ + active: "Действует", + superseded: "Заменено новой версией", + revoked: "Отозвано", + }); + expect(Object.keys(consentPurposeDetails)).toEqual(consentPurposeOrder); + expect(consentPurposeDetails.c1.consequence).toContain("удаление аккаунта"); + expect(consentPurposeDetails.c2.consequence).toContain("карточку"); + expect(consentPurposeDetails.c3.consequence).toContain("ручную оценку"); + expect(consentPurposeDetails.c4.consequence).toContain("компании"); + expect(consentPurposeDetails.c5.consequence).toContain("синхронизацию"); + }); + + it("formats server timestamps in UTC", () => { + expect(formatConsentDate("2026-10-02T09:00:00Z")).toContain("UTC"); + }); + + it("does not claim that an unloaded history has no records", () => { + expect(emptyPurposeHistoryMessage("c2", true)).toContain("В загруженной части истории"); + expect(emptyPurposeHistoryMessage("c2", true)).toContain("Загрузите более ранние записи"); + expect(emptyPurposeHistoryMessage("c2", false)).toBe("Записей C2 пока нет."); + }); + + it("describes the server-reported account-deletion state without claiming completion", () => { + const requested = deletionRequestStatusMessage("requested"); + const processing = deletionRequestStatusMessage("processing"); + + expect(requested).toContain("ожидает обработки"); + expect(processing).toContain("передан в обработку"); + expect(requested).toContain("не удаляются сразу"); + expect(processing).toContain("еще не завершено"); + }); +}); diff --git a/frontend/src/entities/consent/model/consent-presentation.ts b/frontend/src/entities/consent/model/consent-presentation.ts new file mode 100644 index 0000000..f2f718a --- /dev/null +++ b/frontend/src/entities/consent/model/consent-presentation.ts @@ -0,0 +1,137 @@ +import type { + ConsentDeletionRequest, + ConsentRecord, + ConsentPurposeCode, +} from "../../../shared/api/schemas"; + +export const consentPurposeOrder = [ + "c1", + "c2", + "c3", + "c4", + "c5", +] as const satisfies readonly ConsentPurposeCode[]; + +export const consentPurposeDetails: Readonly< + Record +> = { + c1: { + title: "Обработка персональных данных", + consequence: + "Отзыв запускает запрос на удаление аккаунта и данных. Запрос обрабатывается отдельно и не удаляет данные сразу.", + }, + c2: { + title: "Публикация карточки кандидата", + consequence: + "Отзыв закроет карточку для будущих просмотров и связанные доступы. Новая публикация потребует нового согласия.", + }, + c3: { + title: "Автоматическая категоризация", + consequence: + "Отзыв остановит автоматическую категоризацию. Можно запросить ручную оценку по той же рубрике.", + }, + c4: { + title: "Передача выбранных данных компании", + consequence: + "Отзыв закроет будущий доступ указанной компании к выбранным полям и запустит уведомление интеграции.", + }, + c5: { + title: "Импорт результатов ФСП", + consequence: + "Отзыв остановит синхронизацию и закроет новые чтения импортированных результатов. Обработка сохраненных данных следует принятой политике.", + }, +}; + +export const consentStateLabels = { + active: "Действует", + superseded: "Заменено новой версией", + revoked: "Отозвано", +} as const satisfies Record; + +export const consentSourceLabels = { + registration: "При регистрации", + consent_settings: "В настройках согласий", + invitation_acceptance: "При принятии приглашения", +} as const satisfies Record; + +export const contactFieldLabels = { + full_name: "ФИО", + email: "Электронная почта", + phone: "Телефон", + telegram: "Telegram", +} as const satisfies Record[number], string>; + +export type ConsentPurposeGroup = { + purpose: ConsentPurposeCode; + records: ConsentRecord[]; +}; + +export type OrganizationConsentGroup = { + organizationId: string; + displayName: string; + records: ConsentRecord[]; +}; + +export function groupConsentHistory(records: readonly ConsentRecord[]): ConsentPurposeGroup[] { + const grouped = new Map( + consentPurposeOrder.map((purpose) => [purpose, []]), + ); + + for (const record of records) { + grouped.get(record.purpose)?.push(record); + } + + return consentPurposeOrder.map((purpose) => ({ + purpose, + records: grouped.get(purpose) ?? [], + })); +} + +export function groupOrganizationConsents( + records: readonly ConsentRecord[], +): OrganizationConsentGroup[] { + const grouped = new Map(); + + for (const record of records) { + if (record.purpose !== "c4" || !record.organization) continue; + + const current = grouped.get(record.organization.id); + if (current) { + current.records.push(record); + continue; + } + + grouped.set(record.organization.id, { + organizationId: record.organization.id, + displayName: record.organization.name, + records: [record], + }); + } + + return [...grouped.values()]; +} + +export function formatConsentDate(value: string): string { + return `${new Intl.DateTimeFormat("ru-RU", { + dateStyle: "medium", + timeStyle: "short", + timeZone: "UTC", + }).format(new Date(value))} UTC`; +} + +export function emptyPurposeHistoryMessage(purpose: ConsentPurposeCode, hasMore: boolean): string { + if (hasMore) { + return `В загруженной части истории записей C${purpose.slice(1)} пока нет. Загрузите более ранние записи, чтобы проверить историю.`; + } + if (purpose === "c4") { + return "Записей C4 пока нет. Такое согласие появляется при принятии приглашения с показом компании и выбранных полей."; + } + return `Записей C${purpose.slice(1)} пока нет.`; +} + +export function deletionRequestStatusMessage(status: ConsentDeletionRequest["status"]): string { + if (status === "processing") { + return "Запрос на удаление передан в обработку. Удаление еще не завершено; данные не удаляются сразу."; + } + return "Запрос на удаление зарегистрирован. Он ожидает обработки; данные не удаляются сразу."; +} diff --git a/frontend/src/features/consent-management/index.ts b/frontend/src/features/consent-management/index.ts new file mode 100644 index 0000000..d4708d4 --- /dev/null +++ b/frontend/src/features/consent-management/index.ts @@ -0,0 +1 @@ +export { ConsentManagement } from "./ui/consent-management"; diff --git a/frontend/src/features/consent-management/ui/consent-management.module.css b/frontend/src/features/consent-management/ui/consent-management.module.css new file mode 100644 index 0000000..0ef442d --- /dev/null +++ b/frontend/src/features/consent-management/ui/consent-management.module.css @@ -0,0 +1,178 @@ +.root { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.purpose-list { + display: grid; + gap: var(--space-6); + min-width: 0; +} + +.record-list, +.organization-list { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.record, +.organization-group, +.grant-panel, +.confirmation { + display: grid; + gap: var(--space-3); + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.record-title { + overflow-wrap: anywhere; + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); +} + +.organization-snapshot { + overflow-wrap: anywhere; + color: var(--color-text-secondary); +} + +.facts { + display: grid; + grid-template-columns: minmax(0, max-content) minmax(0, 1fr); + gap: var(--space-2) var(--space-4); + min-width: 0; +} + +.facts dt { + color: var(--color-text-secondary); +} + +.facts dd { + min-width: 0; + overflow-wrap: anywhere; +} + +.empty-purpose, +.notice, +.status-message, +.action-error { + overflow-wrap: anywhere; +} + +.notice { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-accent); + background: var(--color-canvas); +} + +.status-message { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-accent); + background: var(--color-canvas); +} + +.action-error { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-danger); + background: var(--color-canvas); +} + +.action-error button { + margin-left: var(--space-2); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + align-items: center; +} + +.checkbox { + display: flex; + gap: var(--space-3); + align-items: flex-start; + width: fit-content; + max-width: 100%; + line-height: var(--line-height-body); +} + +.checkbox input { + flex: none; + width: 1.15rem; + height: 1.15rem; + margin-top: 0.2em; + accent-color: var(--color-accent); +} + +.grant-actions { + display: grid; + gap: var(--space-3); + justify-items: start; + min-width: 0; +} + +.grant-panel { + width: 100%; + max-width: 50rem; +} + +.text-metadata { + color: var(--color-text-secondary); +} + +.consent-text { + max-height: 24rem; + min-width: 0; + overflow: auto; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-canvas); + font: inherit; + line-height: var(--line-height-body); + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.grant-form { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.load-more { + display: flex; + justify-content: center; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + white-space: nowrap; + clip-path: inset(50%); +} + +@media (width < 30rem) { + .facts { + grid-template-columns: minmax(0, 1fr); + } + + .facts dd + dt { + padding-top: var(--space-2); + } + + .record, + .organization-group, + .grant-panel, + .confirmation { + padding: var(--space-3); + } +} diff --git a/frontend/src/features/consent-management/ui/consent-management.tsx b/frontend/src/features/consent-management/ui/consent-management.tsx new file mode 100644 index 0000000..e49fe0d --- /dev/null +++ b/frontend/src/features/consent-management/ui/consent-management.tsx @@ -0,0 +1,708 @@ +import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect, useId, useRef, useState, type FormEvent } from "react"; +import { + getGetCurrentSessionQueryKey, + useGetCurrentSession, +} from "../../../shared/api/endpoints/identity/identity"; +import { + getListMyConsentsQueryKey, + listMyConsents, + useGetMyConsentText, + useGrantMyConsent, + useRequestMyAccountDeletion, + useRevokeMyConsent, + useRevokeMyOrganizationContactConsent, +} from "../../../shared/api/endpoints/consent/consent"; +import type { + ConsentDeletionRequest, + ConsentRecord, + ConsentSettingsPurpose, + ConsentSettingsRevokePurpose, +} from "../../../shared/api/schemas"; +import { ApiRequestError } from "../../../shared/api"; +import { Button, EmptyState, ErrorState, LoadingState, Section } from "../../../shared/ui"; +import { + consentPurposeDetails, + consentSourceLabels, + consentStateLabels, + contactFieldLabels, + deletionRequestStatusMessage, + emptyPurposeHistoryMessage, + formatConsentDate, + groupConsentHistory, + groupOrganizationConsents, +} from "../../../entities/consent"; +import type { OrganizationConsentGroup } from "../../../entities/consent"; +import styles from "./consent-management.module.css"; + +const pageSize = 100; +const historyQueryKey = getListMyConsentsQueryKey({ limit: pageSize }); + +type ConsentAction = + | { kind: "account" } + | { kind: "purpose"; purpose: ConsentSettingsRevokePurpose } + | { kind: "organization"; organizationId: string }; + +function actionCopy(action: ConsentAction): { + title: string; + description: string; + acknowledgment: string; + button: string; + success: string; +} { + if (action.kind === "account") { + return { + title: "Запросить удаление аккаунта", + description: + "Запрос отзовет C1 и запустит отдельную процедуру удаления аккаунта и данных. Удаление не происходит сразу, а повторное согласие не отменит уже созданный запрос.", + acknowledgment: + "Я понимаю, что этот запрос запустит удаление аккаунта и не будет отменен повторным согласием.", + button: "Запросить удаление", + success: + "Запрос на удаление зарегистрирован. Он обрабатывается отдельно; данные не удаляются сразу. Проверьте обновленное состояние согласий ниже.", + }; + } + + if (action.kind === "organization") { + return { + title: "Отозвать C4 для этой компании", + description: + "Будущий доступ этой компании ко всем действующим согласиям C4 будет закрыт. Согласия для других компаний не изменятся.", + acknowledgment: + "Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.", + button: "Подтвердить отзыв", + success: "Запрос на отзыв C4 обработан. Проверьте обновленное состояние ниже.", + }; + } + + return { + title: `Отозвать C${action.purpose.slice(1)}`, + description: consentPurposeDetails[action.purpose].consequence, + acknowledgment: `Я понимаю последствия отзыва C${action.purpose.slice(1)}.`, + button: "Подтвердить отзыв", + success: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`, + }; +} + +function refreshFailureMessage(error: unknown): string { + if (error instanceof ApiRequestError && error.code === "csrf_check_failed") { + return "Не удалось подтвердить запрос. Данные обновлены; проверьте состояние и повторите действие."; + } + if (error instanceof ApiRequestError && error.status === 403) { + return "Сервер отклонил действие. Проверьте обновленное состояние и доступ к этому разделу."; + } + return "Не удалось изменить согласие. Текущее состояние сохранено; обновите список и попробуйте снова."; +} + +function ConsentRecordView({ record }: { record: ConsentRecord }) { + return ( +
+

Версия {record.text_version}

+ {record.purpose === "c4" && record.organization ? ( +

Компания: {record.organization.name}

+ ) : null} +
+
Состояние
+
{consentStateLabels[record.state]}
+
Выдано
+
{formatConsentDate(record.granted_at)}
+
Источник
+
{consentSourceLabels[record.source]}
+ {record.revoked_at ? ( + <> +
Отозвано
+
{formatConsentDate(record.revoked_at)}
+ + ) : null} + {record.revocation_source ? ( + <> +
Кем отозвано
+
+ {record.revocation_source === "support_request" + ? "По обращению в поддержку" + : "В настройках согласий"} +
+ + ) : null} + {record.purpose === "c4" && record.fields ? ( + <> +
Выбранные поля
+
{record.fields.map((field) => contactFieldLabels[field]).join(", ")}
+ {record.invitation_terms_version ? ( + <> +
Версия условий приглашения
+
{record.invitation_terms_version}
+ + ) : null} + + ) : null} +
+
+ ); +} + +type ActionConfirmationProps = { + action: ConsentAction; + accepted: boolean; + isBusy: boolean; + isReady: boolean; + onAcceptChange: (accepted: boolean) => void; + onCancel: () => void; + onConfirm: () => void; +}; + +function ActionConfirmation({ + action, + accepted, + isBusy, + isReady, + onAcceptChange, + onCancel, + onConfirm, +}: ActionConfirmationProps) { + const id = useId(); + const copy = actionCopy(action); + + return ( +
+

{copy.title}

+

{copy.description}

+ +
+ + +
+
+ ); +} + +type ConsentGrantPanelProps = { + purpose: ConsentSettingsPurpose; + activeRecord: ConsentRecord | undefined; + csrfToken: string | undefined; + isSubmitting: boolean; + onCancel: () => void; + onGrant: (purpose: ConsentSettingsPurpose, textVersion: string) => Promise; +}; + +function ConsentGrantPanel({ + purpose, + activeRecord, + csrfToken, + isSubmitting, + onCancel, + onGrant, +}: ConsentGrantPanelProps) { + const id = useId(); + const text = useGetMyConsentText(purpose, { + query: { gcTime: 0, staleTime: 0, refetchOnMount: "always" }, + }); + const [acceptedVersion, setAcceptedVersion] = useState(null); + const currentText = text.data; + const alreadyActive = Boolean( + currentText && activeRecord?.text_version === currentText.text_version, + ); + const acceptedCurrentText = Boolean( + currentText && acceptedVersion === currentText.text_version && !text.isError, + ); + const isReady = Boolean( + currentText && + acceptedCurrentText && + !text.isError && + !text.isFetching && + !isSubmitting && + csrfToken, + ); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (!isReady || !currentText) return; + await onGrant(purpose, currentText.text_version); + } + + return ( +
+

Текущий текст C{purpose.slice(1)}

+ {text.isPending ? : null} + {text.isError ? ( + void text.refetch()} + isRetrying={text.isRefetching} + /> + ) : null} + {currentText && !text.isError ? ( + <> +

+ Версия {currentText.text_version}, опубликовано{" "} + {formatConsentDate(currentText.published_at)} +

+
+            {currentText.text}
+          
+ {alreadyActive ? ( +

Эта версия уже действует. Новое согласие не требуется.

+ ) : ( +
void submit(event)}> + {purpose === "c1" ? ( +

+ Повторное согласие не отменяет ранее созданный запрос на удаление аккаунта. +

+ ) : null} + +

+ Версия {currentText.text_version} +

+
+ + +
+
+ )} + + ) : null} +
+ ); +} + +function OrganizationConsent({ + group, + records, + confirming, + accepted, + isBusy, + isReady, + onBegin, + onAcceptChange, + onCancel, + onConfirm, +}: { + group: OrganizationConsentGroup; + records: ConsentRecord[]; + confirming: boolean; + accepted: boolean; + isBusy: boolean; + isReady: boolean; + onBegin: () => void; + onAcceptChange: (accepted: boolean) => void; + onCancel: () => void; + onConfirm: () => void; +}) { + const hasActiveRecord = records.some((record) => record.state === "active"); + const action: ConsentAction = { kind: "organization", organizationId: group.organizationId }; + + return ( +
+

{group.displayName}

+
+ {records.map((record) => ( + + ))} +
+ {hasActiveRecord && !confirming ? ( + + ) : null} + {hasActiveRecord && confirming ? ( + + ) : null} +
+ ); +} + +export function ConsentManagement() { + const queryClient = useQueryClient(); + const session = useGetCurrentSession(); + const csrfToken = session.data?.csrf_token; + const request = { + headers: csrfToken ? { "X-CSRF-Token": csrfToken } : {}, + }; + const history = useInfiniteQuery({ + queryKey: historyQueryKey, + queryFn: ({ pageParam, signal }) => + listMyConsents( + pageParam === undefined ? { limit: pageSize } : { limit: pageSize, cursor: pageParam }, + { signal }, + ), + initialPageParam: undefined as string | undefined, + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + refetchOnMount: "always", + }); + const grant = useGrantMyConsent({ request, mutation: { gcTime: 0 } }); + const revoke = useRevokeMyConsent({ request, mutation: { gcTime: 0 } }); + const revokeOrganization = useRevokeMyOrganizationContactConsent({ + request, + mutation: { gcTime: 0 }, + }); + const deleteAccount = useRequestMyAccountDeletion({ request, mutation: { gcTime: 0 } }); + const [grantPurpose, setGrantPurpose] = useState(null); + const [confirmation, setConfirmation] = useState(null); + const [acceptedConfirmation, setAcceptedConfirmation] = useState(false); + const [statusMessage, setStatusMessage] = useState(null); + const [actionError, setActionError] = useState(null); + const actionErrorRef = useRef(null); + + useEffect(() => { + if (actionError) actionErrorRef.current?.focus(); + }, [actionError]); + + const records = history.data?.pages.flatMap((page) => page.items) ?? []; + const purposeGroups = groupConsentHistory(records); + const c4Groups = groupOrganizationConsents( + purposeGroups.find(({ purpose }) => purpose === "c4")?.records ?? [], + ); + const isSubmitting = + grant.isPending || revoke.isPending || revokeOrganization.isPending || deleteAccount.isPending; + const canMutate = + Boolean(csrfToken) && !session.isPending && !session.isFetching && !session.isError; + const canConfirm = canMutate && !history.isFetching && acceptedConfirmation; + + function beginConfirmation(action: ConsentAction) { + setConfirmation(action); + setAcceptedConfirmation(false); + setStatusMessage(null); + setActionError(null); + } + + function cancelConfirmation() { + if (isSubmitting) return; + setConfirmation(null); + setAcceptedConfirmation(false); + } + + async function refreshHistory(): Promise { + try { + await queryClient.invalidateQueries( + { queryKey: getListMyConsentsQueryKey() }, + { throwOnError: true }, + ); + return queryClient.getQueryState(historyQueryKey)?.status === "success"; + } catch { + return false; + } + } + + async function refreshAfterFailure(error: unknown): Promise { + if (error instanceof ApiRequestError && error.status === 403) { + await queryClient.invalidateQueries( + { queryKey: getGetCurrentSessionQueryKey() }, + { throwOnError: false }, + ); + } + await queryClient.invalidateQueries( + { queryKey: getListMyConsentsQueryKey() }, + { throwOnError: false }, + ); + } + + async function submitGrant(purpose: ConsentSettingsPurpose, textVersion: string): Promise { + setActionError(null); + setStatusMessage(null); + try { + await grant.mutateAsync({ purpose, data: { text_version: textVersion, accepted: true } }); + if (!(await refreshHistory())) { + setActionError( + "Сервер принял запрос, но не удалось обновить список согласий. Перезагрузите страницу перед повтором.", + ); + return; + } + setGrantPurpose(null); + setStatusMessage( + `Согласие C${purpose.slice(1)} сохранено. Проверьте обновленную историю ниже.`, + ); + } catch (error: unknown) { + await refreshAfterFailure(error); + setActionError(refreshFailureMessage(error)); + } + } + + async function submitConfirmation(): Promise { + if (!confirmation || !canConfirm || isSubmitting) return; + const action = confirmation; + setActionError(null); + setStatusMessage(null); + + try { + let deletionStatus: ConsentDeletionRequest["status"] | undefined; + if (action.kind === "account") { + const deletionRequest = await deleteAccount.mutateAsync(); + deletionStatus = deletionRequest.status; + } else if (action.kind === "purpose") { + await revoke.mutateAsync({ purpose: action.purpose }); + } else { + await revokeOrganization.mutateAsync({ orgId: action.organizationId }); + } + + if (!(await refreshHistory())) { + setConfirmation(null); + setActionError( + "Сервер принял запрос, но не удалось обновить список согласий. Перезагрузите страницу перед повтором.", + ); + return; + } + + setConfirmation(null); + setAcceptedConfirmation(false); + setStatusMessage( + action.kind === "account" && deletionStatus + ? deletionRequestStatusMessage(deletionStatus) + : actionCopy(action).success, + ); + } catch (error: unknown) { + await refreshAfterFailure(error); + setActionError(refreshFailureMessage(error)); + } + } + + if (history.isPending && !history.data) { + return ; + } + + if (history.isError && !history.data) { + return ( + void history.refetch()} + isRetrying={history.isRefetching} + /> + ); + } + + return ( +
+ {statusMessage ? ( +

+ {statusMessage} +

+ ) : null} + {actionError ? ( +
+ {actionError} +
+ ) : null} + {history.isError && history.data ? ( +
+ Не удалось обновить историю. Показаны последние загруженные данные. + +
+ ) : null} + {!canMutate ? ( +

+ Для изменения согласий нужно заново проверить вход. Обновите страницу. +

+ ) : null} + {history.hasNextPage ? ( +

+ Показана часть истории. Загрузите более ранние записи, чтобы проверить все действующие + согласия и компании. +

+ ) : null} +
+ {purposeGroups.map(({ purpose, records: purposeRecords }) => { + const activeRecord = purposeRecords.find((record) => record.state === "active"); + const emptyMessage = emptyPurposeHistoryMessage(purpose, history.hasNextPage); + const isConfirmingPurpose = + confirmation?.kind === "account" + ? purpose === "c1" + : confirmation?.kind === "purpose" && confirmation.purpose === purpose; + const action: ConsentAction | null = + purpose === "c1" + ? { kind: "account" } + : purpose === "c2" || purpose === "c3" || purpose === "c5" + ? { kind: "purpose", purpose } + : null; + const canRevoke = + purpose === "c1" ? Boolean(activeRecord) : Boolean(activeRecord && action); + + return ( +
+ {purpose === "c4" ? ( + c4Groups.length > 0 ? ( +
+ {c4Groups.map((group) => ( + + beginConfirmation({ + kind: "organization", + organizationId: group.organizationId, + }) + } + onAcceptChange={setAcceptedConfirmation} + onCancel={cancelConfirmation} + onConfirm={() => void submitConfirmation()} + /> + ))} +
+ ) : ( +

{emptyMessage}

+ ) + ) : ( + <> + {purposeRecords.length > 0 ? ( +
+ {purposeRecords.map((record) => ( + + ))} +
+ ) : ( +

{emptyMessage}

+ )} + {canRevoke && action && !isConfirmingPurpose ? ( + + ) : null} + {canRevoke && action && isConfirmingPurpose ? ( + void submitConfirmation()} + /> + ) : null} +
+ {grantPurpose === purpose ? ( + setGrantPurpose(null)} + onGrant={submitGrant} + /> + ) : ( + + )} +
+ + )} +
+ ); + })} +
+ {records.length === 0 && !history.hasNextPage ? ( + + ) : null} + {history.hasNextPage ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx index 14216b0..e923d1d 100644 --- a/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx +++ b/frontend/src/pages/candidate-onboarding/ui/candidate-onboarding-page.tsx @@ -2,7 +2,7 @@ import { Navigate } from "react-router-dom"; import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; import { getOnboardingDestination } from "../../../entities/session"; import { paths } from "../../../shared/config"; -import { LoadingState, Page, Section, StatusView } from "../../../shared/ui"; +import { ButtonLink, LoadingState, Page, Section, StatusView } from "../../../shared/ui"; export function CandidateOnboardingPage() { const session = useGetCurrentSession(); @@ -41,7 +41,19 @@ export function CandidateOnboardingPage() { return (
-

Этот шаг сохранен в аккаунте и будет открыт после следующего входа.

+ {step === "candidate_consents" ? ( + <> +

+ Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие + отдельно. +

+ + Открыть согласия и настройки приватности + + + ) : ( +

Этот шаг сохранен в аккаунте и будет открыт после следующего входа.

+ )}
); diff --git a/frontend/src/pages/consents/index.ts b/frontend/src/pages/consents/index.ts new file mode 100644 index 0000000..651d08a --- /dev/null +++ b/frontend/src/pages/consents/index.ts @@ -0,0 +1 @@ +export { ConsentsPage } from "./ui/consents-page"; diff --git a/frontend/src/pages/consents/ui/consents-page.tsx b/frontend/src/pages/consents/ui/consents-page.tsx new file mode 100644 index 0000000..8d5af85 --- /dev/null +++ b/frontend/src/pages/consents/ui/consents-page.tsx @@ -0,0 +1,15 @@ +import { ConsentManagement } from "../../../features/consent-management"; +import { Page } from "../../../shared/ui"; + +export function ConsentsPage() { + return ( + + + + ); +}