feat(invitations): add the candidate invitation inbox with C4 acceptance and decline
This commit is contained in:
1 parent
12a7213d4a
commit
a856066316
54 files changed
+3897
-136
No files matched your search
+3
-3
@@ -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
|
||||
|
||||
|
||||
@@ -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 <trace.zip>` 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=<dir>` runs specs from another directory, such as a scratch copy, against the same isolated stack.
|
||||
|
||||
## Local registration browser tests with a mail fixture
|
||||
|
||||
+3
-3
@@ -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 и данные
|
||||
|
||||
|
||||
@@ -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.zip>` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=<dir>` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке.
|
||||
|
||||
## Локальный браузерный тест регистрации с почтовым fixture
|
||||
|
||||
+17
-3
@@ -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.
|
||||
|
||||
+17
-3
@@ -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` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<string> {
|
||||
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<void> {
|
||||
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<ApiResult> {
|
||||
return page.evaluate(
|
||||
async ({ method, path, body }) => {
|
||||
const headers: Record<string, string> = {};
|
||||
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<Candidate> {
|
||||
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<void> {
|
||||
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<unknown>,
|
||||
): Promise<void> {
|
||||
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()));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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)
|
||||
|
||||
@@ -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"] },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -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[^>]*>Приглашения<\/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("Экран будет реализован в одной из следующих задач");
|
||||
});
|
||||
});
|
||||
@@ -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: <AssessmentResultsPage /> },
|
||||
{ path: `${paths.candidate.results}/:attemptId`, element: <AssessmentResultPage /> },
|
||||
{ path: paths.candidate.invitations, element: <CandidateInvitationsPage /> },
|
||||
{
|
||||
path: paths.candidate.invitations,
|
||||
element: <PlaceholderPage screen="candidateInvitations" />,
|
||||
path: `${paths.candidate.invitations}/:invitationId`,
|
||||
element: <CandidateInvitationPage />,
|
||||
},
|
||||
{ path: paths.candidate.notifications, element: <CandidateNotificationsPage /> },
|
||||
{
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<CandidateInvitationList> {
|
||||
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<CandidateInvitation> {
|
||||
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<CandidateInvitation> {
|
||||
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<CandidateInvitation> {
|
||||
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<CandidateInvitation> {
|
||||
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,
|
||||
};
|
||||
@@ -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,
|
||||
|
||||
@@ -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> = {},
|
||||
): 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,
|
||||
};
|
||||
}
|
||||
@@ -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<Record<InvitationDeclineReason, string>> = {
|
||||
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<Record<ContactFieldKind, string>> = {
|
||||
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<Record<InvitationState, string>> = {
|
||||
draft: "Черновик",
|
||||
delivered: "Ждет вашего решения",
|
||||
viewed: "Вы открыли условия",
|
||||
counter: "Встречное предложение",
|
||||
accepted: "Принято",
|
||||
interview_scheduled: "Назначено интервью",
|
||||
interviewed: "Интервью проведено",
|
||||
negotiation: "Переговоры",
|
||||
terms_agreed: "Условия согласованы",
|
||||
no_deal: "Без сделки",
|
||||
declined: "Вы отклонили приглашение",
|
||||
expired: "Срок ответа истек",
|
||||
withdrawn: "Компания отозвала приглашение",
|
||||
cancelled_by_candidate: "Вы отменили участие",
|
||||
};
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<CandidateInvitation, "state" | "response_deadline_at">,
|
||||
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<CandidateInvitation, "state" | "response_deadline_at">,
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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() };
|
||||
}
|
||||
@@ -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("тем же ключом");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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";
|
||||
@@ -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" });
|
||||
});
|
||||
});
|
||||
@@ -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<AcceptOutcome> {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -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([
|
||||
"Первый абзац.",
|
||||
"Второй абзац.",
|
||||
"Третий.",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
+127
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
<AcceptContactConsentForm
|
||||
invitation={candidateInvitationFixture()}
|
||||
offer={contactConsentOffer}
|
||||
organizationName="Северный ветер"
|
||||
csrfToken={"A".repeat(43)}
|
||||
onAccepted={() => 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(`<span>${label}</span>`);
|
||||
}
|
||||
expect(html).not.toContain("<span>Telegram</span>");
|
||||
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("<p>Я согласен передать компании «Северный ветер» отмеченные контакты");
|
||||
expect(html).toContain("<p>Согласие относится только к этому приглашению.</p>");
|
||||
expect(html).toContain("Я прочитал(а) текст согласия и согласен(на) передать");
|
||||
});
|
||||
|
||||
it("is not ready to send until a kind and the confirmation are chosen", () => {
|
||||
const html = render();
|
||||
|
||||
expect(html).toMatch(
|
||||
/<button[^>]*aria-disabled="true"[^>]*>Принять и передать контакты<\/button>/,
|
||||
);
|
||||
expect(html).not.toContain('role="alert"');
|
||||
});
|
||||
});
|
||||
@@ -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<AcceptDraft>(emptyAcceptDraft);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [failure, setFailure] = useState<ResponseFailure | null>(null);
|
||||
const [hint, setHint] = useState<string | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
const keyRef = useRef<KeyBinding | null>(null);
|
||||
const alertRef = useRef<HTMLDivElement>(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<HTMLFormElement>) {
|
||||
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 (
|
||||
<form className={styles.form} onSubmit={submit} noValidate aria-labelledby={`${id}-title`}>
|
||||
<h3 id={`${id}-title`} className={styles.title}>
|
||||
Принять приглашение
|
||||
</h3>
|
||||
|
||||
<fieldset className={styles.fieldset} aria-describedby={`${id}-fields-hint`}>
|
||||
<legend className={styles.legend}>Контакты, которые получит компания</legend>
|
||||
<p id={`${id}-fields-hint`} className={styles.hint}>
|
||||
Ничего не отмечено заранее. Отметьте только те контакты, которые компания сможет прочитать
|
||||
после принятия. Остальные не передаются.
|
||||
</p>
|
||||
{kinds.map((kind) => (
|
||||
<label key={kind} className={styles.option}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="contact-field"
|
||||
value={kind}
|
||||
checked={draft.fields.includes(kind)}
|
||||
onChange={(event) => {
|
||||
const checked = event.currentTarget.checked;
|
||||
setDraft((current) => toggleAcceptField(current, kind, checked));
|
||||
}}
|
||||
/>
|
||||
<span>{contactKindLabels[kind]}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<section className={styles.consent} aria-labelledby={`${id}-consent-title`}>
|
||||
<h4 id={`${id}-consent-title`} className={styles.subtitle}>
|
||||
Текст согласия C4
|
||||
</h4>
|
||||
<div className={styles.text}>
|
||||
{paragraphs.map((paragraph, index) => (
|
||||
// The consent text is static for the lifetime of this form.
|
||||
<p key={index}>{paragraph}</p>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<label className={styles.option}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="consent-confirmed"
|
||||
checked={draft.confirmed}
|
||||
onChange={(event) => {
|
||||
const confirmed = event.currentTarget.checked;
|
||||
setDraft((current) => setAcceptConfirmed(current, confirmed));
|
||||
}}
|
||||
/>
|
||||
<span>
|
||||
{`Я прочитал(а) текст согласия и согласен(на) передать отмеченные контакты компании «${organizationName}».`}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<p id={`${id}-ready-hint`} className={styles.hint}>
|
||||
Кнопка станет доступна, когда отмечен хотя бы один контакт и подтверждено согласие.
|
||||
</p>
|
||||
|
||||
{hint ? (
|
||||
<p className={styles.hint} role="status">
|
||||
{hint}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{failure ? (
|
||||
<div
|
||||
ref={alertRef}
|
||||
tabIndex={-1}
|
||||
role="alert"
|
||||
className={styles.alert}
|
||||
data-failure={failure.kind}
|
||||
>
|
||||
{failure.message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button
|
||||
type="submit"
|
||||
isBusy={busy}
|
||||
aria-disabled={!ready || undefined}
|
||||
aria-describedby={`${id}-ready-hint`}
|
||||
className={styles.submit}
|
||||
>
|
||||
{busy ? "Отправляем ответ..." : "Принять и передать контакты"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
@@ -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<DeclineOutcome> {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
<DeclineInvitationForm
|
||||
invitation={candidateInvitationFixture()}
|
||||
csrfToken={"A".repeat(43)}
|
||||
onDeclined={() => 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("<span>Вилка зарплаты не подходит</span>");
|
||||
expect(html.indexOf("<span>Другая причина</span>")).toBeGreaterThan(
|
||||
html.indexOf("<span>Я принял другое предложение</span>"),
|
||||
);
|
||||
});
|
||||
|
||||
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(
|
||||
/<button[^>]*aria-disabled="true"[^>]*>Отклонить приглашение<\/button>/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<DeclineDraft>(emptyDeclineDraft);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [failure, setFailure] = useState<ResponseFailure | null>(null);
|
||||
const [hint, setHint] = useState<string | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
const keyRef = useRef<KeyBinding | null>(null);
|
||||
const alertRef = useRef<HTMLDivElement>(null);
|
||||
const ready = declineReady(draft);
|
||||
const tooLong = commentTooLong(draft.comment);
|
||||
|
||||
useEffect(() => {
|
||||
if (failure) alertRef.current?.focus();
|
||||
}, [failure]);
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
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 (
|
||||
<form className={styles.form} onSubmit={submit} noValidate aria-labelledby={`${id}-title`}>
|
||||
<h3 id={`${id}-title`} className={styles.title}>
|
||||
Отклонить приглашение
|
||||
</h3>
|
||||
|
||||
<fieldset className={styles.fieldset} aria-describedby={`${id}-reason-hint`}>
|
||||
<legend className={styles.legend}>Причина отказа</legend>
|
||||
<p id={`${id}-reason-hint`} className={styles.hint}>
|
||||
Выберите одну причину. Ни одна не выбрана заранее. Комментарий необязателен, в том числе
|
||||
для варианта «Другая причина».
|
||||
</p>
|
||||
{declineReasonCodes.map((code) => (
|
||||
<label key={code} className={styles.option}>
|
||||
<input
|
||||
type="radio"
|
||||
name="decline-reason"
|
||||
value={code}
|
||||
checked={draft.reason === code}
|
||||
onChange={() => setDraft((current) => ({ ...current, reason: code }))}
|
||||
/>
|
||||
<span>{declineReasonLabels[code]}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className={styles.comment}>
|
||||
<label htmlFor={`${id}-comment`} className={styles.label}>
|
||||
Комментарий (необязательно)
|
||||
</label>
|
||||
<textarea
|
||||
id={`${id}-comment`}
|
||||
className={styles.textarea}
|
||||
rows={4}
|
||||
maxLength={declineCommentLimit}
|
||||
value={draft.comment}
|
||||
aria-describedby={`${id}-comment-hint`}
|
||||
aria-invalid={tooLong || undefined}
|
||||
onChange={(event) => {
|
||||
const comment = event.currentTarget.value;
|
||||
setDraft((current) => ({ ...current, comment }));
|
||||
}}
|
||||
/>
|
||||
<p id={`${id}-comment-hint`} className={styles.hint}>
|
||||
Комментарий видите только вы. Компания его не получает и не видит причину отказа.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className={styles.hint}>Отказ окончательный: после него приглашение нельзя принять.</p>
|
||||
|
||||
{hint ? (
|
||||
<p className={styles.hint} role="status">
|
||||
{hint}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{failure ? (
|
||||
<div
|
||||
ref={alertRef}
|
||||
tabIndex={-1}
|
||||
role="alert"
|
||||
className={styles.alert}
|
||||
data-failure={failure.kind}
|
||||
>
|
||||
{failure.message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="secondary"
|
||||
isBusy={busy}
|
||||
aria-disabled={!ready || undefined}
|
||||
className={styles.submit}
|
||||
>
|
||||
{busy ? "Отправляем отказ..." : "Отклонить приглашение"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Public API of the candidate-invitations pages: the candidate's inbox and the
|
||||
// screen of one invitation addressed to the candidate.
|
||||
|
||||
export { CandidateInvitationsPage } from "./ui/candidate-invitations-page";
|
||||
export { CandidateInvitationPage } from "./ui/candidate-invitation-page";
|
||||
@@ -0,0 +1,155 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
candidateAccountId,
|
||||
candidateGrantId,
|
||||
candidateInvitationFixture,
|
||||
candidateInvitationId,
|
||||
emailOnlyGrant,
|
||||
openDeadline,
|
||||
passedDeadline,
|
||||
} from "../../../entities/invitation/testing";
|
||||
import { candidateInvitationQueryKeys } from "../../../entities/invitation";
|
||||
import type { CandidateInvitation, Session } from "../../../shared/api/schemas";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { CandidateInvitationPage } from "./candidate-invitation-page";
|
||||
|
||||
const session = {
|
||||
account: {
|
||||
id: candidateAccountId,
|
||||
email: "candidate@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
function render(
|
||||
invitation: CandidateInvitation | null,
|
||||
invitationId = candidateInvitationId,
|
||||
): string {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
if (invitation) {
|
||||
queryClient.setQueryData(
|
||||
candidateInvitationQueryKeys.detail(candidateAccountId, invitation.id),
|
||||
invitation,
|
||||
);
|
||||
}
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[`/candidate/invitations/${invitationId}`]}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/candidate/invitations/:invitationId"
|
||||
element={<CandidateInvitationPage />}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("candidate invitation page", () => {
|
||||
it("shows the company, the terms, and the deadline with its UTC label before any choice", () => {
|
||||
const html = render(candidateInvitationFixture());
|
||||
|
||||
expect(html).toContain("Приглашение</h1>");
|
||||
expect(html).toContain("Северный ветер");
|
||||
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
|
||||
expect(html).toContain(`<time dateTime="${openDeadline}">`);
|
||||
expect(html).toMatch(/<time dateTime="2099-10-16T10:00:00Z">[^<]*UTC<\/time>/);
|
||||
expect(html).toContain("Принять и передать контакты");
|
||||
expect(html).toContain("Отклонить приглашение");
|
||||
expect(html).not.toMatch(/checked=""/);
|
||||
});
|
||||
|
||||
it("offers the contact kinds unchecked and nothing outside the offer", () => {
|
||||
const html = render(candidateInvitationFixture());
|
||||
|
||||
expect(html.match(/type="checkbox"/g)).toHaveLength(4);
|
||||
expect(html).toContain("<span>Электронная почта</span>");
|
||||
expect(html).toContain("<span>Телефон</span>");
|
||||
expect(html).not.toContain("<span>Telegram</span>");
|
||||
});
|
||||
|
||||
it("asks to add a contact instead of an acceptance when the profile holds none", () => {
|
||||
const html = render(candidateInvitationFixture({ contact_consent: null }));
|
||||
|
||||
expect(html).toContain("Принять приглашение нельзя");
|
||||
expect(html).toContain('href="/candidate/profile"');
|
||||
expect(html).not.toContain("Принять и передать контакты");
|
||||
expect(html).toContain("Отклонить приглашение");
|
||||
});
|
||||
|
||||
it("shows only the contacts that the grant covers after an acceptance", () => {
|
||||
const html = render(
|
||||
candidateInvitationFixture({
|
||||
state: "accepted",
|
||||
version: 2,
|
||||
contact_consent: null,
|
||||
contact_grant: emailOnlyGrant,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(html).toContain("Итог");
|
||||
expect(html).toContain("<li>Электронная почта</li>");
|
||||
expect(html).not.toContain("<li>Телефон</li>");
|
||||
expect(html).not.toContain("<li>ФИО</li>");
|
||||
expect(html).toContain("Компания может прочитать эти контакты.");
|
||||
expect(html).not.toContain("Отклонить приглашение");
|
||||
});
|
||||
|
||||
it("explains a grant that the company cannot read yet, and where to change visibility", () => {
|
||||
const html = render(
|
||||
candidateInvitationFixture({
|
||||
state: "accepted",
|
||||
version: 2,
|
||||
contact_consent: null,
|
||||
contact_grant: { ...emailOnlyGrant, readable: false, blocked_by: "visibility" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(html).toContain("Пока карточка не опубликована или скрыта от компании");
|
||||
expect(html).toContain('href="/candidate/privacy"');
|
||||
});
|
||||
|
||||
it("keeps a declined invitation declined, with the reason and the own comment, and no contacts", () => {
|
||||
const html = render(
|
||||
candidateInvitationFixture({
|
||||
state: "declined",
|
||||
version: 2,
|
||||
contact_consent: null,
|
||||
decline: { reason: "other", comment: null, declined_at: "2026-10-10T09:00:00Z" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(html).toContain("Вы отклонили приглашение");
|
||||
expect(html).toContain("Причина: Другая причина.");
|
||||
expect(html).not.toContain("Ваш комментарий");
|
||||
expect(html).not.toContain("Контакты, которые открыты компании");
|
||||
expect(html).not.toContain("Отклонить приглашение");
|
||||
});
|
||||
|
||||
it("closes the answer at the deadline by the clock, even before the server applies the expiry", () => {
|
||||
const html = render(
|
||||
candidateInvitationFixture({ response_deadline_at: passedDeadline, contact_consent: null }),
|
||||
);
|
||||
|
||||
expect(html).toContain("Срок ответа истек. Приглашение закрыто");
|
||||
expect(html).not.toContain("Принять и передать контакты");
|
||||
expect(html).not.toContain("Отклонить приглашение");
|
||||
});
|
||||
|
||||
it("says that the invitation is not found for a malformed or foreign identifier", () => {
|
||||
const html = render(null, "not-a-uuid");
|
||||
|
||||
expect(html).toContain("Приглашение не найдено");
|
||||
expect(html).not.toContain("Принять и передать контакты");
|
||||
expect(html).not.toContain(candidateGrantId);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { AcceptContactConsentForm } from "../../../features/accept-contact-consent";
|
||||
import { DeclineInvitationForm } from "../../../features/respond-invitation";
|
||||
import {
|
||||
candidateInvitationQueryKeys,
|
||||
candidateStatusLabel,
|
||||
contactKindLabels,
|
||||
declineReasonLabels,
|
||||
formatServerMoment,
|
||||
isAnswerable,
|
||||
newerInvitation,
|
||||
orderedContactKinds,
|
||||
readCandidateInvitation,
|
||||
viewCandidateInvitation,
|
||||
type ResponseCommand,
|
||||
type ResponseFailure,
|
||||
useServerNow,
|
||||
} from "../../../entities/invitation";
|
||||
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
CandidateInvitation,
|
||||
ContactGrant,
|
||||
ContactRevocationReason,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import { InvitationTermsArticle } from "../../../widgets/invitation-preview";
|
||||
import styles from "./candidate-invitations.module.css";
|
||||
|
||||
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
const staleAcceptNotice =
|
||||
"Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и подтвердите выбор контактов заново.";
|
||||
|
||||
const revocationText: Readonly<Record<ContactRevocationReason, string>> = {
|
||||
consent_revoked: "вы отозвали согласие C4 для этой компании",
|
||||
participation_cancelled: "вы отменили участие в этом приглашении",
|
||||
visibility_closed: "вы закрыли публикацию или скрыли профиль от компании",
|
||||
};
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof ApiRequestError && error.status === 404;
|
||||
}
|
||||
|
||||
function NotFoundState() {
|
||||
return (
|
||||
<EmptyState
|
||||
title="Приглашение не найдено"
|
||||
description="Оно не адресовано вашему кабинету или уже недоступно."
|
||||
action={
|
||||
<ButtonLink to={paths.candidate.invitations} variant="secondary">
|
||||
К списку приглашений
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the candidate can read about the contacts that one acceptance opened. */
|
||||
function GrantSummary({ grant }: { grant: ContactGrant }) {
|
||||
const kinds = orderedContactKinds(grant.fields);
|
||||
let status: ReactNode;
|
||||
if (grant.status === "revoked") {
|
||||
status = `Доступ закрыт: ${
|
||||
grant.revocation_reason ? revocationText[grant.revocation_reason] : "доступ закрыт"
|
||||
}.`;
|
||||
} else if (grant.readable) {
|
||||
status = "Компания может прочитать эти контакты.";
|
||||
} else {
|
||||
status = (
|
||||
<>
|
||||
{
|
||||
"Пока карточка не опубликована или скрыта от компании, она не может прочитать эти контакты. Измените видимость в "
|
||||
}
|
||||
<TextLink to={paths.candidate.privacy}>настройках приватности</TextLink>.
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={styles.grant}>
|
||||
<h3 className={styles.subtitle}>Контакты, которые открыты компании</h3>
|
||||
<ul className={styles.kinds}>
|
||||
{kinds.map((kind) => (
|
||||
<li key={kind}>{contactKindLabels[kind]}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className={styles.text}>{`Открыто ${formatServerMoment(grant.granted_at)}.`}</p>
|
||||
<p className={styles.text}>{status}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function outcomeText(invitation: CandidateInvitation, serverNow: number): string {
|
||||
if (!isAnswerable(invitation, serverNow) && invitation.state === "delivered") {
|
||||
return "Срок ответа истек. Приглашение закрыто, контакты не передавались.";
|
||||
}
|
||||
switch (invitation.state) {
|
||||
case "accepted":
|
||||
return "Вы приняли приглашение. Компания получила доступ только к отмеченным контактам.";
|
||||
case "declined":
|
||||
return "Вы отклонили приглашение. Компания не получает контакты и не видит причину отказа.";
|
||||
case "expired":
|
||||
return "Срок ответа истек. Контакты не передавались.";
|
||||
case "withdrawn":
|
||||
return "Компания отозвала приглашение. Новых решений по нему не нужно.";
|
||||
case "cancelled_by_candidate":
|
||||
return "Вы отменили участие. Доступ к контактам по этому приглашению закрыт.";
|
||||
default:
|
||||
return candidateStatusLabel(invitation, serverNow);
|
||||
}
|
||||
}
|
||||
|
||||
function OutcomeSection({
|
||||
invitation,
|
||||
serverNow,
|
||||
}: {
|
||||
invitation: CandidateInvitation;
|
||||
serverNow: number;
|
||||
}) {
|
||||
const decline = invitation.decline;
|
||||
return (
|
||||
<Section title="Итог">
|
||||
<p className={styles.text}>{outcomeText(invitation, serverNow)}</p>
|
||||
{decline ? (
|
||||
<div className={styles.grant}>
|
||||
<h3 className={styles.subtitle}>Ваш отказ</h3>
|
||||
<p className={styles.text}>{`Причина: ${declineReasonLabels[decline.reason]}.`}</p>
|
||||
{decline.comment ? (
|
||||
<p className={styles.text}>{`Ваш комментарий: ${decline.comment}`}</p>
|
||||
) : null}
|
||||
<p className={styles.text}>{`Отказ ${formatServerMoment(decline.declined_at)}.`}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{invitation.contact_grant ? <GrantSummary grant={invitation.contact_grant} /> : null}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
type AnswerSectionProps = {
|
||||
invitation: CandidateInvitation;
|
||||
csrfToken: string;
|
||||
onAnswered: (invitation: CandidateInvitation) => void;
|
||||
onFailure: (command: ResponseCommand, failure: ResponseFailure) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The two answers while the invitation is open. Accepting needs the consent
|
||||
* offer, which the server returns only when the profile holds a contact.
|
||||
*/
|
||||
function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerSectionProps) {
|
||||
const offer = invitation.contact_consent;
|
||||
return (
|
||||
<Section
|
||||
title="Ваш ответ"
|
||||
description="Ответ нельзя изменить после отправки: принятие открывает отмеченные контакты, отказ закрывает приглашение."
|
||||
>
|
||||
<div className={styles.decisions}>
|
||||
{offer ? (
|
||||
<AcceptContactConsentForm
|
||||
key={`${invitation.id}:${invitation.terms_version}`}
|
||||
invitation={invitation}
|
||||
offer={offer}
|
||||
organizationName={invitation.organization.name}
|
||||
csrfToken={csrfToken}
|
||||
onAccepted={onAnswered}
|
||||
onFailure={(failure) => onFailure("accept", failure)}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles["no-offer"]}>
|
||||
<h3 className={styles.subtitle}>Принять приглашение нельзя</h3>
|
||||
<p className={styles.text}>
|
||||
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в
|
||||
профиль, чтобы принять приглашение.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.profile} variant="secondary">
|
||||
Открыть профиль
|
||||
</ButtonLink>
|
||||
</div>
|
||||
)}
|
||||
<DeclineInvitationForm
|
||||
key={invitation.id}
|
||||
invitation={invitation}
|
||||
csrfToken={csrfToken}
|
||||
onDeclined={onAnswered}
|
||||
onFailure={(failure) => onFailure("decline", failure)}
|
||||
/>
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
type InvitationContentProps = AnswerSectionProps & {
|
||||
serverNow: number;
|
||||
notice: string | null;
|
||||
};
|
||||
|
||||
function InvitationContent({
|
||||
invitation,
|
||||
serverNow,
|
||||
notice,
|
||||
csrfToken,
|
||||
onAnswered,
|
||||
onFailure,
|
||||
}: InvitationContentProps) {
|
||||
return (
|
||||
<>
|
||||
<Section title="Компания и срок">
|
||||
<dl className={styles.facts}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Компания</dt>
|
||||
<dd>{invitation.organization.name}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Состояние</dt>
|
||||
<dd data-state={invitation.state}>{candidateStatusLabel(invitation, serverNow)}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Срок ответа</dt>
|
||||
<dd data-term="deadline">
|
||||
<time dateTime={invitation.response_deadline_at}>
|
||||
{`До ${formatServerMoment(invitation.response_deadline_at)}`}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</Section>
|
||||
|
||||
{notice ? (
|
||||
<p className={styles.notice} role="status">
|
||||
{notice}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<Section title="Условия приглашения">
|
||||
<InvitationTermsArticle
|
||||
terms={invitation.terms}
|
||||
responsePeriodDays={null}
|
||||
responseDeadlineAt={null}
|
||||
headingLevel={3}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
{isAnswerable(invitation, serverNow) ? (
|
||||
<AnswerSection
|
||||
invitation={invitation}
|
||||
csrfToken={csrfToken}
|
||||
onAnswered={onAnswered}
|
||||
onFailure={onFailure}
|
||||
/>
|
||||
) : (
|
||||
<OutcomeSection invitation={invitation} serverNow={serverNow} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One invitation addressed to the candidate. Opening it records the view once
|
||||
* (the first view is what the company sees as "viewed"); reading it never
|
||||
* does. An answer replaces the shown invitation with the one the server
|
||||
* returns, and a stale terms version makes the page read the new terms.
|
||||
*/
|
||||
export function CandidateInvitationPage() {
|
||||
const { invitationId = "" } = useParams();
|
||||
const validId = uuidPattern.test(invitationId);
|
||||
const session = useGetCurrentSession();
|
||||
const accountId = session.data?.account.id ?? "";
|
||||
const csrfToken = session.data?.csrf_token ?? "";
|
||||
const queryClient = useQueryClient();
|
||||
const detail = useQuery({
|
||||
queryKey: candidateInvitationQueryKeys.detail(accountId, invitationId),
|
||||
queryFn: ({ signal }) => readCandidateInvitation(invitationId, signal),
|
||||
enabled: validId && accountId !== "",
|
||||
});
|
||||
const invitation = detail.data;
|
||||
const openedId = invitation?.id;
|
||||
const viewedId = useRef<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
// One view per opened invitation. A failed view changes nothing on screen:
|
||||
// the terms stay readable and the candidate can still answer.
|
||||
useEffect(() => {
|
||||
if (openedId === undefined || csrfToken === "" || viewedId.current === openedId) return;
|
||||
viewedId.current = openedId;
|
||||
void viewCandidateInvitation(openedId, { csrfToken }).then(
|
||||
(viewed) => {
|
||||
queryClient.setQueryData<CandidateInvitation>(
|
||||
candidateInvitationQueryKeys.detail(accountId, openedId),
|
||||
(current) => newerInvitation(current, viewed),
|
||||
);
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
}, [openedId, csrfToken, accountId, queryClient]);
|
||||
|
||||
function handleAnswered(updated: CandidateInvitation) {
|
||||
queryClient.setQueryData<CandidateInvitation>(
|
||||
candidateInvitationQueryKeys.detail(accountId, updated.id),
|
||||
(current) => newerInvitation(current, updated),
|
||||
);
|
||||
setNotice(null);
|
||||
void queryClient.invalidateQueries({ queryKey: candidateInvitationQueryKeys.inbox(accountId) });
|
||||
}
|
||||
|
||||
function handleFailure(command: ResponseCommand, failure: ResponseFailure) {
|
||||
if (command === "accept" && failure.kind === "stale-terms") setNotice(staleAcceptNotice);
|
||||
if (failure.kind === "csrf") {
|
||||
void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() });
|
||||
}
|
||||
if (failure.refresh) void detail.refetch();
|
||||
}
|
||||
|
||||
const serverNow = useServerNow();
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Приглашение"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead={invitation ? candidateStatusLabel(invitation, serverNow) : undefined}
|
||||
>
|
||||
{!validId ? <NotFoundState /> : null}
|
||||
{validId && accountId !== "" && detail.isPending ? (
|
||||
<LoadingState label="Открываем приглашение..." />
|
||||
) : null}
|
||||
{validId && detail.isError ? (
|
||||
isMissing(detail.error) ? (
|
||||
<NotFoundState />
|
||||
) : isAccessDenied(detail.error) ? (
|
||||
<ForbiddenState error={detail.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={detail.error}
|
||||
title={
|
||||
invitation ? "Не удалось обновить приглашение" : "Не удалось открыть приглашение"
|
||||
}
|
||||
isRetrying={detail.isFetching}
|
||||
onRetry={() => void detail.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{invitation ? (
|
||||
<InvitationContent
|
||||
invitation={invitation}
|
||||
serverNow={serverNow}
|
||||
notice={notice}
|
||||
csrfToken={csrfToken}
|
||||
onAnswered={handleAnswered}
|
||||
onFailure={handleFailure}
|
||||
/>
|
||||
) : null}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
candidateAccountId,
|
||||
candidateInvitationFixture,
|
||||
candidateInvitationId,
|
||||
} from "../../../entities/invitation/testing";
|
||||
import { candidateInvitationQueryKeys } from "../../../entities/invitation";
|
||||
import type { CandidateInvitationList, Session } from "../../../shared/api/schemas";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { CandidateInvitationsPage } from "./candidate-invitations-page";
|
||||
|
||||
const session = {
|
||||
account: {
|
||||
id: candidateAccountId,
|
||||
email: "candidate@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
function summaryOf(overrides: Record<string, unknown> = {}) {
|
||||
const invitation = candidateInvitationFixture();
|
||||
return {
|
||||
id: invitation.id,
|
||||
organization: invitation.organization,
|
||||
state: invitation.state,
|
||||
expiry_reason: null,
|
||||
version: invitation.version,
|
||||
terms_version: invitation.terms_version,
|
||||
role_title: invitation.terms.role_title,
|
||||
salary: invitation.terms.salary,
|
||||
work_formats: invitation.terms.work_formats,
|
||||
response_deadline_at: invitation.response_deadline_at,
|
||||
delivered_at: invitation.delivered_at,
|
||||
viewed_at: null,
|
||||
updated_at: invitation.updated_at,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function render(page: CandidateInvitationList): string {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
queryClient.setQueryData([...candidateInvitationQueryKeys.inbox(candidateAccountId), "pages"], {
|
||||
pages: [page],
|
||||
pageParams: [undefined],
|
||||
});
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<CandidateInvitationsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("candidate inbox page", () => {
|
||||
it("lists each invitation with its company, role, salary, deadline, and state, linked to its screen", () => {
|
||||
const html = render({
|
||||
items: [summaryOf()] as CandidateInvitationList["items"],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
});
|
||||
|
||||
expect(html).toContain("<h1");
|
||||
expect(html).toContain("Приглашения</h1>");
|
||||
expect(html).toContain(`href="/candidate/invitations/${candidateInvitationId}"`);
|
||||
expect(html).toContain("Северный ветер");
|
||||
expect(html).toContain("Middle Go-разработчик в команду платежей");
|
||||
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
|
||||
expect(html).toContain("UTC");
|
||||
expect(html).toContain("Ждет вашего решения");
|
||||
expect(html).not.toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("offers the next page only when the server says there is one", () => {
|
||||
const html = render({
|
||||
items: [summaryOf()] as CandidateInvitationList["items"],
|
||||
page: { has_more: true, next_cursor: "cursor-2" },
|
||||
});
|
||||
|
||||
expect(html).toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("says that the inbox is empty and what happens to contacts", () => {
|
||||
const html = render({ items: [], page: { has_more: false, next_cursor: null } });
|
||||
|
||||
expect(html).toContain("Приглашений пока нет");
|
||||
expect(html).toContain("Контакты передаются компании только после вашего принятия");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
candidateInvitationQueryKeys,
|
||||
candidateStatusLabel,
|
||||
formatSalaryRange,
|
||||
formatServerMoment,
|
||||
listCandidateInvitations,
|
||||
useServerNow,
|
||||
} from "../../../entities/invitation";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Page,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./candidate-invitations.module.css";
|
||||
|
||||
const lead =
|
||||
"Компании присылают приглашения с условиями, вилкой зарплаты и сроком ответа. Контакты компания получит только после вашего принятия и только те, которые вы отметили.";
|
||||
|
||||
/**
|
||||
* The candidate's inbox: every invitation addressed to the candidate, newest
|
||||
* first. Listing never records a view, so opening this page changes nothing
|
||||
* that the company sees.
|
||||
*/
|
||||
export function CandidateInvitationsPage() {
|
||||
const session = useGetCurrentSession();
|
||||
const accountId = session.data?.account.id ?? "";
|
||||
const inbox = useInfiniteQuery({
|
||||
queryKey: [...candidateInvitationQueryKeys.inbox(accountId), "pages"],
|
||||
queryFn: ({ pageParam, signal }) => listCandidateInvitations({ cursor: pageParam, signal }),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (last) =>
|
||||
last.page.has_more ? (last.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: accountId !== "",
|
||||
});
|
||||
|
||||
const items = inbox.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
const serverNow = useServerNow();
|
||||
|
||||
return (
|
||||
<Page title="Приглашения" eyebrow="Кабинет кандидата" lead={lead}>
|
||||
{inbox.isPending && accountId !== "" ? (
|
||||
<LoadingState label="Загружаем приглашения..." />
|
||||
) : null}
|
||||
{inbox.isError ? (
|
||||
isAccessDenied(inbox.error) ? (
|
||||
<ForbiddenState error={inbox.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={inbox.error}
|
||||
title={
|
||||
items.length > 0
|
||||
? "Не удалось загрузить следующую страницу"
|
||||
: "Не удалось загрузить приглашения"
|
||||
}
|
||||
isRetrying={inbox.isFetching}
|
||||
onRetry={() => void inbox.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{inbox.isSuccess && items.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Приглашений пока нет"
|
||||
description="Когда компания отправит приглашение, оно появится здесь. Контакты передаются компании только после вашего принятия."
|
||||
/>
|
||||
) : null}
|
||||
{items.length > 0 ? (
|
||||
<section className={styles.inbox} aria-label="Список приглашений">
|
||||
<ul className={styles.list}>
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link className={styles.card} to={paths.candidate.invitation(item.id)}>
|
||||
<span className={styles["card-company"]}>
|
||||
<span className={styles["card-label"]}>Компания</span>
|
||||
<span className={styles["card-title"]}>{item.organization.name}</span>
|
||||
</span>
|
||||
<span className={styles["card-role"]}>{item.role_title}</span>
|
||||
<span className={styles["card-facts"]}>
|
||||
<span>{formatSalaryRange(item.salary)}</span>
|
||||
<span>
|
||||
{`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
|
||||
</span>
|
||||
</span>
|
||||
<span className={styles["card-status"]} data-state={item.state}>
|
||||
{candidateStatusLabel(item, serverNow)}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{inbox.hasNextPage ? (
|
||||
<div className={styles.more}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={inbox.isFetchingNextPage}
|
||||
onClick={() => void inbox.fetchNextPage()}
|
||||
>
|
||||
{inbox.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/* Shared by the inbox and the invitation screen. Phones come first: every
|
||||
* block is one column and every tap target is at least 44px tall. */
|
||||
|
||||
.inbox {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
border-color: var(--color-border-strong);
|
||||
}
|
||||
|
||||
.card:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.card-company {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.card-label {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.card-role {
|
||||
overflow-wrap: anywhere;
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.card-facts {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.card-status {
|
||||
justify-self: start;
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fact > dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.fact > dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.text {
|
||||
margin: 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.decisions {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.no-offer {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.grant {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.kinds {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.list {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@@ -91,15 +91,6 @@ export const screens = {
|
||||
"Разбор результата по компетенциям",
|
||||
],
|
||||
},
|
||||
candidateInvitations: {
|
||||
area: "candidate",
|
||||
title: "Приглашения",
|
||||
planned: [
|
||||
"Предложения компаний с вилкой зарплаты",
|
||||
"Принятие или отказ",
|
||||
"Какие компании получили доступ к контактам",
|
||||
],
|
||||
},
|
||||
candidatePrivacy: {
|
||||
area: "candidate",
|
||||
title: "Приватность",
|
||||
|
||||
@@ -12,6 +12,7 @@ const cabinets = [
|
||||
features: [
|
||||
"Заявленный уровень из анкеты показан отдельно от подтвержденной категории.",
|
||||
"Категория появляется только по результату теста. Демонстрационный результат помечен как демонстрационный.",
|
||||
"Приглашения компаний: условия, принятие с выбором контактов и отказ.",
|
||||
"Согласия, публикация карточки, статус поиска, уведомления и обращения в поддержку.",
|
||||
],
|
||||
},
|
||||
@@ -62,8 +63,8 @@ export function WelcomePage() {
|
||||
</Section>
|
||||
<Section title="Пока не готово">
|
||||
<p>
|
||||
Входящие приглашения кандидата, их принятие и список приглашений, отправленных компанией,
|
||||
пока заготовки: эти экраны не показывают данных и не выполняют действий.
|
||||
Список приглашений, отправленных компанией, пока заготовка: этот экран не показывает
|
||||
данных и не выполняет действий.
|
||||
</p>
|
||||
</Section>
|
||||
<Section title="Вход и регистрация">
|
||||
|
||||
@@ -20,6 +20,9 @@ export const paths = {
|
||||
results: "/candidate/results",
|
||||
result: (attemptId: string) => `/candidate/results/${encodeURIComponent(attemptId)}`,
|
||||
invitations: "/candidate/invitations",
|
||||
/** One invitation addressed to the current candidate; the id is an opaque UUID. */
|
||||
invitation: (invitationId: string) =>
|
||||
`/candidate/invitations/${encodeURIComponent(invitationId)}`,
|
||||
notifications: "/candidate/notifications",
|
||||
privacy: "/candidate/privacy",
|
||||
supportCases: "/candidate/support/cases",
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// Public API of the invitation-preview widget: the company card and the
|
||||
// terms of an invitation as the candidate sees them.
|
||||
// terms of an invitation as the candidate sees them, and the terms alone for
|
||||
// a candidate reading an invitation addressed to them.
|
||||
|
||||
export { InvitationPreview } from "./ui/invitation-preview";
|
||||
export { InvitationTermsArticle } from "./ui/invitation-terms";
|
||||
@@ -1,17 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { CandidateOrganizationCard, InvitationTerms } from "../../../shared/api/schemas";
|
||||
import { CompanyCardView } from "../../../entities/company";
|
||||
import {
|
||||
communicationChannelLabels,
|
||||
formatSalaryRange,
|
||||
formatServerMoment,
|
||||
notProvidedLabel,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
} from "../../../entities/invitation";
|
||||
import { gradeLabels, specializationLabels, workFormatLabels } from "../../../entities/match";
|
||||
import { InvitationTermsArticle } from "./invitation-terms";
|
||||
import styles from "./invitation-preview.module.css";
|
||||
|
||||
type InvitationPreviewProps = {
|
||||
@@ -40,12 +30,6 @@ export function InvitationPreview({
|
||||
responseDeadlineAt,
|
||||
title = "Так приглашение увидит кандидат",
|
||||
}: InvitationPreviewProps) {
|
||||
const location =
|
||||
terms.location ??
|
||||
(terms.work_formats.every((format) => format === "remote")
|
||||
? "Не требуется: только удаленная работа"
|
||||
: "Не указано");
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<div className={styles.heading}>
|
||||
@@ -58,89 +42,11 @@ export function InvitationPreview({
|
||||
<section className={styles.company} aria-label="Компания">
|
||||
{card ? <CompanyCardView card={card} headingLevel={4} /> : cardFallback}
|
||||
</section>
|
||||
<article className={styles.terms} aria-label="Условия приглашения">
|
||||
<h4 className={styles.role}>{terms.role_title}</h4>
|
||||
<dl className={styles.facts}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Специализация и грейд</dt>
|
||||
<dd>{`${specializationLabels[terms.specialization]}, ${gradeLabels[terms.grade]}`}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Тип предложения</dt>
|
||||
<dd>{offerTypeLabels[terms.offer_type]}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Задачи</dt>
|
||||
<dd>
|
||||
<ul className={styles.list}>
|
||||
{terms.tasks.map((task, index) => (
|
||||
<li key={`${index}-${task}`}>{task}</li>
|
||||
))}
|
||||
</ul>
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Команда</dt>
|
||||
<dd className={styles.multiline}>{terms.team}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Технологии</dt>
|
||||
<dd>{terms.tech_stack.join(", ")}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Формат работы</dt>
|
||||
<dd>{terms.work_formats.map((format) => workFormatLabels[format]).join(", ")}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Место работы</dt>
|
||||
<dd>{location}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Зарплатная вилка</dt>
|
||||
<dd data-term="salary">{formatSalaryRange(terms.salary)}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Способ связи после принятия</dt>
|
||||
<dd data-term="communication">
|
||||
{communicationChannelLabels[terms.communication_method.channel]}
|
||||
{terms.communication_method.details
|
||||
? `. ${terms.communication_method.details}`
|
||||
: null}
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Пакет</dt>
|
||||
<dd>
|
||||
<dl className={styles.package}>
|
||||
{packageItemKeys.map((key) => {
|
||||
const item = terms.package[key];
|
||||
return (
|
||||
<div key={key} className={styles.fact} data-package={key}>
|
||||
<dt>{packageItemLabels[key]}</dt>
|
||||
<dd>{item.status === "provided" ? item.description : notProvidedLabel}</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Срок ответа</dt>
|
||||
<dd>
|
||||
{responseDeadlineAt ? (
|
||||
<>
|
||||
{"До "}
|
||||
<time dateTime={responseDeadlineAt}>
|
||||
{formatServerMoment(responseDeadlineAt)}
|
||||
</time>
|
||||
</>
|
||||
) : (
|
||||
`${responsePeriodLabel(responsePeriodDays)} с момента доставки`
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
<InvitationTermsArticle
|
||||
terms={terms}
|
||||
responsePeriodDays={responsePeriodDays}
|
||||
responseDeadlineAt={responseDeadlineAt}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { candidateTerms, openDeadline } from "../../../entities/invitation/testing";
|
||||
import { InvitationTermsArticle } from "./invitation-terms";
|
||||
|
||||
describe("invitation terms article", () => {
|
||||
it("shows the server deadline with its UTC label when the invitation is delivered", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationTermsArticle
|
||||
terms={candidateTerms}
|
||||
responsePeriodDays={null}
|
||||
responseDeadlineAt={openDeadline}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toMatch(/<dt>Срок ответа<\/dt><dd>До <time dateTime="2099-10-16T10:00:00Z">/);
|
||||
expect(html).toMatch(/UTC<\/time>/);
|
||||
});
|
||||
|
||||
it("shows the answer period for an unsent draft and no deadline row without either", () => {
|
||||
const draft = renderToStaticMarkup(
|
||||
<InvitationTermsArticle
|
||||
terms={candidateTerms}
|
||||
responsePeriodDays={7}
|
||||
responseDeadlineAt={null}
|
||||
/>,
|
||||
);
|
||||
expect(draft).toContain("7 дней с момента доставки");
|
||||
|
||||
const bare = renderToStaticMarkup(
|
||||
<InvitationTermsArticle
|
||||
terms={candidateTerms}
|
||||
responsePeriodDays={null}
|
||||
responseDeadlineAt={null}
|
||||
/>,
|
||||
);
|
||||
expect(bare).not.toContain("Срок ответа");
|
||||
});
|
||||
|
||||
it("uses the heading level of the page outline", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationTermsArticle
|
||||
terms={candidateTerms}
|
||||
responsePeriodDays={null}
|
||||
responseDeadlineAt={null}
|
||||
headingLevel={3}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toMatch(/<h3 class="[^"]*">Middle Go-разработчик/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { InvitationTerms } from "../../../shared/api/schemas";
|
||||
import {
|
||||
communicationChannelLabels,
|
||||
formatSalaryRange,
|
||||
formatServerMoment,
|
||||
notProvidedLabel,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
} from "../../../entities/invitation";
|
||||
import { gradeLabels, specializationLabels, workFormatLabels } from "../../../entities/match";
|
||||
import styles from "./invitation-preview.module.css";
|
||||
|
||||
type InvitationTermsArticleProps = {
|
||||
terms: InvitationTerms;
|
||||
/**
|
||||
* Days to answer, shown while no deadline exists yet (an unsent draft).
|
||||
* Null when the server deadline is shown instead.
|
||||
*/
|
||||
responsePeriodDays: number | null;
|
||||
/** The server deadline once the invitation is delivered; null for an unsent draft. */
|
||||
responseDeadlineAt: string | null;
|
||||
/** The role name is a heading below the section title; the page outline sets its level. */
|
||||
headingLevel?: 3 | 4;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every term of an invitation, as the candidate sees it: each package
|
||||
* condition with its description or as explicitly not provided, the salary
|
||||
* range with its tax basis, and the answer deadline. It renders data only.
|
||||
* Both the organization preview and the candidate's invitation use it.
|
||||
*/
|
||||
export function InvitationTermsArticle({
|
||||
terms,
|
||||
responsePeriodDays,
|
||||
responseDeadlineAt,
|
||||
headingLevel = 4,
|
||||
}: InvitationTermsArticleProps) {
|
||||
const location =
|
||||
terms.location ??
|
||||
(terms.work_formats.every((format) => format === "remote")
|
||||
? "Не требуется: только удаленная работа"
|
||||
: "Не указано");
|
||||
const RoleHeading = headingLevel === 3 ? "h3" : "h4";
|
||||
const responseLine =
|
||||
responseDeadlineAt !== null ? (
|
||||
<>
|
||||
{"До "}
|
||||
<time dateTime={responseDeadlineAt}>{formatServerMoment(responseDeadlineAt)}</time>
|
||||
</>
|
||||
) : responsePeriodDays !== null ? (
|
||||
`${responsePeriodLabel(responsePeriodDays)} с момента доставки`
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<article className={styles.terms} aria-label="Условия приглашения">
|
||||
<RoleHeading className={styles.role}>{terms.role_title}</RoleHeading>
|
||||
<dl className={styles.facts}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Специализация и грейд</dt>
|
||||
<dd>{`${specializationLabels[terms.specialization]}, ${gradeLabels[terms.grade]}`}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Тип предложения</dt>
|
||||
<dd>{offerTypeLabels[terms.offer_type]}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Задачи</dt>
|
||||
<dd>
|
||||
<ul className={styles.list}>
|
||||
{terms.tasks.map((task, index) => (
|
||||
<li key={`${index}-${task}`}>{task}</li>
|
||||
))}
|
||||
</ul>
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Команда</dt>
|
||||
<dd className={styles.multiline}>{terms.team}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Технологии</dt>
|
||||
<dd>{terms.tech_stack.join(", ")}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Формат работы</dt>
|
||||
<dd>{terms.work_formats.map((format) => workFormatLabels[format]).join(", ")}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Место работы</dt>
|
||||
<dd>{location}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Зарплатная вилка</dt>
|
||||
<dd data-term="salary">{formatSalaryRange(terms.salary)}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Способ связи после принятия</dt>
|
||||
<dd data-term="communication">
|
||||
{communicationChannelLabels[terms.communication_method.channel]}
|
||||
{terms.communication_method.details ? `. ${terms.communication_method.details}` : null}
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Пакет</dt>
|
||||
<dd>
|
||||
<dl className={styles.package}>
|
||||
{packageItemKeys.map((key) => {
|
||||
const item = terms.package[key];
|
||||
return (
|
||||
<div key={key} className={styles.fact} data-package={key}>
|
||||
<dt>{packageItemLabels[key]}</dt>
|
||||
<dd>{item.status === "provided" ? item.description : notProvidedLabel}</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
</dd>
|
||||
</div>
|
||||
{responseLine !== null ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Срок ответа</dt>
|
||||
<dd>{responseLine}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user