From a8560663162f680e6c2614888442f13bf0e2850e Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 20:30:35 +0300 Subject: [PATCH] feat(invitations): add the candidate invitation inbox with C4 acceptance and decline --- docs/en/DEPLOY.md | 6 +- docs/en/TESTING.md | 2 + docs/ru/DEPLOY.md | 6 +- docs/ru/TESTING.md | 2 + frontend/README.en.md | 20 +- frontend/README.md | 20 +- frontend/e2e/assessment.spec.ts | 7 + frontend/e2e/candidate-invitations.spec.ts | 533 ++++++++++++++++++ frontend/e2e/match-search.spec.ts | 10 + frontend/playwright.config.ts | 27 +- frontend/src/app/router/routes.test.tsx | 18 +- frontend/src/app/router/routes.tsx | 9 +- .../api/candidate-invitations.test.ts | 217 +++++++ .../invitation/api/candidate-invitations.ts | 131 +++++ frontend/src/entities/invitation/index.ts | 34 +- .../model/candidate-invitation.fixtures.ts | 91 +++ .../invitation/model/candidate-labels.ts | 70 +++ .../model/candidate-standing.test.ts | 65 +++ .../invitation/model/candidate-standing.ts | 46 ++ .../invitation/model/command-key.test.ts | 22 + .../entities/invitation/model/command-key.ts | 25 + .../invitation/model/response-failure.test.ts | 76 +++ .../invitation/model/response-failure.ts | 119 ++++ .../entities/invitation/model/server-now.ts | 24 + frontend/src/entities/invitation/testing.ts | 17 + .../features/accept-contact-consent/index.ts | 5 + .../model/accept-command.test.ts | 126 +++++ .../model/accept-command.ts | 41 ++ .../model/accept-draft.test.ts | 60 ++ .../model/accept-draft.ts | 76 +++ .../ui/accept-contact-consent-form.module.css | 127 +++++ .../ui/accept-contact-consent-form.test.tsx | 50 ++ .../ui/accept-contact-consent-form.tsx | 191 +++++++ .../src/features/respond-invitation/index.ts | 5 + .../model/decline-command.test.ts | 70 +++ .../model/decline-command.ts | 40 ++ .../model/decline-draft.test.ts | 43 ++ .../respond-invitation/model/decline-draft.ts | 45 ++ .../ui/decline-invitation-form.module.css | 129 +++++ .../ui/decline-invitation-form.test.tsx | 42 ++ .../ui/decline-invitation-form.tsx | 170 ++++++ .../src/pages/candidate-invitations/index.ts | 5 + .../ui/candidate-invitation-page.test.tsx | 155 +++++ .../ui/candidate-invitation-page.tsx | 370 ++++++++++++ .../ui/candidate-invitations-page.test.tsx | 96 ++++ .../ui/candidate-invitations-page.tsx | 113 ++++ .../ui/candidate-invitations.module.css | 168 ++++++ .../src/pages/placeholder/model/screens.ts | 9 - .../src/pages/welcome/ui/welcome-page.tsx | 5 +- frontend/src/shared/config/paths.ts | 3 + .../src/widgets/invitation-preview/index.ts | 4 +- .../ui/invitation-preview.tsx | 106 +--- .../ui/invitation-terms.test.tsx | 52 ++ .../ui/invitation-terms.tsx | 130 +++++ 54 files changed, 3897 insertions(+), 136 deletions(-) create mode 100644 frontend/e2e/candidate-invitations.spec.ts create mode 100644 frontend/src/entities/invitation/api/candidate-invitations.test.ts create mode 100644 frontend/src/entities/invitation/api/candidate-invitations.ts create mode 100644 frontend/src/entities/invitation/model/candidate-invitation.fixtures.ts create mode 100644 frontend/src/entities/invitation/model/candidate-labels.ts create mode 100644 frontend/src/entities/invitation/model/candidate-standing.test.ts create mode 100644 frontend/src/entities/invitation/model/candidate-standing.ts create mode 100644 frontend/src/entities/invitation/model/command-key.test.ts create mode 100644 frontend/src/entities/invitation/model/command-key.ts create mode 100644 frontend/src/entities/invitation/model/response-failure.test.ts create mode 100644 frontend/src/entities/invitation/model/response-failure.ts create mode 100644 frontend/src/entities/invitation/model/server-now.ts create mode 100644 frontend/src/entities/invitation/testing.ts create mode 100644 frontend/src/features/accept-contact-consent/index.ts create mode 100644 frontend/src/features/accept-contact-consent/model/accept-command.test.ts create mode 100644 frontend/src/features/accept-contact-consent/model/accept-command.ts create mode 100644 frontend/src/features/accept-contact-consent/model/accept-draft.test.ts create mode 100644 frontend/src/features/accept-contact-consent/model/accept-draft.ts create mode 100644 frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css create mode 100644 frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.test.tsx create mode 100644 frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.tsx create mode 100644 frontend/src/features/respond-invitation/index.ts create mode 100644 frontend/src/features/respond-invitation/model/decline-command.test.ts create mode 100644 frontend/src/features/respond-invitation/model/decline-command.ts create mode 100644 frontend/src/features/respond-invitation/model/decline-draft.test.ts create mode 100644 frontend/src/features/respond-invitation/model/decline-draft.ts create mode 100644 frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css create mode 100644 frontend/src/features/respond-invitation/ui/decline-invitation-form.test.tsx create mode 100644 frontend/src/features/respond-invitation/ui/decline-invitation-form.tsx create mode 100644 frontend/src/pages/candidate-invitations/index.ts create mode 100644 frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.test.tsx create mode 100644 frontend/src/pages/candidate-invitations/ui/candidate-invitation-page.tsx create mode 100644 frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.test.tsx create mode 100644 frontend/src/pages/candidate-invitations/ui/candidate-invitations-page.tsx create mode 100644 frontend/src/pages/candidate-invitations/ui/candidate-invitations.module.css create mode 100644 frontend/src/widgets/invitation-preview/ui/invitation-terms.test.tsx create mode 100644 frontend/src/widgets/invitation-preview/ui/invitation-terms.tsx diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index ff334ac..a7117c4 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -17,9 +17,9 @@ Implemented in this build (backend API and frontend screens): - Employer cabinet: organizations (one account can own several and be a recruiter in others), the company profile, needs with a salary range, deterministic candidate search over the bank or by a need without ML, with an explanation of the components, and the anonymous card with its evidence. Only an organization owner can search. - Support cases in both cabinets, including a manual assessment request after a C3 refusal. - The notification inbox in both cabinets. In this build no product workflow creates notifications yet, so the list is empty. -- Invitation drafts on the organization side only and through the API only: create, list, read, and change the terms with versions. There is no invitation screen. +- Organization-side invitations: create a draft, list, read, and change the terms with versions through the API; the invitation screen opens from a candidate search result, and the company's invitation list is still a placeholder. -Planned and not working: sending an invitation to a candidate (the API answers 501 `not_implemented`), the candidate invitation inbox, viewing, accepting, and declining, withdrawal, salary raise, and contact release, the invitation screens in both cabinets (placeholders now), password reset, mail for product notifications, resume upload and parsing, PDF, FSP integration, ML inference and semantic search, the adaptive test, sandbox practice, percentiles and calibrated grades, and the SMTP transport. +Planned and not working: sending an invitation to a candidate (the API answers 501 `not_implemented`), withdrawal, salary raise, and contact release, the company's invitation list screen (a placeholder now), password reset, mail for product notifications, resume upload and parsing, PDF, FSP integration, ML inference and semantic search, the adaptive test, sandbox practice, percentiles and calibrated grades, and the SMTP transport. ### Requirements @@ -82,7 +82,7 @@ The full inventory and the seed rules are in [Isolated demo stand](#isolated-dem 2. On the same page start the Backend Junior full test with Go: 25 items, a 72-hour deadline, two work sessions, no practice. After it completes, the result is compared with the pass mark of the demo policy; a passed test receives an uncalibrated synthetic category, a failed one the result `not_confirmed`. The result and the history open at `/candidate/results`. 3. Prepared candidate: sign in as `prepared-1@demo.lincodex.test` and open the results, the skill evidence, and the privacy settings with the published card. 4. Employer: sign in as `employer-alpha@demo.lincodex.test`, select "Alpha", create a need, and open the search (`/employer/candidates`). The main group holds the six prepared cards with the flags `ml_unavailable` and `cohort_below_30`; a card and its evidence open from the results. In "Beta" the same account is a recruiter, and search answers 403: in the minimal release only the owner can search. -5. Invitations: the screen in both cabinets is a placeholder. A draft can be created through the API only; sending and the candidate's answer are planned. +5. Invitations: the company's invitation list is a placeholder. An invitation is created from a candidate search result; the candidate sees it in the incoming list and answers it on the invitation screen. ### 5. FSP, ML, and data diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 562609f..6f6d214 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -59,6 +59,8 @@ Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis - Waits for backend readiness, runs the suite with retries disabled, and returns its exit code; make reports any failure as exit status 2. - Removes the containers, volumes, network, locally built images, and env file on every exit, including failures and interrupts. Only the cached Playwright image and the build cache remain. +Every browser of a run reaches the stand from the same client address: the browser container shares the frontend container's network namespace, so the app Nginx sees all requests from loopback. The per-address limit on `/api/v1/` (20 requests per second with a burst of 60, `deploy/nginx/nginx.conf` and `deploy/nginx/conf.d/app.conf`) is therefore one budget for the whole suite. A 429 from that limit is a failed stand, not a result of the flow under test, and the production limits stay unchanged; `deploy/scripts/test_perimeter.py` keeps checking them. The suite stays inside the budget by design. `frontend/playwright.config.ts` runs one worker. `frontend/e2e/assessment.spec.ts` pauses 250 ms after each saved answer of a full attempt, because a candidate reads each item. The real-bank search in `frontend/e2e/match-search.spec.ts` runs first, in its own project: an unfiltered bank search keeps ten entries per group, so candidates published by earlier specs would decide which entries the test sees. On the stand, a replay of this limit over the access log peaked at about two thirds of the burst with one worker and within about ten requests of it with two workers. + Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores; the runner prints the path. `report/` holds the HTML report (`pnpm exec playwright show-report test-results/e2e/report` from `frontend/`). For each failed test, `results/` keeps `trace.zip` and a screenshot (`pnpm exec playwright show-trace ` needs a local browser; trace.playwright.dev opens the file without one). After a failed run, `stand.log` holds the stack logs. `E2E_SPEC_DIR=` runs specs from another directory, such as a scratch copy, against the same isolated stack. ## Local registration browser tests with a mail fixture diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 6b0d9f2..7776b88 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -17,9 +17,9 @@ - Кабинет работодателя: организации (один аккаунт может владеть несколькими и быть рекрутером в других), профиль компании, потребности с вилкой зарплаты, детерминированный поиск кандидатов по банку или по потребности без ML с объяснением компонентов, анонимная карточка и ее доказательства. Поиск доступен только владельцу организации. - Обращения в поддержку в обоих кабинетах, в том числе запрос ручной оценки после отказа от C3. - Inbox уведомлений в обоих кабинетах. В этой сборке ни один продуктовый сценарий еще не создает уведомлений, поэтому список пуст. -- Черновики приглашений только на стороне организации и только через API: создание, список, чтение и изменение условий с версиями. Экрана приглашений нет. +- Приглашения на стороне организации: создание черновика, список, чтение и изменение условий с версиями через API; экран приглашения открывается из поиска кандидатов, а список приглашений компании пока заготовка. -Запланировано и не работает: отправка приглашения кандидату (API отвечает 501 `not_implemented`), входящие приглашения кандидата, просмотр, принятие и отклонение, отзыв, повышение зарплаты и выдача контактов, экраны приглашений в обоих кабинетах (сейчас заготовки), сброс пароля, письма о продуктовых уведомлениях, загрузка и разбор резюме, PDF, интеграция с ФСП, ML inference и смысловой поиск, адаптивный тест, практика в песочнице, перцентиль и откалиброванные грейды, транспорт SMTP. +Запланировано и не работает: отправка приглашения кандидату (API отвечает 501 `not_implemented`), отзыв, повышение зарплаты и выдача контактов, экран приглашений компании (сейчас заготовка), сброс пароля, письма о продуктовых уведомлениях, загрузка и разбор резюме, PDF, интеграция с ФСП, ML inference и смысловой поиск, адаптивный тест, практика в песочнице, перцентиль и откалиброванные грейды, транспорт SMTP. ### Что нужно на машине @@ -82,7 +82,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус 2. Там же начните полный тест Backend Junior с Go: 25 заданий, срок 72 часа, две рабочие сессии, без практики. После завершения результат сравнивается с порогом демонстрационной политики; пройденный тест получает неоткалиброванную синтетическую категорию, непройденный - результат `not_confirmed`. Результат и история открываются в `/candidate/results`. 3. Подготовленный кандидат: войдите как `prepared-1@demo.lincodex.test` и откройте результаты, доказательства навыка и настройки приватности с опубликованной карточкой. 4. Работодатель: войдите как `employer-alpha@demo.lincodex.test`, выберите "Альфу", создайте потребность и откройте подбор (`/employer/candidates`). Основная группа содержит шесть подготовленных карточек с отметками `ml_unavailable` и `cohort_below_30`; карточка и ее доказательства открываются из выдачи. В "Бете" тот же аккаунт - рекрутер, и поиск отвечает 403: в минимальном выпуске искать может только владелец. -5. Приглашения: экран в обоих кабинетах - заготовка. Черновик можно создать только через API, а отправка и ответ кандидата запланированы. +5. Приглашения: список приглашений компании - заготовка. Приглашение создается из результата поиска кандидатов; кандидат видит его во входящих и отвечает на экране приглашения. ### 5. ФСП, ML и данные diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index f83c7e5..91ac7b5 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -59,6 +59,8 @@ Deployment smoke проверяет инфраструктурные маршр - Ждет готовности backend, запускает набор без повторов и возвращает его код завершения; make сообщает о любой ошибке кодом 2. - При любом завершении, включая ошибку и прерывание, удаляет контейнеры, тома, сеть, локально собранные образы и env-файл. Остаются только закешированный образ Playwright и кеш сборки. +Все браузеры одного прогона обращаются к стенду с одного клиентского адреса: контейнер браузера разделяет сетевое пространство контейнера frontend, и app Nginx видит все запросы с loopback. Поэтому лимит на адрес для `/api/v1/` (20 запросов в секунду с burst 60, `deploy/nginx/nginx.conf` и `deploy/nginx/conf.d/app.conf`) общий для всего набора. 429 от этого лимита означает сбой стенда, а не результат проверяемого сценария; продуктивные лимиты не меняются, их по-прежнему проверяет `deploy/scripts/test_perimeter.py`. Набор укладывается в бюджет по замыслу. `frontend/playwright.config.ts` запускает один воркер. `frontend/e2e/assessment.spec.ts` делает паузу 250 мс после каждого сохраненного ответа полной попытки, потому что кандидат читает каждый пункт. Поиск по реальному банку в `frontend/e2e/match-search.spec.ts` идет первым, в собственном проекте: нефильтрованный поиск по банку возвращает десять записей на группу, поэтому кандидаты, опубликованные более ранними спецификациями, определили бы, какие записи увидит тест. На стенде воспроизведение этого лимита по access-логу дало пик примерно в две трети burst при одном воркере и около десяти запросов до порога при двух. + Артефакты последнего прогона лежат в `frontend/test-results/e2e/`, который игнорируется Git; путь печатается в конце. В `report/` лежит HTML-отчет (`pnpm exec playwright show-report test-results/e2e/report` из `frontend/`). Для каждого упавшего теста `results/` сохраняет `trace.zip` и снимок экрана (`pnpm exec playwright show-trace ` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке. ## Локальный браузерный тест регистрации с почтовым fixture diff --git a/frontend/README.en.md b/frontend/README.en.md index 234b3d8..d8ef55d 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -2,10 +2,10 @@ [Русский](README.md) | English -A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API. Candidate search, the employer's read of an anonymous card, and sending an invitation from a search result use the API; the company's invitation list and the candidate's invitation screens remain placeholders. +A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API. Candidate search, the employer's read of an anonymous card, and sending an invitation from a search result use the API. The candidate reads incoming invitations, accepts them with a choice of contacts, and declines them; the company's invitation list remains a placeholder. - `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page. -- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, candidate search, the invitation to a candidate, support cases, technical status, and remaining placeholders. +- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, candidate search, the invitation to a candidate, the candidate's incoming invitations, support cases, technical status, and remaining placeholders. - `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, the result history widget `assessment-history`, the search result widget `match-list`, the invitation preview `invitation-preview`, and the technical `system-status` widget. - `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)), `company`, and `invitation`; `src/features/` holds user actions and forms. - `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. @@ -20,7 +20,7 @@ From the repository root, `make -C frontend dev` starts development and `make -C | Group | Paths | Shell | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | +| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | | Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. `/support` sends a signed-in user to the support area for their account or to sign-in. Need pages pass `organization_id` in the query string, but the client checks the current owner directory and the server authorizes every request. @@ -150,6 +150,20 @@ Checks. Unit tests cover parsing and labels (`entities/match`), the request buil Checks. Unit tests cover the range rules (`entities/invitation`), draft validation and pointer mapping, the send command over MSW (keys, a retry after a lost create and a lost send response, 400 with fields, a draft update, 412), and the preview and page markup (owner access, an empty address). The Playwright suite `e2e/invitation-compose.spec.ts` runs on the real backend in `make -C deploy test-e2e-registration`: five synthetic candidates publish the same card, the owner finds them with a search, opens the invitation from the result, fills [100000; 140000] net and a package, and checks the preview against every term; without the communication method a field error shows, no request is sent, and the candidates' inboxes stay empty. Then the send is slowed down and its first response lost, a second click during the request starts nothing, and the retry uses the same key; the result is one invitation in one inbox (`GET /me/invitations`) with the deadline the screen shows, also after a reload. A 403 for a recruiter is not checked in the browser, since the stand cannot grant that role; the screen for a non-owner role is covered by a unit test. +## Candidate incoming invitations + +`/candidate/invitations` (`pages/candidate-invitations`) shows the incoming invitations: a cursor-paged list from `GET /me/invitations`, newest first, which records no view. `/candidate/invitations/:invitationId` opens one invitation. The contract is in the [API](../api/README.en.md#invitations-and-contact-grants). + +- Reading and viewing. The screen reads the invitation with `GET /me/invitations/{id}` and records the view once per opening (`POST .../view` with the CSRF token, without an Idempotency-Key). Reading changes nothing; the view moves `delivered` to `viewed` and keeps the deadline. A view answer replaces the shown invitation only when its version is newer. +- Terms. The company, the role, the tasks, the team, the technologies, the format and place of work, the salary range with its basis (net or gross), the package, and the communication method are shown as in the company's preview (`widgets/invitation-preview`, the shared `InvitationTermsArticle`). The response deadline is shown with a UTC label (`formatServerMoment`). The candidate sees no company card: the contract returns only the name. +- Deadline. Whether an answer is open depends on the invitation state and the server clock (`useServerNow`, corrected by the `Date` header). After the deadline the answers are closed, even before the server applies the expiry on a later read. +- Acceptance with C4 (`features/accept-contact-consent`). The contact kinds come from `contact_consent.available_fields`: full name, email, phone, and Telegram, as far as the profile holds them. Nothing is preselected, and each kind is chosen separately. The button becomes available after at least one kind and a separate confirmation of the text are chosen. The consent text is shown as plain text, unchanged, with its paragraphs from the server response. Without a contact in the profile the invitation cannot be accepted, and the screen offers to open the profile. +- Decline (`features/respond-invitation`). A reason is chosen explicitly; none is preselected. The comment is optional for every reason, including "Другая причина", up to 500 characters. Only the candidate reads the comment. +- Outdated terms. A 412 `version_conflict` (and a 409 with the same code) reads the invitation again: the new version of the terms is shown, the choice of contacts and the confirmation are reset, and the screen asks for a new confirmation. A 409 `state_conflict` shows the final state instead of a retry. A repeated answer after a lost response or a 5xx uses the same Idempotency-Key (`entities/invitation/model/command-key.ts`); a changed choice gets a new key. +- Outcome. After acceptance the screen shows only the contact kinds that the grant covers (`contact_grant.fields`) and whether the company can read them now: with `readable` false and the reason `visibility`, it explains that the card must be published and open to the company. After a decline it shows the reason and the candidate's own comment. The company gets contacts only through its own endpoint, and only the kinds of the grant. + +Checks. Unit tests cover the deadline and view rules, the classification of answer errors (`entities/invitation/model/response-failure.ts`), the idempotency keys, the form draft states, and the adapters and answer commands over MSW (CSRF and Idempotency-Key headers, schema checks of the response, a retry after a lost response), and the markup of the list, the screen, the forms, and the terms block. The Playwright suite `e2e/candidate-invitations.spec.ts` runs on the real backend in `make -C deploy test-e2e-registration`: five synthetic candidates publish a card, the owner finds them with a search, and three invitations are sent through the API. At 360 px a candidate accepts with the email only: the candidate's API shows one grant, and the company's contact endpoint returns the email and no phone. Outdated terms are checked with an intercepted response: the backend does not implement the raise of the upper salary bound after sending (`RaiseOrganizationInvitationSalary`), so the 412 and the new version of the terms come from a route, while the absence of a grant is checked on the real backend. A decline with "Другая причина" and no comment, followed by a reload, is checked on the real backend: the `declined` state stays after the reload, and the company's contact endpoint answers 404. + ## Support and manual assessment `/candidate/support/cases` and `/employer/support/cases` show each account's paginated support history. Their `.../new` routes create a case and `.../:caseId` routes show its status and history. The public `/support` route directs a signed-in user to their cabinet. The form draft stays in memory, and a retry of an unchanged request reuses its idempotency key. Support history is scoped to the current account and cleared when the session changes or the server denies access. diff --git a/frontend/README.md b/frontend/README.md index ea59956..8e4612f 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -2,10 +2,10 @@ Русский | [English](README.en.md) -SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API. Подбор кандидатов, чтение анонимной карточки работодателем и отправка приглашения из выдачи работают с API; список приглашений компании и экраны приглашений кандидата остаются заготовками. +SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API. Подбор кандидатов, чтение анонимной карточки работодателем и отправка приглашения из выдачи работают с API. Кандидат читает входящие приглашения, принимает их с выбором контактов и отклоняет; список приглашений компании остается заготовкой. - `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. -- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, подбор кандидатов, приглашение кандидату, обращения в поддержку, технический статус и оставшиеся заготовки экранов. +- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, подбор кандидатов, приглашение кандидату, входящие приглашения кандидата, обращения в поддержку, технический статус и оставшиеся заготовки экранов. - `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, виджет истории результатов `assessment-history`, виджет выдачи подбора `match-list`, предпросмотр приглашения `invitation-preview` и технический виджет `system-status`. - `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)), `company` и `invitation`; `src/features/` - действия пользователя и формы. - `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. @@ -20,7 +20,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS | Группа | Пути | Оболочка | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | +| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | | Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере. @@ -150,6 +150,20 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Проверки. Модульные тесты: правила вилки (`entities/invitation`), проверка черновика и перевод указателей ошибок, команда отправки на MSW (ключи, повтор после потерянного ответа создания и отправки, 400 с полями, обновление черновика, 412), разметка предпросмотра и страницы (доступ владельца, пустой адрес). Playwright `e2e/invitation-compose.spec.ts` работает на реальном бэкенде в `make -C deploy test-e2e-registration`: пять синтетических кандидатов публикуют одинаковую карточку, владелец находит их поиском, открывает приглашение из выдачи, заполняет [100000; 140000] net и пакет и сверяет предпросмотр со всеми условиями; без способа связи видна ошибка поля, запросов нет, inbox кандидатов пуст. Затем отправка замедляется, первый ответ теряется, второе нажатие во время запроса ничего не запускает, повтор идет с тем же ключом; в итоге одно приглашение в одном inbox (`GET /me/invitations`) с тем же сроком, что на экране и после перезагрузки. Отказ 403 для рекрутера в браузере не проверен: на стенде нет способа выдать такую роль; поведение экрана для неглавной роли покрыто модульным тестом. +## Входящие приглашения кандидата + +`/candidate/invitations` (`pages/candidate-invitations`) показывает входящие приглашения: список по курсору из `GET /me/invitations`, новые сверху, без записи просмотра. `/candidate/invitations/:invitationId` открывает одно приглашение. Контракт описан в [API](../api/README.md#приглашения-и-контактные-разрешения). + +- Чтение и просмотр. Экран читает приглашение через `GET /me/invitations/{id}`, а при открытии один раз записывает просмотр (`POST .../view` с CSRF-токеном, без Idempotency-Key). Чтение ничего не меняет; просмотр переводит `delivered` в `viewed` и не меняет срок. Ответ просмотра применяется только если его версия новее уже показанной. +- Условия. Компания, роль, задачи, команда, технологии, формат и место работы, вилка зарплаты с базой (net или gross), пакет и способ связи показаны так же, как в предпросмотре компании (`widgets/invitation-preview`, общий блок `InvitationTermsArticle`). Срок ответа показан с меткой UTC (`formatServerMoment`). Карточки компании у кандидата нет: контракт отдает только название. +- Срок. Открыт ли ответ, решают состояние приглашения и серверные часы (`useServerNow`, поправка по заголовку `Date`). После срока ответы закрыты даже до того, как сервер применит истечение при следующем чтении. +- Принятие с C4 (`features/accept-contact-consent`). Виды контактов берутся из `contact_consent.available_fields` и могут быть ФИО, электронная почта, телефон и Telegram, если профиль их содержит. Ничего не отмечено заранее: каждый вид выбирается отдельно. Кнопка становится доступна после выбора хотя бы одного вида и отдельного подтверждения текста. Текст согласия показывается как текст без изменений, абзацы берутся из ответа сервера. Без контактов в профиле принять нельзя, экран предлагает открыть профиль. +- Отказ (`features/respond-invitation`). Причина выбирается явно, ни одна не выбрана заранее. Комментарий необязателен для любой причины, включая «Другая причина»; до 500 символов. Комментарий видит только кандидат. +- Устаревшие условия. Ответ 412 `version_conflict` (и 409 с тем же кодом) перечитывает приглашение: показывается новая версия условий, выбор контактов и подтверждение сбрасываются, экран просит подтвердить заново; ответ 409 `state_conflict` показывает итоговое состояние вместо повтора. Повтор того же ответа после потерянного ответа или 5xx использует тот же Idempotency-Key (`entities/invitation/model/command-key.ts`), изменившийся выбор получает новый ключ. +- Итог. После принятия экран показывает только виды контактов, которые покрывает грант (`contact_grant.fields`), и готовность компании их прочитать: при `readable` false с причиной `visibility` объясняет, что карточка должна быть опубликована и открыта для компании. После отказа показывает причину и собственный комментарий кандидата. Компания получает контакты только через свой эндпоинт, и только виды из гранта. + +Проверки. Модульные тесты: правила срока и просмотра, классификация ошибок ответа (`entities/invitation/model/response-failure.ts`), ключи повторов, состояния черновиков формы, адаптеры и команды ответа на MSW (заголовки CSRF и Idempotency-Key, проверка ответа схемой, повтор после потерянного ответа), разметка списка, экрана, форм и блока условий. Playwright `e2e/candidate-invitations.spec.ts` работает на настоящем бэкенде в `make -C deploy test-e2e-registration`: пять синтетических кандидатов публикуют карточку, владелец находит их поиском, три приглашения отправляются через API. На 360 px кандидат принимает приглашение, отметив только электронную почту; API кандидата показывает один грант, эндпоинт компании отдает почту и не отдает телефон. Устаревшие условия проверяются перехватом ответа: команда повышения верхней границы вилки после отправки (`RaiseOrganizationInvitationSalary`) в бэкенде пока не реализована, поэтому 412 и новая версия условий задаются маршрутом, а отсутствие гранта проверяется на настоящем бэкенде. Отказ «Другая причина» без комментария и перезагрузка проверяются на настоящем бэкенде: после перезагрузки состояние `declined` сохраняется, эндпоинт контактов компании отвечает 404. + ## Поддержка и ручная оценка `/candidate/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе. diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index 7fcf3ac..622dadc 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -27,6 +27,12 @@ type AttemptSnapshot = { const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1"; const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; const password = "correct horse battery staple 2026"; +// Pause after each saved answer of a full attempt. Back to back, the loop sends +// about fifty requests a second (each answer and the attempt read that follows +// it) from the one client address of the stand, which spends the per-address +// API budget of the app Nginx in about a second. A candidate reads each item +// before answering, so this pace is what a person produces. +const answerPauseMs = 250; test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" }); @@ -209,6 +215,7 @@ async function answerRequiredNumericItems( await page.keyboard.press("Enter"); expect((await answerResponsePromise).status()).toBe(200); submitted += 1; + await page.waitForTimeout(answerPauseMs); } return submitted; } diff --git a/frontend/e2e/candidate-invitations.spec.ts b/frontend/e2e/candidate-invitations.spec.ts new file mode 100644 index 0000000..15381fe --- /dev/null +++ b/frontend/e2e/candidate-invitations.spec.ts @@ -0,0 +1,533 @@ +import { + expect, + test, + type Browser, + type BrowserContext, + type Locator, + type Page, +} from "@playwright/test"; + +// The candidate side of an invitation with the real backend. Five synthetic +// candidates publish the same card, the owner of a new organization finds +// them with one search, and three of them receive an invitation through the +// organization API. Each candidate keeps a signed-in browser context, so the +// spec reads the outcome through the candidate and organization APIs as well +// as the screen. The steps run in order and each one leaves the next one a +// known state: +// +// 1. At 360px a candidate accepts with the email only: the grant covers the +// email, the phone is not disclosed to the organization. +// 2. A stale terms answer (412, the stand has no way to raise a sent +// invitation, so the response is intercepted) leaves the new terms in view +// with the consent unchosen; nothing is granted on the backend. +// 3. Another candidate declines with the neutral reason and no comment; a +// reload keeps the decline, and no contact is readable by the organization. + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const password = "correct horse battery staple 2026"; +// The declared grade is unique to this spec, so the search returns only the +// candidates it publishes and never those of another spec. +const declaredSpecialization = "information_security"; +const declaredGrade = "junior"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +type ApiResult = { status: number; body: unknown }; +type InboxPage = { items: { id: string; state: string; organization: { id: string } }[] }; +type Invitation = { + id: string; + state: string; + version: number; + terms_version: number; + response_deadline_at: string; + decline: { reason: string; comment: string | null } | null; + contact_grant: { fields: string[]; status: string } | null; +}; +type Candidate = { context: BrowserContext; page: Page; email: string; phone: string }; + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readMailbox(email: string): Promise<{ text?: string; html?: string }[]> { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as { messages: { text?: string; html?: string }[] }).messages; +} + +async function verificationToken(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readMailbox(email)).at(-1); + if (message) { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The registration message had no verification link."); + return token; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local mailbox did not receive the verification message."); +} + +// Registers, confirms, and signs in a synthetic account. +async function createAccount( + page: Page, + scenario: "candidate" | "employer", + email: string, +): Promise { + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page + .getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ }) + .check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${await verificationToken(email)}`; + await page.goto(verificationUrl.toString()); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto(scenario === "employer" ? "/employer/company" : "/candidate"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.status() === 201, + ); + await page.getByRole("button", { name: "Войти" }).click(); + await loginResponse; +} + +// Calls the API from the page, so the cookie and the origin are the browser's. +async function api(page: Page, method: string, path: string, body?: unknown): Promise { + return page.evaluate( + async ({ method, path, body }) => { + const headers: Record = {}; + if (method !== "GET") { + const session = await fetch("/api/v1/identity/sessions/current", { + credentials: "include", + }); + headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token; + headers["Idempotency-Key"] = crypto.randomUUID(); + } + if (body !== undefined) headers["Content-Type"] = "application/json"; + const response = await fetch(path, { + method, + headers, + credentials: "include", + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + return { status: response.status, body: await response.json().catch(() => null) }; + }, + { method, path, body }, + ); +} + +// A candidate with a declared information security junior, an active C2, a +// published card, and two contact channels: the offer then lists four kinds +// that the profile holds (full name, email, phone, and the first two). +async function publishCandidate(browser: Browser): Promise { + const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + const page = await context.newPage(); + const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); + const email = `invitee-${suffix}@example.test`; + const phone = `+7900${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`; + await createAccount(page, "candidate", email); + const profile = await api(page, "PUT", "/api/v1/me/profile", { + expected_version: 0, + full_name: { value: "Приглашаемый кандидат", status: "confirmed" }, + contacts: { + email: { value: email, status: "confirmed" }, + phone: { value: phone, status: "confirmed" }, + telegram: null, + }, + stack: [], + roles: [ + { + specialization: declaredSpecialization, + self_assessed_grade: declaredGrade, + status: "confirmed", + }, + ], + experience: [], + soft_skills: [], + terms: { location: null, relocation: null, salary_minimum: null }, + }); + expect(profile.status).toBe(200); + const text = await api(page, "GET", "/api/v1/me/consent-texts/c2"); + expect(text.status).toBe(200); + const granted = await api(page, "PUT", "/api/v1/me/consents/c2", { + text_version: (text.body as { text_version: string }).text_version, + accepted: true, + }); + expect(granted.status).toBe(200); + const published = await api(page, "PUT", "/api/v1/me/privacy/publication", { + expected_version: 0, + state: "published", + fields: ["self_assessment"], + }); + expect(published.status).toBe(200); + return { context, page, email, phone }; +} + +// The terms of the invitation: remote only, so the place of work is null. +const terms = { + role_title: "Аналитик SOC, стажировка", + specialization: declaredSpecialization, + grade: "junior", + offer_type: "internship", + tasks: ["Разбирать события SIEM", "Готовить отчеты об инцидентах"], + team: "Дежурная смена SOC: четыре аналитика и руководитель.", + tech_stack: ["Splunk", "Suricata"], + work_formats: ["remote"], + location: null, + communication_method: { channel: "video_call", details: null }, + salary: { + salary_from: 100000, + salary_to: 140000, + currency: "RUB", + period: "month", + tax_basis: "net", + }, + package: { + bonus: { status: "not_provided" }, + equipment: { status: "provided", description: "Ноутбук и второй монитор" }, + training: { status: "not_provided" }, + health_insurance: { status: "not_provided" }, + }, +}; + +async function expectNoHorizontalOverflow(page: Page, width: number): Promise { + await page.setViewportSize({ width, height: 900 }); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(overflow, `no horizontal overflow at ${width}px`).toBe(false); +} + +// The list of contacts that the grant covers, found by the heading above it. +function grantList(page: Page): Locator { + return page + .getByRole("heading", { name: "Контакты, которые открыты компании" }) + .locator("xpath=following-sibling::ul[1]") + .getByRole("listitem"); +} + +// Opens an invitation screen by an action (a link click or a direct address) +// and waits for the view the page records once when it opens. +async function openInvitation( + candidatePage: Page, + invitationId: string, + navigate: () => Promise, +): Promise { + const viewed = candidatePage.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/invitations/${invitationId}/view` && + response.status() === 200, + ); + await navigate(); + expect((await viewed).status()).toBe(200); + await expect(candidatePage.getByRole("heading", { level: 1, name: "Приглашение" })).toBeVisible(); +} + +test.describe("candidate invitations with the real backend", () => { + test.skip(!mailFixtureEnabled, "Requires the isolated mail fixture."); + + test("accepts with the email only, keeps a stale answer unchanged, and declines without a comment", async ({ + browser, + page, + }) => { + test.setTimeout(600_000); + const candidates: Candidate[] = []; + try { + for (let index = 0; index < 5; index += 1) candidates.push(await publishCandidate(browser)); + + const ownerSuffix = crypto.randomUUID().slice(0, 8); + await createAccount(page, "employer", `inviter-${ownerSuffix}@example.test`); + const organizationName = `Компания ${ownerSuffix}`; + const organization = await api(page, "POST", "/api/v1/organizations", { + name: organizationName, + }); + expect(organization.status).toBe(201); + const organizationId = (organization.body as { id: string }).id; + + // One search returns the five cards; three handles receive an invitation. + const search = await api(page, "POST", `/api/v1/organizations/${organizationId}/matches`, { + filters: { specialization: declaredSpecialization, declared_grade: declaredGrade }, + }); + expect(search.status).toBe(200); + const handles = ( + search.body as { groups: { unconfirmed: { candidate_handle: string }[] } } + ).groups.unconfirmed.map((entry) => entry.candidate_handle); + expect(handles.length).toBeGreaterThanOrEqual(3); + for (const handle of handles.slice(0, 3)) { + const draft = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations`, + { + candidate_handle: handle, + response_period_days: 7, + terms, + }, + ); + expect(draft.status).toBe(201); + const draftId = (draft.body as { id: string; version: number }).id; + const version = (draft.body as { version: number }).version; + const sent = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations/${draftId}/send`, + { expected_version: version }, + ); + expect(sent.status).toBe(200); + } + + // Which candidates received them: read each inbox, one request at a time. + const received: { candidate: Candidate; invitationId: string }[] = []; + for (const candidate of candidates) { + const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); + expect(inbox.status).toBe(200); + for (const item of (inbox.body as InboxPage).items) { + if (item.organization.id === organizationId) { + received.push({ candidate, invitationId: item.id }); + } + } + } + expect(received).toHaveLength(3); + const [accepting, stale, declining] = received; + if (!accepting || !stale || !declining) throw new Error("Three invitations are needed."); + + await test.step("accepts with the email only at 360px, and the organization reads the email only", async () => { + const candidatePage = accepting.candidate.page; + await candidatePage.setViewportSize({ width: 360, height: 900 }); + await candidatePage.goto("/candidate/invitations"); + const link = candidatePage.getByRole("link", { name: new RegExp(organizationName) }); + await expect(link).toBeVisible(); + await expectNoHorizontalOverflow(candidatePage, 360); + await openInvitation(candidatePage, accepting.invitationId, async () => { + await link.click(); + await expect(candidatePage).toHaveURL( + new RegExp(`/candidate/invitations/${accepting.invitationId}$`), + ); + }); + + // Nothing is preselected: every kind and the confirmation start unchecked. + for (const label of ["ФИО", "Электронная почта", "Телефон"]) { + await expect( + candidatePage.getByRole("checkbox", { name: label, exact: true }), + ).not.toBeChecked(); + } + await expect(candidatePage.getByRole("checkbox", { name: "Telegram" })).toHaveCount(0); + const submit = candidatePage.getByRole("button", { name: "Принять и передать контакты" }); + await expect(submit).toHaveAttribute("aria-disabled", "true"); + + await candidatePage + .getByRole("checkbox", { name: "Электронная почта", exact: true }) + .check(); + await candidatePage + .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) + .check(); + await expect(submit).not.toHaveAttribute("aria-disabled", "true"); + await expectNoHorizontalOverflow(candidatePage, 360); + + const accepted = candidatePage.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/invitations/${accepting.invitationId}/accept`, + ); + await submit.click(); + expect((await accepted).status()).toBe(200); + + await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); + await expect(grantList(candidatePage)).toHaveText(["Электронная почта"]); + await expectNoHorizontalOverflow(candidatePage, 360); + + // The candidate's read: exactly one granted kind. + const mine = await api( + candidatePage, + "GET", + `/api/v1/me/invitations/${accepting.invitationId}`, + ); + expect(mine.status).toBe(200); + expect(mine.body).toMatchObject({ + state: "accepted", + contact_grant: { fields: ["email"], status: "active" }, + }); + + // The organization's read: the email, and no phone or name. + const disclosed = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${accepting.invitationId}/contacts`, + ); + expect(disclosed.status).toBe(200); + expect(disclosed.body).toMatchObject({ email: accepting.candidate.email, phone: null }); + expect((disclosed.body as { full_name: unknown }).full_name).toBeNull(); + }); + + await test.step("keeps a stale terms answer unchanged and asks for a new confirmation", async () => { + const staleId = stale.invitationId; + const candidatePage = stale.candidate.page; + await candidatePage.setViewportSize({ width: 360, height: 900 }); + await openInvitation(candidatePage, staleId, () => + candidatePage.goto(`/candidate/invitations/${staleId}`), + ); + await candidatePage.getByRole("checkbox", { name: "Телефон", exact: true }).check(); + await candidatePage + .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) + .check(); + + // The company changed the terms after the candidate read them. A sent + // invitation cannot be changed on this stand, so the first acceptance is + // answered 412 by the route, and the re-read returns the raised bound. + let staleAnswers = 0; + const acceptBodies: unknown[] = []; + const acceptPath = new RegExp(`/api/v1/me/invitations/${staleId}/accept$`); + const detailPath = new RegExp(`/api/v1/me/invitations/${staleId}$`); + await candidatePage.route(acceptPath, async (route) => { + acceptBodies.push(route.request().postDataJSON()); + staleAnswers += 1; + await route.fulfill({ + status: 412, + contentType: "application/problem+json", + body: JSON.stringify({ + type: "urn:lincodex:problem:version_conflict", + title: "Version conflict", + status: 412, + code: "version_conflict", + }), + }); + }); + await candidatePage.route(detailPath, async (route) => { + if (route.request().method() !== "GET" || staleAnswers === 0) { + await route.continue(); + return; + } + const real = await route.fetch(); + const body = (await real.json()) as { + version: number; + terms_version: number; + terms: { salary: { salary_to: number } }; + }; + await route.fulfill({ + response: real, + json: { + ...body, + version: body.version + 1, + terms_version: body.terms_version + 1, + terms: { ...body.terms, salary: { ...body.terms.salary, salary_to: 150000 } }, + }, + }); + }); + + await candidatePage.getByRole("button", { name: "Принять и передать контакты" }).click(); + await expect( + candidatePage.getByRole("status").filter({ hasText: "Приглашение изменилось" }), + ).toBeVisible(); + await expect(candidatePage.locator('[data-term="salary"]')).toHaveText( + /от 100\s000 ₽ до 150\s000 ₽/, + ); + // The new version starts with nothing chosen, so a new confirmation is needed. + await expect( + candidatePage.getByRole("checkbox", { name: "Телефон", exact: true }), + ).not.toBeChecked(); + await expect( + candidatePage.getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }), + ).not.toBeChecked(); + await expect( + candidatePage.getByRole("button", { name: "Принять и передать контакты" }), + ).toHaveAttribute("aria-disabled", "true"); + expect(staleAnswers).toBe(1); + expect(acceptBodies).toEqual([ + { + expected_version: expect.any(Number), + terms_version: 1, + consent_c4: expect.objectContaining({ accepted: true, fields: ["phone"] }), + }, + ]); + await expectNoHorizontalOverflow(candidatePage, 360); + + // The backend itself recorded no acceptance and no grant. + await candidatePage.unroute(acceptPath); + await candidatePage.unroute(detailPath); + const current = await api(candidatePage, "GET", `/api/v1/me/invitations/${staleId}`); + expect(current.status).toBe(200); + expect(current.body).toMatchObject({ contact_grant: null }); + expect(["delivered", "viewed"]).toContain((current.body as Invitation).state); + }); + + await test.step("declines without a comment, keeps the decline after a reload, and discloses nothing", async () => { + const candidatePage = declining.candidate.page; + await candidatePage.setViewportSize({ width: 360, height: 900 }); + await openInvitation(candidatePage, declining.invitationId, () => + candidatePage.goto(`/candidate/invitations/${declining.invitationId}`), + ); + await candidatePage.getByRole("radio", { name: "Другая причина", exact: true }).check(); + // No comment is written: the neutral reason never asks for one. + const declined = candidatePage.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === + `/api/v1/me/invitations/${declining.invitationId}/decline` && + response.status() === 200, + ); + await candidatePage.getByRole("button", { name: "Отклонить приглашение" }).click(); + expect((await declined).status()).toBe(200); + await expect(candidatePage.locator('[data-state="declined"]')).toHaveText( + "Вы отклонили приглашение", + ); + await expect(candidatePage.getByText("Причина: Другая причина.")).toBeVisible(); + + await candidatePage.reload(); + await expect(candidatePage.locator('[data-state="declined"]')).toHaveText( + "Вы отклонили приглашение", + ); + await expect(candidatePage.getByText("Причина: Другая причина.")).toBeVisible(); + await expect( + candidatePage.getByRole("button", { name: "Отклонить приглашение" }), + ).toHaveCount(0); + await expectNoHorizontalOverflow(candidatePage, 360); + + const mine = await api( + candidatePage, + "GET", + `/api/v1/me/invitations/${declining.invitationId}`, + ); + expect(mine.body).toMatchObject({ + state: "declined", + contact_grant: null, + decline: { reason: "other", comment: null }, + }); + + // The organization reads no contact: the endpoint answers not found. + const disclosed = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${declining.invitationId}/contacts`, + ); + expect(disclosed.status).toBe(404); + }); + } finally { + await Promise.all(candidates.map((candidate) => candidate.context.close())); + } + }); +}); diff --git a/frontend/e2e/match-search.spec.ts b/frontend/e2e/match-search.spec.ts index cf30c36..26c4fa6 100644 --- a/frontend/e2e/match-search.spec.ts +++ b/frontend/e2e/match-search.spec.ts @@ -11,6 +11,13 @@ import { expect, test, type Browser, type Locator, type Page, type Route } from // parts the stand cannot produce: the order of all three groups, a candidate // confirmed in one specialization and not in another, a partial output, the // quota refusal of a card read, and the other failure states. +// +// The real-bank test runs in its own Playwright project, before every other +// spec (frontend/playwright.config.ts). The unfiltered search returns at most +// ten entries per group, and for a bank search Fit and Coverage are equal for +// every unconfirmed entry, so the group is ordered by the internal candidate +// identifier. A candidate published by another spec earlier in the same stand +// would therefore push this test's candidates out of the group at random. const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1"; @@ -381,6 +388,9 @@ test.describe("employer candidate search with the real backend", () => { const second = await secondSearch; const secondBody = (await second.json()) as ServerResult; expect(JSON.parse(matchRequests[1] ?? "")).toEqual({ filters: {} }); + // The five candidates give exactly ten unconfirmed entries, the group limit. + // A truncated group means that another candidate shares the bank. + expect(secondBody.truncated, "the bank holds only the candidates of this test").toBe(false); const sharedHandle = secondBody.groups.unconfirmed .filter((card) => card.specialization === "backend" && card.declared_grade === "senior") .map((card) => card.candidate_handle) diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index a48e3c9..faeea4d 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -17,12 +17,20 @@ if (!allowedHosts.has(new URL(baseURL).hostname)) { const artifactsDir = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; +// The real-bank search runs first and alone. An unfiltered bank search returns +// the candidates that earlier specs published, so the test is independent of +// the other specs only if it runs before them (see the header of +// match-search.spec.ts). +const realBankSearch = /employer candidate search with the real backend/; + export default defineConfig({ testDir: "./e2e", outputDir: `${artifactsDir}/results`, forbidOnly: Boolean(process.env.CI), - // The browser container has two CPUs; host-based defaults oversubscribe it. - workers: 2, + // One worker: every browser shares one client address, so all browsers draw + // on one per-address API budget of the stand's Nginx. Two workers left too + // little margin in the busiest seconds of the suite (see docs/en/TESTING.md). + workers: 1, retries: 0, reporter: [["list"], ["html", { outputFolder: `${artifactsDir}/report`, open: "never" }]], use: { @@ -32,5 +40,18 @@ export default defineConfig({ screenshot: "only-on-failure", video: "off", }, - projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }], + projects: [ + { + name: "real-bank-search", + testMatch: /match-search\.spec\.ts$/, + grep: realBankSearch, + use: { ...devices["Desktop Chrome"] }, + }, + { + name: "chromium", + dependencies: ["real-bank-search"], + grepInvert: realBankSearch, + use: { ...devices["Desktop Chrome"] }, + }, + ], }); diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 5658c95..0f5ecaa 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -289,8 +289,20 @@ describe("product readiness", () => { }); it("labels the remaining cabinet scaffolds as placeholders", async () => { - for (const path of ["/candidate/invitations", "/employer/invitations"]) { - expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач"); - } + expect(await renderHtml("/employer/invitations")).toContain( + "Экран будет реализован в одной из следующих задач", + ); + }); + + it("routes the candidate inbox and one invitation to their own screens, not placeholders", async () => { + const inbox = await renderHtml("/candidate/invitations"); + expect(inbox).toMatch(/]*>Приглашения<\/h1>/); + expect(inbox).not.toContain("Экран будет реализован в одной из следующих задач"); + + const detail = await renderHtml( + `/candidate/invitations/${"0".repeat(8)}-0000-4000-8000-000000000000`, + ); + expect(detail).toContain("Открываем приглашение..."); + expect(detail).not.toContain("Экран будет реализован в одной из следующих задач"); }); }); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 2e3a4bc..bdb4217 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -2,6 +2,10 @@ import { redirect, type RouteObject } from "react-router-dom"; import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment"; import { AssessmentResultPage, AssessmentResultsPage } from "../../pages/assessment-result"; import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; +import { + CandidateInvitationPage, + CandidateInvitationsPage, +} from "../../pages/candidate-invitations"; import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; import { CompanyPage } from "../../pages/company"; import { PrivacyPage } from "../../pages/privacy"; @@ -80,9 +84,10 @@ export const routes: RouteObject[] = [ }, { path: paths.candidate.results, element: }, { path: `${paths.candidate.results}/:attemptId`, element: }, + { path: paths.candidate.invitations, element: }, { - path: paths.candidate.invitations, - element: , + path: `${paths.candidate.invitations}/:invitationId`, + element: , }, { path: paths.candidate.notifications, element: }, { diff --git a/frontend/src/entities/invitation/api/candidate-invitations.test.ts b/frontend/src/entities/invitation/api/candidate-invitations.test.ts new file mode 100644 index 0000000..3ddbc28 --- /dev/null +++ b/frontend/src/entities/invitation/api/candidate-invitations.test.ts @@ -0,0 +1,217 @@ +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import { candidateInvitationFixture, candidateInvitationId } from "../testing"; +import { + acceptCandidateInvitation, + declineCandidateInvitation, + listCandidateInvitations, + readCandidateInvitation, + viewCandidateInvitation, +} from "./candidate-invitations"; + +const base = "http://localhost/api/v1/me/invitations"; +const csrfToken = "A".repeat(43); +const idempotencyKey = "11111111-2222-4333-8444-555555555555"; + +const server = setupServer(); +beforeAll(() => server.listen({ onUnhandledFrame: "error" })); +beforeEach(() => { + // The browser client uses same-origin paths; Node needs an origin. + const realFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + realFetch(new URL(input, "http://localhost"), init), + ); +}); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +const problemHeaders = { "Content-Type": "application/problem+json" }; + +describe("candidate invitation transport", () => { + it("reads the inbox page with its cursor and parses it with the contract", async () => { + let cursor: string | null = null; + server.use( + http.get(base, ({ request }) => { + cursor = new URL(request.url).searchParams.get("cursor"); + return HttpResponse.json({ + items: [ + { + id: candidateInvitationId, + organization: { id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3201", name: "Северный ветер" }, + state: "delivered", + expiry_reason: null, + version: 1, + terms_version: 1, + role_title: "Middle Go-разработчик", + salary: { + salary_from: 100000, + salary_to: 140000, + currency: "RUB", + period: "month", + tax_basis: "net", + }, + work_formats: ["remote"], + response_deadline_at: "2099-10-16T10:00:00Z", + delivered_at: "2026-10-09T10:00:00Z", + viewed_at: null, + updated_at: "2026-10-09T10:00:00Z", + }, + ], + page: { has_more: true, next_cursor: "next-1" }, + }); + }), + ); + + const list = await listCandidateInvitations({ cursor: "first-1" }); + + expect(cursor).toBe("first-1"); + expect(list.items[0]?.role_title).toBe("Middle Go-разработчик"); + expect(list.page).toEqual({ has_more: true, next_cursor: "next-1" }); + }); + + it("refuses a response that does not match the contract instead of showing it", async () => { + server.use(http.get(base, () => HttpResponse.json({ items: [{ id: "not-an-invitation" }] }))); + + const failure = await listCandidateInvitations().catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(ApiRequestError); + expect((failure as ApiRequestError).code).toBe("invalid_response"); + }); + + it("reads the terms without any side effect and parses the full invitation", async () => { + const methods: string[] = []; + server.use( + http.get(`${base}/${candidateInvitationId}`, ({ request }) => { + methods.push(request.method); + return HttpResponse.json(candidateInvitationFixture()); + }), + ); + + const invitation = await readCandidateInvitation(candidateInvitationId); + + expect(methods).toEqual(["GET"]); + expect(invitation.contact_consent?.available_fields).toEqual(["full_name", "email", "phone"]); + }); + + it("records a view with the CSRF token and no Idempotency-Key", async () => { + const seen: { csrf: string | null; key: string | null; method: string }[] = []; + server.use( + http.post(`${base}/${candidateInvitationId}/view`, ({ request }) => { + seen.push({ + csrf: request.headers.get("X-CSRF-Token"), + key: request.headers.get("Idempotency-Key"), + method: request.method, + }); + return HttpResponse.json(candidateInvitationFixture({ state: "viewed", version: 2 })); + }), + ); + + const viewed = await viewCandidateInvitation(candidateInvitationId, { csrfToken }); + + expect(viewed.state).toBe("viewed"); + expect(seen).toEqual([{ csrf: csrfToken, key: null, method: "POST" }]); + }); + + it("sends the accepted fields, the versions, and the key, and returns the grant", async () => { + let body: unknown = null; + let key: string | null = null; + server.use( + http.post(`${base}/${candidateInvitationId}/accept`, async ({ request }) => { + key = request.headers.get("Idempotency-Key"); + body = await request.json(); + return HttpResponse.json( + candidateInvitationFixture({ + state: "accepted", + version: 2, + contact_grant: { + id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301", + fields: ["email"], + status: "active", + readable: true, + blocked_by: null, + terms_version: 1, + consent_text_version: "c4-2026-10", + granted_at: "2026-10-10T09:00:00Z", + revoked_at: null, + revocation_reason: null, + }, + }), + ); + }), + ); + + const accepted = await acceptCandidateInvitation({ + invitationId: candidateInvitationId, + csrfToken, + idempotencyKey, + body: { + expected_version: 1, + terms_version: 1, + consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] }, + }, + }); + + expect(key).toBe(idempotencyKey); + expect(body).toEqual({ + expected_version: 1, + terms_version: 1, + consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] }, + }); + expect(accepted.contact_grant?.fields).toEqual(["email"]); + }); + + it("surfaces a stale terms version as the problem code the contract names", async () => { + server.use( + http.post(`${base}/${candidateInvitationId}/accept`, () => + HttpResponse.json( + { + type: "urn:lincodex:problem:version_conflict", + title: "Version conflict", + status: 412, + code: "version_conflict", + }, + { status: 412, headers: problemHeaders }, + ), + ), + ); + + const failure = await acceptCandidateInvitation({ + invitationId: candidateInvitationId, + csrfToken, + idempotencyKey, + body: { + expected_version: 1, + terms_version: 1, + consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["phone"] }, + }, + }).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(ApiRequestError); + expect(failure).toMatchObject({ status: 412, code: "version_conflict" }); + }); + + it("sends a decline with its reason and without a comment when none was written", async () => { + let body: unknown = null; + server.use( + http.post(`${base}/${candidateInvitationId}/decline`, async ({ request }) => { + body = await request.json(); + return HttpResponse.json(candidateInvitationFixture({ state: "declined", version: 2 })); + }), + ); + + const declined = await declineCandidateInvitation({ + invitationId: candidateInvitationId, + csrfToken, + idempotencyKey, + body: { expected_version: 1, reason: "other" }, + }); + + expect(body).toEqual({ expected_version: 1, reason: "other" }); + expect(declined.state).toBe("declined"); + }); +}); diff --git a/frontend/src/entities/invitation/api/candidate-invitations.ts b/frontend/src/entities/invitation/api/candidate-invitations.ts new file mode 100644 index 0000000..8190653 --- /dev/null +++ b/frontend/src/entities/invitation/api/candidate-invitations.ts @@ -0,0 +1,131 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { + acceptMyInvitation, + declineMyInvitation, + getGetMyInvitationQueryKey, + getListMyInvitationsQueryKey, + getMyInvitation, + listMyInvitations, + viewMyInvitation, +} from "../../../shared/api/endpoints/invitation/invitation"; +import { + CandidateInvitation as candidateInvitationSchema, + CandidateInvitationList as candidateInvitationListSchema, + type CandidateInvitation, + type CandidateInvitationList, + type InvitationAcceptance, + type InvitationDeclineRequest, +} from "../../../shared/api/schemas"; + +// Transport adapters of the candidate side of an invitation. The generated +// client does not check response bodies, so every adapter parses the response +// with the generated schema: a body that does not match the contract is an +// invalid response, never a shown invitation. + +function invalidResponse(): ApiRequestError { + return new ApiRequestError({ + status: 200, + code: invalidResponseCode, + title: "The response does not match the API contract.", + }); +} + +function parseInvitation(value: unknown): CandidateInvitation { + const parsed = candidateInvitationSchema.safeParse(value); + if (!parsed.success) throw invalidResponse(); + return parsed.data; +} + +function parseInvitationList(value: unknown): CandidateInvitationList { + const parsed = candidateInvitationListSchema.safeParse(value); + if (!parsed.success) throw invalidResponse(); + return parsed.data; +} + +type CommandOptions = { + csrfToken: string; + signal?: AbortSignal | undefined; +}; + +function commandRequest(csrfToken: string, signal: AbortSignal | undefined): RequestInit { + return { headers: { "X-CSRF-Token": csrfToken }, ...(signal ? { signal } : {}) }; +} + +/** One page of the candidate's inbox, newest first; the cursor comes only from the previous page. */ +export async function listCandidateInvitations( + options: { cursor?: string | undefined; signal?: AbortSignal | undefined } = {}, +): Promise { + const params = options.cursor === undefined ? {} : { cursor: options.cursor }; + return parseInvitationList( + await listMyInvitations(params, options.signal ? { signal: options.signal } : {}), + ); +} + +/** Reads the terms of one invitation. A read never records a view and never answers it. */ +export async function readCandidateInvitation( + invitationId: string, + signal: AbortSignal | undefined = undefined, +): Promise { + return parseInvitation(await getMyInvitation(invitationId, signal ? { signal } : {})); +} + +/** + * Records that the candidate opened the terms. The server keeps the first + * view and answers with the current invitation on every repeat, so the call + * needs no Idempotency-Key. + */ +export async function viewCandidateInvitation( + invitationId: string, + options: CommandOptions, +): Promise { + return parseInvitation( + await viewMyInvitation(invitationId, commandRequest(options.csrfToken, options.signal)), + ); +} + +/** Accepts the terms version the candidate read and discloses the chosen contact kinds. */ +export async function acceptCandidateInvitation( + options: CommandOptions & { + invitationId: string; + body: InvitationAcceptance; + idempotencyKey: string; + }, +): Promise { + return parseInvitation( + await acceptMyInvitation( + options.invitationId, + options.body, + { "Idempotency-Key": options.idempotencyKey }, + commandRequest(options.csrfToken, options.signal), + ), + ); +} + +/** Declines the invitation with a structured reason and an optional comment. */ +export async function declineCandidateInvitation( + options: CommandOptions & { + invitationId: string; + body: InvitationDeclineRequest; + idempotencyKey: string; + }, +): Promise { + return parseInvitation( + await declineMyInvitation( + options.invitationId, + options.body, + { "Idempotency-Key": options.idempotencyKey }, + commandRequest(options.csrfToken, options.signal), + ), + ); +} + +/** + * Candidate reads are separate for each signed-in account, so a response for + * one account never fills another account's cache. + */ +export const candidateInvitationQueryKeys = { + /** Every inbox query of the account; invalidating it refreshes all pages. */ + inbox: (accountId: string) => [...getListMyInvitationsQueryKey(), accountId] as const, + detail: (accountId: string, invitationId: string) => + [...getGetMyInvitationQueryKey(invitationId), accountId] as const, +}; diff --git a/frontend/src/entities/invitation/index.ts b/frontend/src/entities/invitation/index.ts index 3b71037..96682a7 100644 --- a/frontend/src/entities/invitation/index.ts +++ b/frontend/src/entities/invitation/index.ts @@ -1,7 +1,8 @@ -// Public API of the invitation entity: contract-checked transport adapters -// of the organization side, the labels and formatting of terms and states, -// and the client mirror of the salary range rules. The slice holds no -// server state; features own the commands and the query cache owns reads. +// Public API of the invitation entity: contract-checked transport adapters of +// both sides, the labels and formatting of terms and states, the candidate's +// answer rules, and the client mirror of the salary range rules. The slice +// holds no server state; features own the commands and the query cache owns +// reads. export { createInvitationDraft, @@ -10,7 +11,32 @@ export { sendInvitationDraft, updateInvitationDraft, } from "./api/organization-invitations"; +export { + acceptCandidateInvitation, + candidateInvitationQueryKeys, + declineCandidateInvitation, + listCandidateInvitations, + readCandidateInvitation, + viewCandidateInvitation, +} from "./api/candidate-invitations"; export { formatRubles, formatSalaryRange, formatServerMoment } from "./model/format"; +export { + candidateInvitationStateLabels, + contactKindCodes, + contactKindLabels, + declineReasonCodes, + declineReasonLabels, + orderedContactKinds, +} from "./model/candidate-labels"; +export { candidateStatusLabel, isAnswerable, newerInvitation } from "./model/candidate-standing"; +export { bindKey, newIdempotencyKey, type KeyBinding } from "./model/command-key"; +export { useServerNow } from "./model/server-now"; +export { + describeResponseFailure, + type ResponseCommand, + type ResponseFailure, + type ResponseFailureKind, +} from "./model/response-failure"; export { communicationChannelCodes, communicationChannelLabels, diff --git a/frontend/src/entities/invitation/model/candidate-invitation.fixtures.ts b/frontend/src/entities/invitation/model/candidate-invitation.fixtures.ts new file mode 100644 index 0000000..669d78d --- /dev/null +++ b/frontend/src/entities/invitation/model/candidate-invitation.fixtures.ts @@ -0,0 +1,91 @@ +import type { + CandidateInvitation, + ContactConsentOffer, + ContactGrant, + InvitationTerms, +} from "../../../shared/api/schemas"; + +// Synthetic candidate-side invitation shaped by the contract. The fixtures are +// test inputs; they do not show what the backend returns for a real account. + +export const candidateAccountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3001"; +export const candidateInvitationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3101"; +export const candidateOrganizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3201"; +export const candidateGrantId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301"; + +/** A deadline far in the future, so the fixture stays open for every test run. */ +export const openDeadline = "2099-10-16T10:00:00Z"; +/** A deadline in the past, so the fixture reads as expired by the clock. */ +export const passedDeadline = "2020-10-16T10:00:00Z"; + +export const candidateTerms: InvitationTerms = { + role_title: "Middle Go-разработчик в команду платежей", + specialization: "backend", + grade: "middle", + offer_type: "full_time", + tasks: ["Развивать сервис выплат", "Перевести отчеты на события"], + team: "Пять бэкенд-разработчиков\nи QA-инженер", + tech_stack: ["Go", "PostgreSQL"], + work_formats: ["remote", "hybrid"], + location: "Москва", + communication_method: { channel: "video_call", details: "Созвон с тимлидом" }, + salary: { + salary_from: 100000, + salary_to: 140000, + currency: "RUB", + period: "month", + tax_basis: "net", + }, + package: { + bonus: { status: "provided", description: "Квартальная премия до 20%" }, + equipment: { status: "provided", description: "Ноутбук и монитор" }, + training: { status: "not_provided" }, + health_insurance: { status: "not_provided" }, + }, +}; + +/** The consent C4 offer: the text and the kinds the profile holds, nothing preselected. */ +export const contactConsentOffer: ContactConsentOffer = { + text: { + text_version: "c4-2026-10", + text: "Я согласен передать компании «Северный ветер» отмеченные контакты из моего профиля.\n\nСогласие относится только к этому приглашению.", + }, + available_fields: ["full_name", "email", "phone"], +}; + +export const emailOnlyGrant: ContactGrant = { + id: candidateGrantId, + fields: ["email"], + status: "active", + readable: true, + blocked_by: null, + terms_version: 1, + consent_text_version: "c4-2026-10", + granted_at: "2026-10-10T09:00:00Z", + revoked_at: null, + revocation_reason: null, +}; + +/** The invitation as the candidate reads it; the fields can be overridden per test. */ +export function candidateInvitationFixture( + overrides: Partial = {}, +): CandidateInvitation { + return { + id: candidateInvitationId, + organization: { id: candidateOrganizationId, name: "Северный ветер" }, + state: "delivered", + expiry_reason: null, + version: 1, + terms_version: 1, + terms: candidateTerms, + response_deadline_at: openDeadline, + delivered_at: "2026-10-09T10:00:00Z", + viewed_at: null, + responded_at: null, + updated_at: "2026-10-09T10:00:00Z", + contact_consent: contactConsentOffer, + decline: null, + contact_grant: null, + ...overrides, + }; +} diff --git a/frontend/src/entities/invitation/model/candidate-labels.ts b/frontend/src/entities/invitation/model/candidate-labels.ts new file mode 100644 index 0000000..b9434ae --- /dev/null +++ b/frontend/src/entities/invitation/model/candidate-labels.ts @@ -0,0 +1,70 @@ +import type { + ContactFieldKind, + InvitationDeclineReason, + InvitationState, +} from "../../../shared/api/schemas"; + +// Candidate-facing wording. The candidate reads their own state and reasons, +// so these labels say "you" where the organization side says "candidate". + +/** Decline reasons in the order the form offers them; "other" stays last. */ +export const declineReasonCodes: readonly InvitationDeclineReason[] = [ + "salary", + "tasks", + "stack", + "work_format", + "package", + "company", + "not_looking", + "other_offer", + "other", +]; + +export const declineReasonLabels: Readonly> = { + salary: "Вилка зарплаты не подходит", + tasks: "Роль или задачи не подходят", + stack: "Технологии не подходят", + work_format: "Формат работы или место не подходят", + package: "Пакет условий не подходит", + company: "Компания или сфера не подходят", + not_looking: "Сейчас я не ищу работу", + other_offer: "Я принял другое предложение", + other: "Другая причина", +}; + +/** Contact kinds in the order of the contract's ContactFieldKind. */ +export const contactKindCodes: readonly ContactFieldKind[] = [ + "full_name", + "email", + "phone", + "telegram", +]; + +export const contactKindLabels: Readonly> = { + full_name: "ФИО", + email: "Электронная почта", + phone: "Телефон", + telegram: "Telegram", +}; + +/** The kinds in contract order, so every list of them reads the same way. */ +export function orderedContactKinds(kinds: readonly ContactFieldKind[]): ContactFieldKind[] { + return contactKindCodes.filter((code) => kinds.includes(code)); +} + +export const candidateInvitationStateLabels: Readonly> = { + draft: "Черновик", + delivered: "Ждет вашего решения", + viewed: "Вы открыли условия", + counter: "Встречное предложение", + accepted: "Принято", + interview_scheduled: "Назначено интервью", + interviewed: "Интервью проведено", + negotiation: "Переговоры", + terms_agreed: "Условия согласованы", + no_deal: "Без сделки", + declined: "Вы отклонили приглашение", + expired: "Срок ответа истек", + withdrawn: "Компания отозвала приглашение", + cancelled_by_candidate: "Вы отменили участие", +}; diff --git a/frontend/src/entities/invitation/model/candidate-standing.test.ts b/frontend/src/entities/invitation/model/candidate-standing.test.ts new file mode 100644 index 0000000..1d63d23 --- /dev/null +++ b/frontend/src/entities/invitation/model/candidate-standing.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { candidateInvitationFixture, openDeadline, passedDeadline } from "../testing"; +import { candidateStatusLabel, isAnswerable, newerInvitation } from "./candidate-standing"; + +const beforeDeadline = Date.parse("2026-10-10T10:00:00Z"); +const deadlineMs = Date.parse(openDeadline); +const afterDeadline = deadlineMs + 1_000; + +describe("candidate answer window", () => { + it.each(["delivered", "viewed"] as const)( + "is open for a %s invitation before the deadline", + (state) => { + expect(isAnswerable({ state, response_deadline_at: openDeadline }, beforeDeadline)).toBe( + true, + ); + }, + ); + + it("closes at the deadline itself and after it, by the server clock", () => { + expect( + isAnswerable({ state: "delivered", response_deadline_at: openDeadline }, deadlineMs), + ).toBe(false); + expect( + isAnswerable({ state: "delivered", response_deadline_at: openDeadline }, afterDeadline), + ).toBe(false); + }); + + it.each(["accepted", "declined", "expired", "withdrawn", "cancelled_by_candidate"] as const)( + "is closed for a %s invitation whatever the clock says", + (state) => { + expect(isAnswerable({ state, response_deadline_at: openDeadline }, beforeDeadline)).toBe( + false, + ); + }, + ); + + it("reads a delivered invitation past its deadline as expired", () => { + const invitation = candidateInvitationFixture({ response_deadline_at: passedDeadline }); + expect(candidateStatusLabel(invitation, beforeDeadline)).toBe("Срок ответа истек"); + }); + + it("names the stored state of a closed invitation", () => { + const invitation = candidateInvitationFixture({ state: "declined" }); + expect(candidateStatusLabel(invitation, beforeDeadline)).toBe("Вы отклонили приглашение"); + }); +}); + +describe("newer invitation", () => { + it("keeps the higher version, so a late answer never overwrites a newer one", () => { + const accepted = candidateInvitationFixture({ state: "accepted", version: 3 }); + const viewed = candidateInvitationFixture({ state: "viewed", version: 2 }); + expect(newerInvitation(accepted, viewed)).toBe(accepted); + expect(newerInvitation(viewed, accepted)).toBe(accepted); + }); + + it("takes the incoming invitation when nothing is cached or the id differs", () => { + const incoming = candidateInvitationFixture({ version: 2 }); + expect(newerInvitation(undefined, incoming)).toBe(incoming); + const other = candidateInvitationFixture({ + id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3999", + version: 9, + }); + expect(newerInvitation(other, incoming)).toBe(incoming); + }); +}); diff --git a/frontend/src/entities/invitation/model/candidate-standing.ts b/frontend/src/entities/invitation/model/candidate-standing.ts new file mode 100644 index 0000000..abbb7e0 --- /dev/null +++ b/frontend/src/entities/invitation/model/candidate-standing.ts @@ -0,0 +1,46 @@ +import type { CandidateInvitation } from "../../../shared/api/schemas"; +import { candidateInvitationStateLabels } from "./candidate-labels"; + +/** + * Whether the candidate can still answer: the state allows an answer and the + * deadline has not passed. The clock is the server's, so a device clock that + * is minutes off does not open or close the answer window. + */ +export function isAnswerable( + invitation: Pick, + serverNowMs: number, +): boolean { + if (invitation.state !== "delivered" && invitation.state !== "viewed") return false; + const deadline = Date.parse(invitation.response_deadline_at); + return Number.isFinite(deadline) && deadline > serverNowMs; +} + +/** + * The status line for the candidate. A delivered or viewed invitation whose + * deadline has passed reads as expired even before the server applies the + * expiry on the next read. + */ +export function candidateStatusLabel( + invitation: Pick, + serverNowMs: number, +): string { + if ( + (invitation.state === "delivered" || invitation.state === "viewed") && + !isAnswerable(invitation, serverNowMs) + ) { + return candidateInvitationStateLabels.expired; + } + return candidateInvitationStateLabels[invitation.state]; +} + +/** + * Keeps the newer of two reads of one invitation. Every command answers with + * the invitation after it, and a late answer must never overwrite a newer one. + */ +export function newerInvitation( + current: CandidateInvitation | undefined, + incoming: CandidateInvitation, +): CandidateInvitation { + if (!current || current.id !== incoming.id) return incoming; + return current.version > incoming.version ? current : incoming; +} diff --git a/frontend/src/entities/invitation/model/command-key.test.ts b/frontend/src/entities/invitation/model/command-key.test.ts new file mode 100644 index 0000000..850cfad --- /dev/null +++ b/frontend/src/entities/invitation/model/command-key.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { bindKey, newIdempotencyKey } from "./command-key"; + +describe("idempotency keys of an answer", () => { + it("keeps the key of an unchanged request, so a retry replays the same answer", () => { + const first = bindKey(null, "invitation:body"); + expect(bindKey(first, "invitation:body")).toBe(first); + }); + + it("issues a new key when the request changes", () => { + const first = bindKey(null, "invitation:email"); + const second = bindKey(first, "invitation:email,phone"); + expect(second.fingerprint).toBe("invitation:email,phone"); + expect(second.key).not.toBe(first.key); + }); + + it("issues random keys that the contract accepts", () => { + const key = newIdempotencyKey(); + expect(key).toMatch(/^[A-Za-z0-9._:-]{1,255}$/); + expect(newIdempotencyKey()).not.toBe(key); + }); +}); diff --git a/frontend/src/entities/invitation/model/command-key.ts b/frontend/src/entities/invitation/model/command-key.ts new file mode 100644 index 0000000..5571c4b --- /dev/null +++ b/frontend/src/entities/invitation/model/command-key.ts @@ -0,0 +1,25 @@ +// Idempotency bookkeeping of a candidate's answer. The key belongs to the +// request it protects: a repeated click or a retry after a lost response +// sends the same key with the same body, so the server replays the stored +// answer instead of recording a second one. A changed body gets a new key, +// because the server would answer 422 for the old key with another body. + +/** An Idempotency-Key and the request fingerprint it was issued for. */ +export interface KeyBinding { + readonly fingerprint: string; + readonly key: string; +} + +export function newIdempotencyKey(): string { + if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") { + throw new Error("Secure random key generation is unavailable."); + } + return crypto.randomUUID(); +} + +/** Keeps the previous key while the fingerprint stays the same; otherwise issues a new one. */ +export function bindKey(previous: KeyBinding | null, fingerprint: string): KeyBinding { + return previous?.fingerprint === fingerprint + ? previous + : { fingerprint, key: newIdempotencyKey() }; +} diff --git a/frontend/src/entities/invitation/model/response-failure.test.ts b/frontend/src/entities/invitation/model/response-failure.test.ts new file mode 100644 index 0000000..6ce9286 --- /dev/null +++ b/frontend/src/entities/invitation/model/response-failure.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { describeResponseFailure } from "./response-failure"; + +function problem(status: number, code: string, pointer?: string): ApiRequestError { + return new ApiRequestError({ + status, + code: code as ApiRequestError["code"], + title: "Problem", + fieldErrors: pointer ? [{ in: "body", pointer, code: "invalid", message: "Invalid." }] : [], + }); +} + +describe("describing a failed answer", () => { + it("treats a stale version as a reason to read the invitation again, for both 412 and 409", () => { + for (const error of [problem(412, "version_conflict"), problem(409, "version_conflict")]) { + const failure = describeResponseFailure("accept", error); + expect(failure).toMatchObject({ kind: "stale-terms", refresh: true }); + expect(failure.message).toContain("Приглашение изменилось"); + } + }); + + it("shows the final state for a state conflict instead of a retry", () => { + expect(describeResponseFailure("accept", problem(409, "state_conflict"))).toMatchObject({ + kind: "final-state", + refresh: true, + }); + }); + + it("keeps the same key for an outcome that is unknown or temporary", () => { + const retryable = [ + new ApiRequestError({ status: 0, code: "network_error", title: "" }), + problem(500, "internal"), + new ApiRequestError({ status: 200, code: invalidResponseCode, title: "" }), + problem(409, "idempotency_in_progress"), + problem(429, "rate_limited"), + new TypeError("not an API error"), + ]; + for (const error of retryable) { + expect(describeResponseFailure("decline", error)).toMatchObject({ + kind: "retry", + refresh: false, + }); + } + }); + + it("sends a consent pointer to the offer, and any other validation error to the page", () => { + expect( + describeResponseFailure("accept", problem(400, "validation_failed", "/consent_c4/fields/1")), + ).toMatchObject({ kind: "consent", refresh: true }); + expect( + describeResponseFailure("accept", problem(400, "validation_failed", "/terms/salary")), + ).toMatchObject({ kind: "blocked", refresh: true }); + }); + + it("separates the session, CSRF, and missing-invitation cases", () => { + expect(describeResponseFailure("accept", problem(403, "csrf_check_failed"))).toMatchObject({ + kind: "csrf", + refresh: true, + }); + expect(describeResponseFailure("accept", problem(403, "forbidden"))).toMatchObject({ + kind: "access", + refresh: true, + }); + expect(describeResponseFailure("decline", problem(404, "not_found"))).toMatchObject({ + kind: "not-found", + refresh: true, + }); + }); + + it("never shows server text: the messages are the product's own", () => { + const failure = describeResponseFailure("decline", problem(500, "internal")); + expect(failure.message).toContain("Сервер не подтвердил результат"); + expect(failure.message).toContain("тем же ключом"); + }); +}); diff --git a/frontend/src/entities/invitation/model/response-failure.ts b/frontend/src/entities/invitation/model/response-failure.ts new file mode 100644 index 0000000..d9d4ab0 --- /dev/null +++ b/frontend/src/entities/invitation/model/response-failure.ts @@ -0,0 +1,119 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; + +/** The candidate's answers that can fail: accepting with the consent C4, or declining. */ +export type ResponseCommand = "accept" | "decline"; + +/** + * What the candidate sees after a failed answer. + * + * - stale-terms: the terms version or the version of the invitation changed + * (412, or 409 with `version_conflict`); the new version must be read and + * decided again. + * - final-state: the invitation has ended (409 `state_conflict`), for example + * it expired at the deadline; the final state is shown instead of a retry. + * - retry: the outcome is unknown or temporary; the same control repeats the + * command with the same Idempotency-Key. + * - consent: the text version or a selected kind no longer matches the profile + * (400 with a `/consent_c4` pointer); the offer is read again. + * - access, csrf, not-found, blocked: the page reads the invitation again or + * explains why the answer cannot be sent. + */ +export type ResponseFailureKind = + "stale-terms" | "final-state" | "retry" | "consent" | "access" | "csrf" | "not-found" | "blocked"; + +export interface ResponseFailure { + readonly kind: ResponseFailureKind; + readonly message: string; + /** Whether the page reads the invitation again before the next decision. */ + readonly refresh: boolean; +} + +const sameKeyHint = "Повторите нажатие: запрос уйдет с тем же ключом и не создаст второй ответ."; + +/** Describes a failed answer without showing any server text or value. */ +export function describeResponseFailure(command: ResponseCommand, error: unknown): ResponseFailure { + if (!(error instanceof ApiRequestError)) { + return { kind: "retry", message: `Не удалось отправить ответ. ${sameKeyHint}`, refresh: false }; + } + if (error.status === 0 || error.status >= 500 || error.code === invalidResponseCode) { + return { + kind: "retry", + message: `Сервер не подтвердил результат. ${sameKeyHint}`, + refresh: false, + }; + } + if (error.status === 412 || (error.status === 409 && error.code === "version_conflict")) { + return { + kind: "stale-terms", + message: + command === "accept" + ? "Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и выбор контактов и подтвердите согласие заново." + : "Приглашение изменилось в другом окне. Мы загрузили его текущую версию: проверьте ответ и отправьте его снова.", + refresh: true, + }; + } + if (error.status === 409 && error.code === "state_conflict") { + return { + kind: "final-state", + message: + "Приглашение уже завершилось, поэтому ответ не сохранен. Мы обновили его состояние ниже.", + refresh: true, + }; + } + if (error.status === 409 && error.code === "idempotency_in_progress") { + return { + kind: "retry", + message: `Предыдущий ответ еще обрабатывается. Подождите несколько секунд. ${sameKeyHint}`, + refresh: false, + }; + } + if (error.status === 403 && error.code === "csrf_check_failed") { + return { + kind: "csrf", + message: "Проверка входа устарела. Мы обновили ее; повторите ответ.", + refresh: true, + }; + } + if (error.status === 401 || error.status === 403) { + return { + kind: "access", + message: + "Нет доступа к этому приглашению. Обновите страницу; если вход истек, войдите снова.", + refresh: true, + }; + } + if (error.status === 404) { + return { + kind: "not-found", + message: "Приглашение не найдено. Возможно, оно уже недоступно.", + refresh: true, + }; + } + if (error.status === 400) { + if (error.fieldErrors.some((field) => field.pointer.startsWith("/consent_c4"))) { + return { + kind: "consent", + message: + "Текст согласия или список контактов изменились. Мы обновили приглашение: проверьте выбор и подтвердите его заново.", + refresh: true, + }; + } + return { + kind: "blocked", + message: "Сервер не принял ответ. Обновите страницу и проверьте приглашение.", + refresh: true, + }; + } + if (error.status === 429) { + return { + kind: "retry", + message: `Слишком много запросов. Подождите немного. ${sameKeyHint}`, + refresh: false, + }; + } + return { + kind: "blocked", + message: "Сервер отклонил ответ. Обновите страницу и проверьте состояние приглашения.", + refresh: true, + }; +} diff --git a/frontend/src/entities/invitation/model/server-now.ts b/frontend/src/entities/invitation/model/server-now.ts new file mode 100644 index 0000000..b354802 --- /dev/null +++ b/frontend/src/entities/invitation/model/server-now.ts @@ -0,0 +1,24 @@ +import { useEffect, useState } from "react"; +import { toServerTime } from "../../../shared/api"; + +/** How often the deadline status is recomputed while a screen stays open. */ +const refreshIntervalMs = 30_000; + +/** + * The current server time in milliseconds, refreshed on an interval. The + * answer window closes at a server deadline, so a screen left open must notice + * the deadline passing without a reload; the device clock is corrected by the + * offset learned from response Date headers. + */ +export function useServerNow(): number { + const [now, setNow] = useState(() => toServerTime(Date.now())); + + useEffect(() => { + const timer = window.setInterval(() => { + setNow(toServerTime(Date.now())); + }, refreshIntervalMs); + return () => window.clearInterval(timer); + }, []); + + return now; +} diff --git a/frontend/src/entities/invitation/testing.ts b/frontend/src/entities/invitation/testing.ts new file mode 100644 index 0000000..46ad92e --- /dev/null +++ b/frontend/src/entities/invitation/testing.ts @@ -0,0 +1,17 @@ +// Test-only entry of the invitation entity. Tests of the layers above import +// the candidate-side fixtures from here. The fixtures are inputs, not evidence +// about the backend. The lint configuration lets only test files import this +// file, so production code cannot reach it. + +export { + candidateAccountId, + candidateGrantId, + candidateInvitationFixture, + candidateInvitationId, + candidateOrganizationId, + candidateTerms, + contactConsentOffer, + emailOnlyGrant, + openDeadline, + passedDeadline, +} from "./model/candidate-invitation.fixtures"; diff --git a/frontend/src/features/accept-contact-consent/index.ts b/frontend/src/features/accept-contact-consent/index.ts new file mode 100644 index 0000000..d737752 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/index.ts @@ -0,0 +1,5 @@ +// Public API of the accept-contact-consent feature: the candidate's acceptance +// of an invitation's current terms with the consent C4, with the contact kinds +// chosen one by one. The page reacts to the outcome and reads the invitation again. + +export { AcceptContactConsentForm } from "./ui/accept-contact-consent-form"; diff --git a/frontend/src/features/accept-contact-consent/model/accept-command.test.ts b/frontend/src/features/accept-contact-consent/model/accept-command.test.ts new file mode 100644 index 0000000..90601e2 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/model/accept-command.test.ts @@ -0,0 +1,126 @@ +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import type { InvitationAcceptance } from "../../../shared/api/schemas"; +import { + candidateInvitationFixture, + candidateInvitationId, +} from "../../../entities/invitation/testing"; +import { runAcceptCommand } from "./accept-command"; + +const url = `http://localhost/api/v1/me/invitations/${candidateInvitationId}/accept`; +const csrfToken = "A".repeat(43); + +const emailBody: InvitationAcceptance = { + expected_version: 1, + terms_version: 1, + consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] }, +}; +const emailAndPhoneBody: InvitationAcceptance = { + ...emailBody, + consent_c4: { ...emailBody.consent_c4, fields: ["email", "phone"] }, +}; + +const server = setupServer(); +beforeAll(() => server.listen({ onUnhandledFrame: "error" })); +beforeEach(() => { + const realFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + realFetch(new URL(input, "http://localhost"), init), + ); +}); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +/** + * A fake of the accept endpoint with the replay rule of the contract: a key + * that was already used with the same body replays the stored answer, and + * `loseFirstResponse` drops the answer of the first request after the server + * recorded it. + */ +function fakeAccept(options: { loseFirstResponse?: boolean; status?: number } = {}) { + const keys: (string | null)[] = []; + let recorded = false; + let lose = options.loseFirstResponse ?? false; + server.use( + http.post(url, async ({ request }) => { + keys.push(request.headers.get("Idempotency-Key")); + await request.json(); + if (options.status) { + return HttpResponse.json( + { + type: "urn:lincodex:problem:state_conflict", + title: "State", + status: options.status, + code: "state_conflict", + }, + { status: options.status, headers: { "Content-Type": "application/problem+json" } }, + ); + } + recorded = true; + if (lose) { + lose = false; + return HttpResponse.error(); + } + return HttpResponse.json(candidateInvitationFixture({ state: "accepted", version: 2 })); + }), + ); + return { keys, wasRecorded: () => recorded }; +} + +const request = (body: InvitationAcceptance) => ({ + invitationId: candidateInvitationId, + csrfToken, + body, +}); + +describe("accept command", () => { + it("accepts the chosen contacts with the CSRF token and returns the invitation", async () => { + const fake = fakeAccept(); + + const outcome = await runAcceptCommand(request(emailBody), null); + + expect(outcome.kind).toBe("accepted"); + expect(fake.keys).toHaveLength(1); + expect(fake.keys[0]).toBeTruthy(); + }); + + it("repeats the same key after a lost response, so the server records one answer", async () => { + const fake = fakeAccept({ loseFirstResponse: true }); + + const first = await runAcceptCommand(request(emailBody), null); + expect(first.kind).toBe("failed"); + if (first.kind !== "failed") throw new Error("expected a failure"); + expect(fake.wasRecorded()).toBe(true); + + const retry = await runAcceptCommand(request(emailBody), first.key); + + expect(retry.kind).toBe("accepted"); + expect(fake.keys[1]).toBe(fake.keys[0]); + }); + + it("gives a changed choice a new key rather than replaying the old body", async () => { + const fake = fakeAccept({ loseFirstResponse: true }); + const first = await runAcceptCommand(request(emailBody), null); + if (first.kind !== "failed") throw new Error("expected a failure"); + + await runAcceptCommand(request(emailAndPhoneBody), first.key); + + expect(fake.keys[1]).not.toBe(fake.keys[0]); + }); + + it("returns the state conflict as a failure with its problem code", async () => { + fakeAccept({ status: 409 }); + + const outcome = await runAcceptCommand(request(emailBody), null); + + expect(outcome.kind).toBe("failed"); + if (outcome.kind !== "failed") throw new Error("expected a failure"); + expect(outcome.error).toBeInstanceOf(ApiRequestError); + expect(outcome.error).toMatchObject({ status: 409, code: "state_conflict" }); + }); +}); diff --git a/frontend/src/features/accept-contact-consent/model/accept-command.ts b/frontend/src/features/accept-contact-consent/model/accept-command.ts new file mode 100644 index 0000000..3d337cf --- /dev/null +++ b/frontend/src/features/accept-contact-consent/model/accept-command.ts @@ -0,0 +1,41 @@ +import { acceptCandidateInvitation, bindKey, type KeyBinding } from "../../../entities/invitation"; +import type { CandidateInvitation, InvitationAcceptance } from "../../../shared/api/schemas"; + +export interface AcceptRequest { + readonly invitationId: string; + readonly csrfToken: string; + readonly body: InvitationAcceptance; +} + +export type AcceptOutcome = + | { readonly kind: "accepted"; readonly invitation: CandidateInvitation } + | { + readonly kind: "failed"; + readonly error: unknown; + /** The key of this attempt; the next attempt of the same choice repeats it. */ + readonly key: KeyBinding; + }; + +/** + * Sends one acceptance and never throws for a request failure. The key is + * bound to the invitation and the whole body, so a repeated click or a retry + * after a lost response replays the same answer, while a changed choice or a + * new terms version gets a new key. + */ +export async function runAcceptCommand( + request: AcceptRequest, + previous: KeyBinding | null, +): Promise { + const key = bindKey(previous, JSON.stringify([request.invitationId, request.body])); + try { + const invitation = await acceptCandidateInvitation({ + invitationId: request.invitationId, + csrfToken: request.csrfToken, + body: request.body, + idempotencyKey: key.key, + }); + return { kind: "accepted", invitation }; + } catch (error: unknown) { + return { kind: "failed", error, key }; + } +} diff --git a/frontend/src/features/accept-contact-consent/model/accept-draft.test.ts b/frontend/src/features/accept-contact-consent/model/accept-draft.test.ts new file mode 100644 index 0000000..5e441a6 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/model/accept-draft.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; +import { contactConsentOffer } from "../../../entities/invitation/testing"; +import { + acceptReady, + acceptanceBody, + consentParagraphs, + emptyAcceptDraft, + setAcceptConfirmed, + toggleAcceptField, +} from "./accept-draft"; + +describe("accept draft", () => { + it("starts with nothing chosen, so no kind is preselected and the send is not ready", () => { + expect(emptyAcceptDraft).toEqual({ fields: [], confirmed: false }); + expect(acceptReady(emptyAcceptDraft, contactConsentOffer)).toBe(false); + }); + + it("chooses each contact kind separately and keeps the contract order", () => { + let draft = toggleAcceptField(emptyAcceptDraft, "phone", true); + draft = toggleAcceptField(draft, "email", true); + expect(draft.fields).toEqual(["email", "phone"]); + + draft = toggleAcceptField(draft, "email", false); + expect(draft.fields).toEqual(["phone"]); + expect(toggleAcceptField(draft, "phone", true).fields).toEqual(["phone"]); + }); + + it("is ready only with the explicit confirmation and at least one offered kind", () => { + const chosen = toggleAcceptField(emptyAcceptDraft, "email", true); + expect(acceptReady(chosen, contactConsentOffer)).toBe(false); + expect(acceptReady(setAcceptConfirmed(chosen, true), contactConsentOffer)).toBe(true); + expect(acceptReady(setAcceptConfirmed(emptyAcceptDraft, true), contactConsentOffer)).toBe( + false, + ); + }); + + it("never sends a kind that the profile did not offer", () => { + const draft = setAcceptConfirmed({ fields: ["telegram"], confirmed: true }, true); + expect(acceptReady(draft, contactConsentOffer)).toBe(false); + }); + + it("builds the body from the versions the candidate read, the consent text version, and the chosen kinds only", () => { + const draft = setAcceptConfirmed(toggleAcceptField(emptyAcceptDraft, "email", true), true); + expect( + acceptanceBody({ expectedVersion: 3, termsVersion: 2, offer: contactConsentOffer, draft }), + ).toEqual({ + expected_version: 3, + terms_version: 2, + consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] }, + }); + }); + + it("splits the consent text into paragraphs at empty lines", () => { + expect(consentParagraphs("Первый абзац.\n\nВторой абзац.\n \nТретий.")).toEqual([ + "Первый абзац.", + "Второй абзац.", + "Третий.", + ]); + }); +}); diff --git a/frontend/src/features/accept-contact-consent/model/accept-draft.ts b/frontend/src/features/accept-contact-consent/model/accept-draft.ts new file mode 100644 index 0000000..f8ecf26 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/model/accept-draft.ts @@ -0,0 +1,76 @@ +import type { + ContactConsentOffer, + ContactFieldKind, + InvitationAcceptance, +} from "../../../shared/api/schemas"; +import { orderedContactKinds } from "../../../entities/invitation"; + +// The candidate's choice on the consent form. Nothing is preselected: the +// draft starts with no kind and an unchecked confirmation, and a new terms +// version starts a new draft, because the candidate decides on the new terms. + +export interface AcceptDraft { + readonly fields: readonly ContactFieldKind[]; + readonly confirmed: boolean; +} + +export const emptyAcceptDraft: AcceptDraft = { fields: [], confirmed: false }; + +/** Adds or removes one contact kind; the list keeps the contract order and never repeats a kind. */ +export function toggleAcceptField( + draft: AcceptDraft, + kind: ContactFieldKind, + checked: boolean, +): AcceptDraft { + const others = draft.fields.filter((item) => item !== kind); + return { ...draft, fields: checked ? orderedContactKinds([...others, kind]) : others }; +} + +export function setAcceptConfirmed(draft: AcceptDraft, confirmed: boolean): AcceptDraft { + return { ...draft, confirmed }; +} + +/** + * Whether the acceptance may be sent: the explicit confirmation is given, at + * least one kind is chosen, and every chosen kind is one the profile holds. + */ +export function acceptReady(draft: AcceptDraft, offer: ContactConsentOffer): boolean { + return ( + draft.confirmed && + draft.fields.length > 0 && + draft.fields.every((kind) => offer.available_fields.includes(kind)) + ); +} + +/** + * The request body. It names the terms version and the invitation version + * that the candidate read, and the text version of the consent they saw. It + * never carries contact values. + */ +export function acceptanceBody(input: { + readonly expectedVersion: number; + readonly termsVersion: number; + readonly offer: ContactConsentOffer; + readonly draft: AcceptDraft; +}): InvitationAcceptance { + return { + expected_version: input.expectedVersion, + terms_version: input.termsVersion, + consent_c4: { + text_version: input.offer.text.text_version, + accepted: true, + fields: [...input.draft.fields], + }, + }; +} + +/** + * The consent text as paragraphs. The contract separates paragraphs with an + * empty line; the text is shown as text, never as HTML. + */ +export function consentParagraphs(text: string): string[] { + return text + .split(/\n\s*\n/) + .map((paragraph) => paragraph.trim()) + .filter((paragraph) => paragraph.length > 0); +} diff --git a/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css new file mode 100644 index 0000000..96d5ad2 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.module.css @@ -0,0 +1,127 @@ +.form { + display: grid; + gap: var(--space-4); + min-width: 0; + padding: var(--space-4); + border: var(--line-strong) solid var(--color-accent); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.title { + font-size: var(--font-size-l); + font-weight: var(--font-weight-bold); +} + +.fieldset { + display: grid; + gap: var(--space-2); + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} + +.legend { + padding: 0; + margin-bottom: var(--space-2); + font-weight: var(--font-weight-bold); +} + +.subtitle { + font-size: var(--font-size-s); + font-weight: var(--font-weight-bold); +} + +.hint { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.consent { + display: grid; + gap: var(--space-2); + min-width: 0; +} + +.text { + display: grid; + gap: var(--space-2); + max-height: 16rem; + overflow-y: auto; + padding: var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-canvas); + color: var(--color-text); + line-height: var(--line-height-body); + overflow-wrap: anywhere; +} + +.text p { + margin: 0; +} + +.option { + display: flex; + align-items: flex-start; + gap: var(--space-3); + min-height: 2.75rem; + min-width: 0; + padding: var(--space-2) var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-surface); + line-height: var(--line-height-body); + cursor: pointer; +} + +.option input { + flex: none; + width: 1.25rem; + height: 1.25rem; + margin: 0.2rem 0 0; + accent-color: var(--color-accent); +} + +.option span { + min-width: 0; + overflow-wrap: anywhere; +} + +.option:has(input:focus-visible) { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.alert { + padding: var(--space-3); + border: var(--line-strong) solid var(--color-danger); + border-radius: var(--radius-s); + background: var(--color-surface); + color: var(--color-text); + line-height: var(--line-height-body); +} + +.alert:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.submit { + width: 100%; +} + +@media (width >= 36rem) { + .submit { + width: auto; + } +} diff --git a/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.test.tsx b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.test.tsx new file mode 100644 index 0000000..939d111 --- /dev/null +++ b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.test.tsx @@ -0,0 +1,50 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + candidateInvitationFixture, + contactConsentOffer, +} from "../../../entities/invitation/testing"; +import { AcceptContactConsentForm } from "./accept-contact-consent-form"; + +function render(): string { + return renderToStaticMarkup( + undefined} + onFailure={() => undefined} + />, + ); +} + +describe("accept contact consent form", () => { + it("offers each kind the profile holds as a separate, unchecked choice", () => { + const html = render(); + + for (const label of ["ФИО", "Электронная почта", "Телефон"]) { + expect(html).toContain(`${label}`); + } + expect(html).not.toContain("Telegram"); + expect(html.match(/type="checkbox"/g)).toHaveLength(4); + expect(html).not.toMatch(/checked=""/); + }); + + it("shows the consent text as paragraphs and the organization in the confirmation", () => { + const html = render(); + + expect(html).toContain("

Я согласен передать компании «Северный ветер» отмеченные контакты"); + expect(html).toContain("

Согласие относится только к этому приглашению.

"); + expect(html).toContain("Я прочитал(а) текст согласия и согласен(на) передать"); + }); + + it("is not ready to send until a kind and the confirmation are chosen", () => { + const html = render(); + + expect(html).toMatch( + /]*aria-disabled="true"[^>]*>Принять и передать контакты<\/button>/, + ); + expect(html).not.toContain('role="alert"'); + }); +}); diff --git a/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.tsx b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.tsx new file mode 100644 index 0000000..2fd85da --- /dev/null +++ b/frontend/src/features/accept-contact-consent/ui/accept-contact-consent-form.tsx @@ -0,0 +1,191 @@ +import { useEffect, useId, useRef, useState, type FormEvent } from "react"; +import { + contactKindLabels, + describeResponseFailure, + orderedContactKinds, + type KeyBinding, + type ResponseFailure, +} from "../../../entities/invitation"; +import type { CandidateInvitation, ContactConsentOffer } from "../../../shared/api/schemas"; +import { Button } from "../../../shared/ui"; +import { + acceptReady, + acceptanceBody, + consentParagraphs, + emptyAcceptDraft, + setAcceptConfirmed, + toggleAcceptField, + type AcceptDraft, +} from "../model/accept-draft"; +import { runAcceptCommand } from "../model/accept-command"; +import styles from "./accept-contact-consent-form.module.css"; + +type AcceptContactConsentFormProps = { + /** The invitation whose current terms version the candidate is deciding on. */ + invitation: CandidateInvitation; + /** The consent C4 offer of that version: the text and the kinds the profile holds. */ + offer: ContactConsentOffer; + organizationName: string; + csrfToken: string; + onAccepted: (invitation: CandidateInvitation) => void; + onFailure: (failure: ResponseFailure) => void; +}; + +/** + * Accepts the terms with the consent C4. Nothing is preselected: the + * candidate ticks each contact kind they agree to disclose and confirms the + * text, and only then can the answer be sent. The form is keyed by the terms + * version by its parent, so a new version starts with an empty choice. + */ +export function AcceptContactConsentForm({ + invitation, + offer, + organizationName, + csrfToken, + onAccepted, + onFailure, +}: AcceptContactConsentFormProps) { + const id = useId(); + const [draft, setDraft] = useState(emptyAcceptDraft); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + const [hint, setHint] = useState(null); + const inFlight = useRef(false); + const keyRef = useRef(null); + const alertRef = useRef(null); + const ready = acceptReady(draft, offer); + const paragraphs = consentParagraphs(offer.text.text); + const kinds = orderedContactKinds(offer.available_fields); + + useEffect(() => { + if (failure) alertRef.current?.focus(); + }, [failure]); + + function submit(event: FormEvent) { + event.preventDefault(); + if (inFlight.current) return; + if (!ready) { + setHint( + "Отметьте хотя бы один контакт и подтвердите согласие: без этого приглашение не принимается.", + ); + return; + } + inFlight.current = true; + setBusy(true); + setFailure(null); + setHint(null); + const body = acceptanceBody({ + expectedVersion: invitation.version, + termsVersion: invitation.terms_version, + offer, + draft, + }); + void runAcceptCommand({ invitationId: invitation.id, csrfToken, body }, keyRef.current).then( + (outcome) => { + inFlight.current = false; + if (outcome.kind === "accepted") { + keyRef.current = null; + onAccepted(outcome.invitation); + return; + } + keyRef.current = outcome.key; + setBusy(false); + const described = describeResponseFailure("accept", outcome.error); + setFailure(described); + onFailure(described); + }, + ); + } + + return ( +
+

+ Принять приглашение +

+ +
+ Контакты, которые получит компания +

+ Ничего не отмечено заранее. Отметьте только те контакты, которые компания сможет прочитать + после принятия. Остальные не передаются. +

+ {kinds.map((kind) => ( + + ))} +
+ +
+ +
+ {paragraphs.map((paragraph, index) => ( + // The consent text is static for the lifetime of this form. +

{paragraph}

+ ))} +
+
+ + + +

+ Кнопка станет доступна, когда отмечен хотя бы один контакт и подтверждено согласие. +

+ + {hint ? ( +

+ {hint} +

+ ) : null} + + {failure ? ( +
+ {failure.message} +
+ ) : null} + +
+ +
+
+ ); +} diff --git a/frontend/src/features/respond-invitation/index.ts b/frontend/src/features/respond-invitation/index.ts new file mode 100644 index 0000000..897817c --- /dev/null +++ b/frontend/src/features/respond-invitation/index.ts @@ -0,0 +1,5 @@ +// Public API of the respond-invitation feature: the candidate's decline of an +// invitation with a structured reason and an optional comment. The page reacts +// to the outcome and reads the invitation again. + +export { DeclineInvitationForm } from "./ui/decline-invitation-form"; diff --git a/frontend/src/features/respond-invitation/model/decline-command.test.ts b/frontend/src/features/respond-invitation/model/decline-command.test.ts new file mode 100644 index 0000000..fe15564 --- /dev/null +++ b/frontend/src/features/respond-invitation/model/decline-command.test.ts @@ -0,0 +1,70 @@ +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { InvitationDeclineRequest } from "../../../shared/api/schemas"; +import { + candidateInvitationFixture, + candidateInvitationId, +} from "../../../entities/invitation/testing"; +import { runDeclineCommand } from "./decline-command"; + +const url = `http://localhost/api/v1/me/invitations/${candidateInvitationId}/decline`; + +const server = setupServer(); +beforeAll(() => server.listen({ onUnhandledFrame: "error" })); +beforeEach(() => { + const realFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + realFetch(new URL(input, "http://localhost"), init), + ); +}); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +describe("decline command", () => { + it("declines with the reason only and reads the declined invitation back", async () => { + const bodies: unknown[] = []; + server.use( + http.post(url, async ({ request }) => { + bodies.push(await request.json()); + return HttpResponse.json(candidateInvitationFixture({ state: "declined", version: 2 })); + }), + ); + const body: InvitationDeclineRequest = { expected_version: 1, reason: "other" }; + + const outcome = await runDeclineCommand( + { invitationId: candidateInvitationId, csrfToken: "A".repeat(43), body }, + null, + ); + + expect(bodies).toEqual([{ expected_version: 1, reason: "other" }]); + expect(outcome.kind).toBe("declined"); + if (outcome.kind !== "declined") throw new Error("expected a decline"); + expect(outcome.invitation.state).toBe("declined"); + }); + + it("keeps the failure key so that a retry of the same answer replays it", async () => { + const keys: (string | null)[] = []; + server.use( + http.post(url, ({ request }) => { + keys.push(request.headers.get("Idempotency-Key")); + return HttpResponse.error(); + }), + ); + const request = { + invitationId: candidateInvitationId, + csrfToken: "A".repeat(43), + body: { expected_version: 1, reason: "salary" } as const, + }; + + const first = await runDeclineCommand(request, null); + if (first.kind !== "failed") throw new Error("expected a failure"); + await runDeclineCommand(request, first.key); + + expect(keys).toHaveLength(2); + expect(keys[1]).toBe(keys[0]); + }); +}); diff --git a/frontend/src/features/respond-invitation/model/decline-command.ts b/frontend/src/features/respond-invitation/model/decline-command.ts new file mode 100644 index 0000000..21fdabd --- /dev/null +++ b/frontend/src/features/respond-invitation/model/decline-command.ts @@ -0,0 +1,40 @@ +import { bindKey, declineCandidateInvitation, type KeyBinding } from "../../../entities/invitation"; +import type { CandidateInvitation, InvitationDeclineRequest } from "../../../shared/api/schemas"; + +export interface DeclineRequest { + readonly invitationId: string; + readonly csrfToken: string; + readonly body: InvitationDeclineRequest; +} + +export type DeclineOutcome = + | { readonly kind: "declined"; readonly invitation: CandidateInvitation } + | { + readonly kind: "failed"; + readonly error: unknown; + /** The key of this attempt; the next attempt of the same answer repeats it. */ + readonly key: KeyBinding; + }; + +/** + * Sends one decline and never throws for a request failure. The key is bound + * to the invitation and the whole body, so a retry of the same answer replays + * it and a changed answer gets a new key. + */ +export async function runDeclineCommand( + request: DeclineRequest, + previous: KeyBinding | null, +): Promise { + const key = bindKey(previous, JSON.stringify([request.invitationId, request.body])); + try { + const invitation = await declineCandidateInvitation({ + invitationId: request.invitationId, + csrfToken: request.csrfToken, + body: request.body, + idempotencyKey: key.key, + }); + return { kind: "declined", invitation }; + } catch (error: unknown) { + return { kind: "failed", error, key }; + } +} diff --git a/frontend/src/features/respond-invitation/model/decline-draft.test.ts b/frontend/src/features/respond-invitation/model/decline-draft.test.ts new file mode 100644 index 0000000..35b7b15 --- /dev/null +++ b/frontend/src/features/respond-invitation/model/decline-draft.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { + commentTooLong, + declineBody, + declineComment, + declineCommentLimit, + declineReady, + emptyDeclineDraft, +} from "./decline-draft"; + +describe("decline draft", () => { + it("needs a reason and nothing else: no reason is preselected", () => { + expect(declineReady(emptyDeclineDraft)).toBe(false); + expect(declineReady({ reason: "other", comment: "" })).toBe(true); + }); + + it("sends the reason without a comment when the candidate writes none, even for other", () => { + expect(declineBody(2, { reason: "other", comment: " " })).toEqual({ + expected_version: 2, + reason: "other", + }); + }); + + it("trims a written comment and keeps its line breaks", () => { + expect(declineComment(" Не сейчас\nСпасибо ")).toBe("Не сейчас\nСпасибо"); + expect(declineBody(2, { reason: "salary", comment: " Вилка ниже ожиданий " })).toEqual({ + expected_version: 2, + reason: "salary", + comment: "Вилка ниже ожиданий", + }); + }); + + it("counts the comment limit in code points and blocks a longer comment", () => { + const exact = "я".repeat(declineCommentLimit); + expect(commentTooLong(exact)).toBe(false); + expect(commentTooLong(`${exact}я`)).toBe(true); + expect(declineReady({ reason: "tasks", comment: `${exact}я` })).toBe(false); + }); + + it("refuses to build a body without a reason", () => { + expect(() => declineBody(1, emptyDeclineDraft)).toThrow("A decline needs a reason."); + }); +}); diff --git a/frontend/src/features/respond-invitation/model/decline-draft.ts b/frontend/src/features/respond-invitation/model/decline-draft.ts new file mode 100644 index 0000000..dcc327a --- /dev/null +++ b/frontend/src/features/respond-invitation/model/decline-draft.ts @@ -0,0 +1,45 @@ +import type { + InvitationDeclineReason, + InvitationDeclineRequest, +} from "../../../shared/api/schemas"; + +// The candidate's decline form. A reason is required, and the comment is +// optional for every reason, including "other": the neutral reason never +// asks for free text. The comment is never shown to the organization. + +/** The contract's limit on the comment, in Unicode code points. */ +export const declineCommentLimit = 500; + +export interface DeclineDraft { + readonly reason: InvitationDeclineReason | null; + readonly comment: string; +} + +export const emptyDeclineDraft: DeclineDraft = { reason: null, comment: "" }; + +/** The comment as sent, or null when it is blank: a blank comment means none. */ +export function declineComment(comment: string): string | null { + const trimmed = comment.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +export function commentTooLong(comment: string): boolean { + return Array.from(comment.trim()).length > declineCommentLimit; +} + +/** Whether the decline may be sent: a reason is chosen and the comment fits the limit. */ +export function declineReady(draft: DeclineDraft): boolean { + return draft.reason !== null && !commentTooLong(draft.comment); +} + +/** The request body; the comment is absent when the candidate wrote none. */ +export function declineBody( + expectedVersion: number, + draft: DeclineDraft, +): InvitationDeclineRequest { + if (draft.reason === null) throw new Error("A decline needs a reason."); + const comment = declineComment(draft.comment); + return comment === null + ? { expected_version: expectedVersion, reason: draft.reason } + : { expected_version: expectedVersion, reason: draft.reason, comment }; +} diff --git a/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css b/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css new file mode 100644 index 0000000..387238c --- /dev/null +++ b/frontend/src/features/respond-invitation/ui/decline-invitation-form.module.css @@ -0,0 +1,129 @@ +.form { + display: grid; + gap: var(--space-4); + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.title { + font-size: var(--font-size-l); + font-weight: var(--font-weight-bold); +} + +.fieldset { + display: grid; + gap: var(--space-2); + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} + +.legend, +.label { + display: block; + padding: 0; + margin-bottom: var(--space-2); + font-weight: var(--font-weight-bold); +} + +.hint { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.option { + display: flex; + align-items: flex-start; + gap: var(--space-3); + min-height: 2.75rem; + min-width: 0; + padding: var(--space-2) var(--space-3); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-s); + background: var(--color-surface); + line-height: var(--line-height-body); + cursor: pointer; +} + +.option input { + flex: none; + width: 1.25rem; + height: 1.25rem; + margin: 0.2rem 0 0; + accent-color: var(--color-accent); +} + +.option span { + min-width: 0; + overflow-wrap: anywhere; +} + +.option:has(input:focus-visible) { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.comment { + display: grid; + gap: var(--space-2); + min-width: 0; +} + +.textarea { + box-sizing: border-box; + width: 100%; + min-width: 0; + padding: var(--space-3); + border: var(--line-strong) solid var(--color-border-strong); + border-radius: var(--radius-s); + background: var(--color-surface); + color: var(--color-text); + font: inherit; + line-height: var(--line-height-body); + resize: vertical; +} + +.textarea[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.textarea:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.alert { + padding: var(--space-3); + border: var(--line-strong) solid var(--color-danger); + border-radius: var(--radius-s); + background: var(--color-surface); + color: var(--color-text); + line-height: var(--line-height-body); +} + +.alert:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +.submit { + width: 100%; +} + +@media (width >= 36rem) { + .submit { + width: auto; + } +} diff --git a/frontend/src/features/respond-invitation/ui/decline-invitation-form.test.tsx b/frontend/src/features/respond-invitation/ui/decline-invitation-form.test.tsx new file mode 100644 index 0000000..e64f5a6 --- /dev/null +++ b/frontend/src/features/respond-invitation/ui/decline-invitation-form.test.tsx @@ -0,0 +1,42 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { candidateInvitationFixture } from "../../../entities/invitation/testing"; +import { DeclineInvitationForm } from "./decline-invitation-form"; + +function render(): string { + return renderToStaticMarkup( + undefined} + onFailure={() => undefined} + />, + ); +} + +describe("decline invitation form", () => { + it("offers every reason as an unchecked choice, with the neutral reason last", () => { + const html = render(); + + expect(html.match(/type="radio"/g)).toHaveLength(9); + expect(html).not.toMatch(/checked=""/); + expect(html).toContain("Вилка зарплаты не подходит"); + expect(html.indexOf("Другая причина")).toBeGreaterThan( + html.indexOf("Я принял другое предложение"), + ); + }); + + it("keeps the comment optional for every reason and says who reads it", () => { + const html = render(); + + expect(html).toContain("Комментарий (необязательно)"); + expect(html).toContain("Комментарий видите только вы"); + expect(html).toContain("Отказ окончательный"); + }); + + it("is not ready to send until a reason is chosen", () => { + expect(render()).toMatch( + /]*aria-disabled="true"[^>]*>Отклонить приглашение<\/button>/, + ); + }); +}); diff --git a/frontend/src/features/respond-invitation/ui/decline-invitation-form.tsx b/frontend/src/features/respond-invitation/ui/decline-invitation-form.tsx new file mode 100644 index 0000000..b29edb7 --- /dev/null +++ b/frontend/src/features/respond-invitation/ui/decline-invitation-form.tsx @@ -0,0 +1,170 @@ +import { useEffect, useId, useRef, useState, type FormEvent } from "react"; +import { + declineReasonCodes, + declineReasonLabels, + describeResponseFailure, + type KeyBinding, + type ResponseFailure, +} from "../../../entities/invitation"; +import type { CandidateInvitation } from "../../../shared/api/schemas"; +import { Button } from "../../../shared/ui"; +import { + commentTooLong, + declineBody, + declineCommentLimit, + declineReady, + emptyDeclineDraft, + type DeclineDraft, +} from "../model/decline-draft"; +import { runDeclineCommand } from "../model/decline-command"; +import styles from "./decline-invitation-form.module.css"; + +type DeclineInvitationFormProps = { + /** The invitation the candidate is still able to answer. */ + invitation: CandidateInvitation; + csrfToken: string; + onDeclined: (invitation: CandidateInvitation) => void; + onFailure: (failure: ResponseFailure) => void; +}; + +/** + * Declines the invitation with a structured reason. The reason is chosen by + * the candidate and nothing is preselected; the comment is optional for every + * reason, including "other". The decline is final, so the form says so. + */ +export function DeclineInvitationForm({ + invitation, + csrfToken, + onDeclined, + onFailure, +}: DeclineInvitationFormProps) { + const id = useId(); + const [draft, setDraft] = useState(emptyDeclineDraft); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + const [hint, setHint] = useState(null); + const inFlight = useRef(false); + const keyRef = useRef(null); + const alertRef = useRef(null); + const ready = declineReady(draft); + const tooLong = commentTooLong(draft.comment); + + useEffect(() => { + if (failure) alertRef.current?.focus(); + }, [failure]); + + function submit(event: FormEvent) { + event.preventDefault(); + if (inFlight.current) return; + if (!ready) { + setHint( + tooLong + ? `Комментарий длиннее ${declineCommentLimit} символов. Сократите его, чтобы отправить отказ.` + : "Выберите причину отказа, чтобы отправить ответ.", + ); + return; + } + inFlight.current = true; + setBusy(true); + setFailure(null); + setHint(null); + const body = declineBody(invitation.version, draft); + void runDeclineCommand({ invitationId: invitation.id, csrfToken, body }, keyRef.current).then( + (outcome) => { + inFlight.current = false; + if (outcome.kind === "declined") { + keyRef.current = null; + onDeclined(outcome.invitation); + return; + } + keyRef.current = outcome.key; + setBusy(false); + const described = describeResponseFailure("decline", outcome.error); + setFailure(described); + onFailure(described); + }, + ); + } + + return ( +
+

+ Отклонить приглашение +

+ +
+ Причина отказа +

+ Выберите одну причину. Ни одна не выбрана заранее. Комментарий необязателен, в том числе + для варианта «Другая причина». +

+ {declineReasonCodes.map((code) => ( + + ))} +
+ +
+ +