diff --git a/frontend/README.en.md b/frontend/README.en.md
index 2a127b9..234b3d8 100644
--- a/frontend/README.en.md
+++ b/frontend/README.en.md
@@ -2,12 +2,12 @@
[Русский](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 and the employer's read of an anonymous card use the API; invitations remain a placeholder.
+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.
- `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, 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`, and the technical `system-status` widget.
-- `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)) and `company`; `src/features/` holds user actions and forms.
+- `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/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.
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)).
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
@@ -17,11 +17,11 @@ From the repository root, `make -C frontend dev` starts development and `make -C
## Routes
-| 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` |
-| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` |
+| 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` |
+| 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.
@@ -131,11 +131,25 @@ The tests take their fixtures from the named contract examples in `api/core/open
- Entry (`entities/match`). It shows the specialization, the status "Грейд подтвержден: X" or "Грейд не подтвержден" (by icon shape and text), the confirmed category with its strength on a line apart from the grade the candidate declared, the safe card context (technologies, experience, formats, expectations), and the server's explanation of sources: every `evidence_summary` row with the state "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом", or "Пробел: подтверждения нет". A `null` context value is printed as "Нет значения в карточке", because the contract does not say whether it is hidden or absent. The entry has no contact, no real identifier, and no reason why a grade is unconfirmed.
- The explanation opens with a button that carries `aria-expanded`. It is built only from the components of the response: Fit, Cov, Dom, Sem, the percentile, V, Fr, Rsp, and the final score S appear exactly as they arrived, with no rounding beyond six decimals. A neutral value (`unknown_flags`) is labelled "Нейтральное значение, не измерено" with its reason (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed`, and others). A `null` percentile is printed as "Нет значения" and no number is invented. A zero competition value is called "не штраф". An entry without a confirmed grade has only Fit and Cov: the server computes no S, percentile, or category for it, and the screen draws none. Unknowns outside the scores (experience, formats, expectations, the assessment result) are listed under "Что неизвестно" with a note that they are not an absence of ability.
- Opening a card. The "Открыть карточку" button reads `GET /organizations/{org_id}/candidate-cards/{handle}` and, when the card has categories, the evidence section as well; the server refuses the section for a card without categories, so the request is not sent. Reads are neither retried automatically nor cached after the panel leaves the screen (`gcTime: 0`, no refetch on focus), because every read is an entry in the candidate's access history. A closed panel stays mounted, and opening it again does not read the card again. A 429 shows "Квота просмотров карточек исчерпана" and the time from `Retry-After`; when the server named none, no time is invented. A 404 replaces every hidden case with one text and names no reason.
-- Invitation. Every entry has a "Пригласить" button, an unconfirmed one included. It leads to `/employer/invitations` with `organization_id`, `candidate_handle`, `specialization`, and, for a need search, `need_id`. The alias is scoped to the organization and is not a candidate identifier. The invitations screen is still a placeholder, so the link lands on it for now.
+- Invitation. Every entry has a "Пригласить" button, an unconfirmed one included. It leads to `/employer/invitations/new` with `organization_id`, `candidate_handle`, `specialization`, and, for a need search, `need_id` (see [Invitation to a candidate](#invitation-to-a-candidate)). The alias is scoped to the organization and is not a candidate identifier.
- Layout. At 1280 px the form is on the left and the result on the right; below 1024 px the form sits above the result; at 360 px the entry actions stack and the facts and the explanation fold into one column. Every action works from the keyboard, focus is visible, and status is carried by text and shape, not by color.
Checks. Unit tests cover parsing and labels (`entities/match`), the request built from a draft (`features/filter-matches`), and the result markup (`widgets/match-list`). The Playwright suite `e2e/match-search.spec.ts` has two groups. The first runs on the real backend (it needs the mail and company fixtures): five synthetic candidates publish the same card with declared Backend and Networks grades, and the owner searches and checks the groups, the Backend/Networks switch for one alias, Fit and Cov against the response, a card read, an explained empty result for an impossible filter, no repeated search after a reload, and 360 px. The second group answers from a stub and covers what the stand cannot produce: the order of three groups with a confirmed Backend and unconfirmed Networks for one alias, neutral values and reasons, `truncated`, a 429 with `Retry-After`, a 404 card, errors, rights, and a need search. Confirmed groups are not checked on the real backend: a card is served only to a group of at least five identical cards, and a confirmed category on the stand needs each of them to pass an assessment. A real exhausted quota and hiding or revoking C2 from the employer's browser are not checked either.
+## Invitation to a candidate
+
+`/employer/invitations/new` (`pages/invitation-compose`) opens from the "Пригласить" button of a search result. The candidate is named only by the alias of the entry (`candidate_handle`, shortened on screen); an address without an alias offers to go to the search. The contract is in the [API](../api/README.en.md#invitations-and-contact-grants).
+
+- Access. As with the search, only the active owner of the company in `organization_id` can use the screen: the company list is read on every visit, and a member with another role gets no send button ("Нужны права владельца компании"). The server checks the role itself and answers 403; the form shows it as lost access.
+- Form (`features/send-invitation`). The fields follow `InvitationTerms` and nothing more: the role, the specialization (from the search entry), the grade, the offer type, the tasks (one per line), the team, the technologies, the work formats and the place of work, the channel with an optional note, the range in rubles with an explicit basis (net or gross), the four package conditions, and a response period of 3, 7, or 14 days. Each package condition is chosen explicitly: "Предусмотрено" with a description or "Не предусмотрено"; nothing is preselected. For a need search the form is prefilled only with the confirmed requirements of the need, and the draft refers to its `requirements_version`.
+- Checks before a request. The client repeats the contract rules: required fields and lengths, a range in whole rubles with a step of 1000, a lower bound below the upper one, and a width from 10% to 40% of the midpoint (`entities/invitation/model/salary-range.ts`), a place of work for office and hybrid, and a technology repeated in another letter case. With an incomplete range, no communication method, or an unanswered package condition nothing is sent. Issues are listed in a focused summary at the top of the form and bound to their fields with `aria-invalid` and `aria-describedby`.
+- The server decides. RFC 9457 errors from `errors[].pointer` are mapped to form fields (`fieldOfPointer`, for example `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); server text is not shown. `/candidate_handle` and `/need` give a general message without the reason.
+- Preview (`widgets/invitation-preview`). "Показать предпросмотр" checks the form and shows the company card from `candidate_card` (`GET /organizations/{org_id}`) and every term as the candidate will see them; focus moves to the preview. The preview sends nothing and creates no draft. When the form changes, a note says the preview is out of date.
+- Sending. "Отправить приглашение" runs a command of three operations (`features/send-invitation/model/send-command.ts`): `CreateOrganizationInvitation` with an Idempotency-Key, `UpdateOrganizationInvitation` with `expected_version` when the terms of a saved draft changed, then `SendOrganizationInvitation` with its own Idempotency-Key. The create key is bound to the request body and the send key to the draft and its version; both are kept until the command completes, so a click after a lost response, a 5xx, or 409 `idempotency_in_progress` repeats the same key. A click while the command runs starts nothing. After 412 the form reads the draft again and applies its terms on the next send. Responses are checked with the generated Zod schema.
+- Result. After a successful send the screen shows the state "Доставлено", the delivery moment and the response deadline from the server response (`response_deadline_at`, in UTC), the terms version, the salary indicator, and the sent terms; focus moves to the heading. Once a draft exists its `invitation_id` is written to the address: a reload reopens an unsent draft for sending or a sent invitation with its stored deadline.
+
+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.
+
## Support and manual assessment
`/candidate/support/cases` and `/employer/support/cases` show each account's paginated support history. Their `.../new` routes create a case and `.../:caseId` routes show its status and history. The public `/support` route directs a signed-in user to their cabinet. The form draft stays in memory, and a retry of an unchanged request reuses its idempotency key. Support history is scoped to the current account and cleared when the session changes or the server denies access.
diff --git a/frontend/README.md b/frontend/README.md
index 09d3c3c..ea59956 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -2,12 +2,12 @@
Русский | [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/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, виджет истории результатов `assessment-history`, виджет выдачи подбора `match-list` и технический виджет `system-status`.
-- `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)) и `company`; `src/features/` - действия пользователя и формы.
+- `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-моками.
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)).
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
@@ -17,11 +17,11 @@ 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` |
-| Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` |
+| Группа | Пути | Оболочка |
+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
+| Публичная | `/`, `/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` |
+| Работодатель | `/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, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере.
@@ -131,11 +131,25 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
- Запись (`entities/match`). Показаны специализация, статус "Грейд подтвержден: X" или "Грейд не подтвержден" (форма значка и текст), подтвержденная категория и сила подтверждения отдельной строкой от заявленного кандидатом грейда, безопасный контекст карточки (технологии, опыт, форматы, ожидания) и серверное объяснение источников: каждая строка `evidence_summary` с состоянием "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом" или "Пробел: подтверждения нет". Значение `null` из контекста выводится как "Нет значения в карточке": контракт не говорит, скрыто оно или отсутствует. Контактов, настоящего идентификатора и причин отсутствия подтверждения в записи нет.
- Объяснение раскрывается кнопкой с `aria-expanded`. Оно строится только из компонентов ответа: Fit, Cov, Dom, Sem, перцентиль, V, Fr, Rsp и итоговый балл S показаны ровно так, как пришли, без округления сверх шести знаков. Нейтральное значение (`unknown_flags`) подписано "Нейтральное значение, не измерено" с причиной (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed` и другие). Перцентиль `null` выводится как "Нет значения", число не выдумывается. Нулевой соревновательный вклад назван "не штрафом". У записи без подтвержденного грейда есть только Fit и Cov: балла S, перцентиля и категории для нее не считают, и экран их не рисует. Неизвестное вне баллов (опыт, форматы, ожидания, результат проверки) перечислено в блоке "Что неизвестно" с пометкой, что это не отсутствие способности.
- Открытие карточки. Кнопка "Открыть карточку" читает `GET /organizations/{org_id}/candidate-cards/{handle}`, а при наличии категорий - и раздел доказательств; без категорий сервер раздел не отдает, поэтому запрос не отправляется. Чтения не повторяются автоматически и не кешируются после ухода с экрана (`gcTime: 0`, без обновления при фокусе): каждое чтение попадает в журнал доступа кандидата. Закрытая панель остается в дереве, повторное открытие не читает карточку снова. Ответ 429 показывает "Квота просмотров карточек исчерпана" и время из `Retry-After`; если сервер его не назвал, время не выдумывается. Ответ 404 одним текстом заменяет все скрытые случаи и не называет причину.
-- Приглашение. Кнопка "Пригласить" есть у каждой записи, в том числе у неподтвержденной. Она ведет на `/employer/invitations` с параметрами `organization_id`, `candidate_handle`, `specialization` и, для поиска по потребности, `need_id`. Псевдоним привязан к организации и не является идентификатором кандидата. Экран приглашений остается заготовкой, поэтому ссылка пока приводит на нее.
+- Приглашение. Кнопка "Пригласить" есть у каждой записи, в том числе у неподтвержденной. Она ведет на `/employer/invitations/new` с параметрами `organization_id`, `candidate_handle`, `specialization` и, для поиска по потребности, `need_id` (см. [приглашение кандидату](#приглашение-кандидату)). Псевдоним привязан к организации и не является идентификатором кандидата.
- Раскладка. На 1280 px форма слева, выдача справа; ниже 1024 px форма стоит над выдачей; на 360 px действия записи идут в столбец, а факты и объяснение складываются в один столбец. Все действия доступны с клавиатуры, фокус виден, статус кодируется текстом и формой, а не цветом.
Проверки. Модульные тесты: разбор и подписи (`entities/match`), сборка запроса из черновика (`features/filter-matches`), разметка выдачи (`widgets/match-list`). Playwright `e2e/match-search.spec.ts` состоит из двух групп. Первая работает на реальном бэкенде (нужны почтовая и компанийная фикстуры): пять синтетических кандидатов публикуют одинаковую карточку с заявленными грейдами Backend и сетей, владелец ищет, проверяет группы, переключение Backend/Сети для одного псевдонима, сравнение Fit и Cov с ответом, чтение карточки, объясненную пустую выдачу при невыполнимом фильтре, отсутствие повторного поиска после перезагрузки и 360 px. Вторая группа отвечает из заглушки и проверяет то, чего стенд не создает: порядок трех групп с подтвержденным Backend и неподтвержденными сетями у одного псевдонима, нейтральные значения и причины, `truncated`, 429 с `Retry-After`, 404 карточки, ошибки, права и поиск по потребности. Подтвержденные группы на реальном бэкенде не проверены: карточка отдается группе не меньше пяти одинаковых карточек, а подтвержденная категория на стенде требует прохождения проверки каждым из них. Реальная исчерпанная квота и скрытие или отзыв C2 из браузера работодателя тоже не проверены.
+## Приглашение кандидату
+
+`/employer/invitations/new` (`pages/invitation-compose`) открывается кнопкой "Пригласить" из выдачи подбора. Кандидат назван только псевдонимом записи (`candidate_handle`, на экране сокращенно); адрес без псевдонима предлагает перейти к поиску. Контракт описан в [API](../api/README.md#приглашения-и-контактные-разрешения).
+
+- Доступ. Как и поиск, экран доступен только активному владельцу компании из `organization_id`: список компаний читается при каждом заходе, у участника с другой ролью кнопки отправки нет ("Нужны права владельца компании"). Сервер проверяет роль сам и отвечает 403; форма показывает это как потерю доступа.
+- Форма (`features/send-invitation`). Поля повторяют `InvitationTerms` и ничего сверх: роль, специализация (из записи поиска), грейд, тип предложения, задачи (по одной в строке), команда, технологии, форматы и место работы, канал связи с необязательным комментарием, вилка в рублях с явной базой (net или gross), четыре условия пакета и срок ответа 3, 7 или 14 дней. Каждое условие пакета выбирается явно: "Предусмотрено" с описанием или "Не предусмотрено"; по умолчанию не выбрано ничего. При поиске по потребности форма заполняется только подтвержденными требованиями потребности, а в черновик уходит ссылка на ее `requirements_version`.
+- Проверка до запроса. Клиент повторяет правила контракта: обязательные поля и длины, вилка из целых рублей с шагом 1 000, нижняя граница меньше верхней, ширина от 10% до 40% середины (`entities/invitation/model/salary-range.ts`), место работы для офиса и гибрида, повтор технологии без учета регистра. С неполной вилкой, без способа связи или без выбора в пакете запрос не отправляется. Ошибки собираются в список с фокусом в начале формы и привязаны к полям через `aria-invalid` и `aria-describedby`.
+- Ответ сервера главнее. Ошибки RFC 9457 из `errors[].pointer` переводятся в поля формы (`fieldOfPointer`, например `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); текст сервера не показывается. `/candidate_handle` и `/need` дают общее сообщение без причины.
+- Предпросмотр (`widgets/invitation-preview`). "Показать предпросмотр" проверяет форму и показывает карточку компании из `candidate_card` (`GET /organizations/{org_id}`) и все условия так, как их увидит кандидат; фокус переходит на предпросмотр. Предпросмотр ничего не отправляет и не создает черновик. Если форма изменилась, над ним появляется пометка, что он устарел.
+- Отправка. "Отправить приглашение" выполняет команду из трех операций (`features/send-invitation/model/send-command.ts`): `CreateOrganizationInvitation` с Idempotency-Key, при изменившихся условиях сохраненного черновика `UpdateOrganizationInvitation` с `expected_version`, затем `SendOrganizationInvitation` с отдельным Idempotency-Key. Ключ создания привязан к телу запроса, ключ отправки - к черновику и его версии; оба сохраняются, пока команда не завершится, поэтому повторное нажатие после потерянного ответа, 5xx или 409 `idempotency_in_progress` повторяет тот же ключ. Нажатие во время выполнения ничего не запускает. После 412 форма перечитывает черновик и применит свои условия при следующей отправке. Ответы проверяются сгенерированной схемой Zod.
+- Результат. После успешной отправки экран показывает состояние "Доставлено", момент доставки и срок ответа из ответа сервера (`response_deadline_at`, в UTC), версию условий, зарплатный индикатор и отправленные условия; фокус переходит на заголовок. После создания черновика его `invitation_id` записывается в адрес: перезагрузка открывает несохраненный черновик для отправки или уже отправленное приглашение с сохраненным сроком.
+
+Проверки. Модульные тесты: правила вилки (`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/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе.
diff --git a/frontend/e2e/invitation-compose.spec.ts b/frontend/e2e/invitation-compose.spec.ts
new file mode 100644
index 0000000..cf582d6
--- /dev/null
+++ b/frontend/e2e/invitation-compose.spec.ts
@@ -0,0 +1,413 @@
+import {
+ expect,
+ test,
+ type Browser,
+ type BrowserContext,
+ type Page,
+ type Request,
+} from "@playwright/test";
+
+// The organization owner invites a candidate from a real search result
+// against the real backend. Five synthetic candidates publish the same card
+// (the card projection needs a group of five), all with a declared
+// information security intern grade that no other spec uses, so the search
+// result holds only them. Each candidate keeps a signed-in browser context,
+// so the spec reads every inbox through the candidate API and proves that
+// the preview and a rejected form send nothing, and that a repeated click on
+// a slow send and a retry after a lost response deliver exactly one
+// invitation under one Idempotency-Key.
+
+const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
+const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
+const password = "correct horse battery staple 2026";
+
+test.use({ trace: "off", screenshot: "off", video: "off" });
+
+type ApiResult = { status: number; body: unknown };
+type InboxMessage = { text?: string; html?: string };
+type InboxPage = { items: { state: string; response_deadline_at: string; role_title: string }[] };
+type SentInvitation = { id: string; state: string; response_deadline_at: string | null };
+
+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 {
+ 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: InboxMessage[] }).messages;
+}
+
+async function verificationToken(email: string): Promise {
+ const deadline = Date.now() + 20_000;
+ while (Date.now() < deadline) {
+ const message = (await readMailbox(email)).at(-1);
+ if (message) {
+ const content = `${message.text ?? ""}\n${message.html ?? ""}`;
+ const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
+ if (!token) throw new Error("The registration message had no verification link.");
+ return token;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ throw new Error("The local mailbox did not receive the verification message.");
+}
+
+// Registers, confirms, and signs in a synthetic account.
+async function createAccount(page: Page, scenario: "candidate" | "employer"): Promise {
+ const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8);
+ const email =
+ scenario === "employer" ? `inviter-${suffix}@example.test` : `invitee-${suffix}@example.test`;
+ await page.goto("/register");
+ await page.getByLabel("Электронная почта").fill(email);
+ await page.getByLabel("Пароль", { exact: true }).fill(password);
+ await page
+ .getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ })
+ .check();
+ await page.getByRole("checkbox", { name: /принимаю его/ }).check();
+ await page.getByRole("button", { name: "Создать аккаунт" }).click();
+ await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
+
+ const verificationUrl = new URL("/verify-email", baseUrl());
+ verificationUrl.hash = `token=${await verificationToken(email)}`;
+ await page.goto(verificationUrl.toString());
+ await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
+ await page.getByRole("button", { name: "Подтвердить почту" }).click();
+ await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
+
+ await page.goto(scenario === "employer" ? "/employer/company" : "/candidate");
+ await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
+ await page.getByLabel("Электронная почта").fill(email);
+ await page.getByLabel("Пароль", { exact: true }).fill(password);
+ const loginResponse = page.waitForResponse(
+ (response) =>
+ response.request().method() === "POST" &&
+ new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
+ response.status() === 201,
+ );
+ await page.getByRole("button", { name: "Войти" }).click();
+ await loginResponse;
+}
+
+// Calls the API from the page, so the cookie and the origin are the browser's.
+async function api(page: Page, method: string, path: string, body?: unknown): Promise {
+ return page.evaluate(
+ async ({ method, path, body }) => {
+ const headers: Record = {};
+ if (method !== "GET") {
+ const session = await fetch("/api/v1/identity/sessions/current", {
+ credentials: "include",
+ });
+ headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token;
+ headers["Idempotency-Key"] = crypto.randomUUID();
+ }
+ if (body !== undefined) headers["Content-Type"] = "application/json";
+ const response = await fetch(path, {
+ method,
+ headers,
+ credentials: "include",
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json().catch(() => null) };
+ },
+ { method, path, body },
+ );
+}
+
+type Candidate = { context: BrowserContext; page: Page };
+
+// A candidate with one declared specialization, no test, an active C2, and a
+// published card that holds only the self-assessment.
+async function publishCandidate(browser: Browser): Promise {
+ const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
+ const page = await context.newPage();
+ await createAccount(page, "candidate");
+ const profile = await api(page, "PUT", "/api/v1/me/profile", {
+ expected_version: 0,
+ full_name: { value: "Приглашаемый кандидат", status: "confirmed" },
+ contacts: { email: null, phone: null, telegram: null },
+ stack: [],
+ roles: [
+ {
+ specialization: "information_security",
+ self_assessed_grade: "intern",
+ 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 };
+}
+
+/**
+ * Every invitation in the inboxes of the given candidates. The reads run one
+ * after another: the stand shares one client address for all browser tests,
+ * and a burst would spend its request rate.
+ */
+async function inboxItems(candidates: readonly Candidate[]): Promise {
+ const items: InboxPage["items"] = [];
+ for (const candidate of candidates) {
+ const result = await api(candidate.page, "GET", "/api/v1/me/invitations");
+ expect(result.status).toBe(200);
+ items.push(...(result.body as InboxPage).items);
+ }
+ return items;
+}
+
+function isInvitationCommand(request: Request): boolean {
+ return (
+ request.method() !== "GET" &&
+ /\/api\/v1\/organizations\/[0-9a-f-]+\/invitations/.test(new URL(request.url()).pathname)
+ );
+}
+
+async function expectNoHorizontalOverflow(page: Page): Promise {
+ for (const width of [360, 1280]) {
+ await page.setViewportSize({ width, height: 900 });
+ const overflow = await page.evaluate(
+ () => document.documentElement.scrollWidth > window.innerWidth,
+ );
+ expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
+ }
+}
+
+test.describe("organization invitation with the real backend", () => {
+ test.skip(
+ !mailFixtureEnabled || !companyFixtureEnabled,
+ "Requires the isolated mail and company fixtures.",
+ );
+
+ test("previews all terms, binds errors to fields, and delivers one invitation", async ({
+ browser,
+ page,
+ }) => {
+ test.setTimeout(480_000);
+ const candidates: Candidate[] = [];
+ try {
+ for (let index = 0; index < 5; index += 1) candidates.push(await publishCandidate(browser));
+
+ await createAccount(page, "employer");
+ const organization = await api(page, "POST", "/api/v1/organizations", {
+ name: `Invite team ${crypto.randomUUID().slice(0, 8)}`,
+ });
+ expect(organization.status).toBe(201);
+ const organizationId = (organization.body as { id: string }).id;
+ const organizationName = (organization.body as { name: string }).name;
+
+ // The invitation starts from an entry of a real search result.
+ await page.goto(`/employer/candidates?organization_id=${organizationId}`);
+ await page.getByLabel("Специализация", { exact: true }).selectOption("information_security");
+ await page.getByLabel("Заявленный кандидатом грейд").selectOption("intern");
+ const search = page.waitForResponse(
+ (response) =>
+ response.request().method() === "POST" &&
+ new URL(response.url()).pathname.endsWith("/matches"),
+ );
+ await page.getByRole("button", { name: "Найти кандидатов" }).click();
+ const result = (await (await search).json()) as {
+ groups: { unconfirmed: { candidate_handle: string }[] };
+ };
+ expect(result.groups.unconfirmed).toHaveLength(5);
+ const invite = page.getByRole("link", { name: /^Пригласить кандидата/ }).first();
+ const handle = new URL((await invite.getAttribute("href")) ?? "", baseUrl()).searchParams.get(
+ "candidate_handle",
+ );
+ await invite.click();
+ await expect(page).toHaveURL(/\/employer\/invitations\/new\?/);
+ await expect(
+ page.getByRole("heading", { level: 1, name: "Приглашение кандидату" }),
+ ).toBeVisible();
+ await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue(
+ "information_security",
+ );
+ expect(handle).toMatch(/^cv1_/);
+
+ const commands: Request[] = [];
+ page.on("request", (request) => {
+ if (isInvitationCommand(request)) commands.push(request);
+ });
+
+ // Step 1: the terms with [100000; 140000] net and a package.
+ await page.getByLabel("Название роли", { exact: true }).fill("Аналитик SOC, стажировка");
+ await page.getByLabel("Грейд", { exact: true }).selectOption("intern");
+ await page.getByLabel("Тип предложения", { exact: true }).selectOption("internship");
+ await page
+ .getByLabel("Задачи", { exact: true })
+ .fill("Разбирать события SIEM\nГотовить отчеты об инцидентах");
+ await page
+ .getByLabel("Команда", { exact: true })
+ .fill("Дежурная смена SOC: четыре аналитика и руководитель.");
+ await page.getByLabel("Технологии", { exact: true }).fill("Splunk, Suricata");
+ await page.getByRole("checkbox", { name: "Удаленно" }).check();
+ await page.getByRole("checkbox", { name: "Гибридно" }).check();
+ await page.getByLabel("Место работы", { exact: true }).fill("Казань");
+ await page.getByLabel("Канал связи", { exact: true }).selectOption("video_call");
+ await page
+ .getByLabel("Комментарий (необязательно)")
+ .fill("Созвон с руководителем смены в течение трех рабочих дней");
+ await page.getByLabel("От, ₽", { exact: true }).fill("100000");
+ await page.getByLabel("До, ₽", { exact: true }).fill("140000");
+ await page.getByLabel("База суммы", { exact: true }).selectOption("net");
+ const bonus = page.getByRole("group", { name: "Премии и бонусы" });
+ await bonus.getByRole("radio", { name: "Предусмотрено", exact: true }).check();
+ await page.getByLabel("Премии и бонусы: описание").fill("Квартальная премия до 10%");
+ const equipment = page.getByRole("group", { name: "Оборудование" });
+ await equipment.getByRole("radio", { name: "Предусмотрено", exact: true }).check();
+ await page.getByLabel("Оборудование: описание").fill("Ноутбук и второй монитор");
+ await page
+ .getByRole("group", { name: "Обучение" })
+ .getByRole("radio", { name: "Не предусмотрено", exact: true })
+ .check();
+ await page
+ .getByRole("group", { name: "ДМС" })
+ .getByRole("radio", { name: "Не предусмотрено", exact: true })
+ .check();
+
+ await page.getByRole("button", { name: "Показать предпросмотр" }).click();
+ const preview = page.getByRole("region", { name: "Предпросмотр приглашения" });
+ await expect(preview).toBeFocused();
+ await expect(preview.getByRole("heading", { name: organizationName })).toBeVisible();
+ const terms = preview.getByRole("article", { name: "Условия приглашения" });
+ for (const value of [
+ "Аналитик SOC, стажировка",
+ "Информационная безопасность, Стажер",
+ "Стажировка",
+ "Разбирать события SIEM",
+ "Готовить отчеты об инцидентах",
+ "Дежурная смена SOC: четыре аналитика и руководитель.",
+ "Splunk, Suricata",
+ "Удаленно, Гибридно",
+ "Казань",
+ "Видеозвонок. Созвон с руководителем смены в течение трех рабочих дней",
+ "Квартальная премия до 10%",
+ "Ноутбук и второй монитор",
+ "7 дней с момента доставки",
+ ]) {
+ await expect(terms).toContainText(value);
+ }
+ await expect(terms.locator('[data-term="salary"]')).toHaveText(
+ /^от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)$/,
+ );
+ await expect(terms.locator('[data-package="training"] dd')).toHaveText("Не предусмотрено");
+ await expect(terms.locator('[data-package="health_insurance"] dd')).toHaveText(
+ "Не предусмотрено",
+ );
+ // The preview is local: no command, nothing in any inbox.
+ expect(commands).toEqual([]);
+ expect(await inboxItems(candidates)).toEqual([]);
+
+ // Step 2: without the communication method the form refuses to send.
+ const channel = page.getByLabel("Канал связи", { exact: true });
+ await channel.selectOption({ index: 0 });
+ await page.getByRole("button", { name: "Отправить приглашение" }).click();
+ const summary = page.getByRole("alert").filter({ hasText: "Проверьте условия приглашения" });
+ await expect(summary).toBeFocused();
+ await expect(channel).toHaveAttribute("aria-invalid", "true");
+ await expect(channel).toHaveAccessibleDescription(
+ "Выберите способ связи после принятия приглашения.",
+ );
+ await expect(page.getByText("Условия изменены после предпросмотра")).toBeVisible();
+ expect(commands).toEqual([]);
+ expect(await inboxItems(candidates)).toEqual([]);
+
+ // Step 3: a slow send whose first response is lost, clicked twice and
+ // then retried. The browser keeps the key until the command completes.
+ await channel.selectOption("video_call");
+ await expect(channel).toHaveAttribute("aria-invalid", "false");
+ let sendAttempts = 0;
+ let delivered: SentInvitation | null = null;
+ await page.route("**/api/v1/organizations/*/invitations/*/send", async (route) => {
+ sendAttempts += 1;
+ const response = await route.fetch();
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ if (sendAttempts === 1) {
+ await route.abort("connectionreset");
+ return;
+ }
+ delivered = (await response.json()) as SentInvitation;
+ await route.fulfill({ response });
+ });
+ const sendButton = page.getByRole("button", { name: "Отправить приглашение" });
+ await sendButton.click();
+ await expect.poll(() => sendAttempts).toBe(1);
+ await expect(sendButton).toHaveAttribute("aria-busy", "true");
+ // The second click during the slow request starts nothing.
+ await sendButton.click({ force: true });
+ await expect(page.getByText("Сервер не подтвердил результат")).toBeVisible();
+ await expect(sendButton).not.toHaveAttribute("aria-busy", "true");
+ expect(sendAttempts).toBe(1);
+
+ await sendButton.click();
+ await expect.poll(() => sendAttempts).toBe(2);
+ await sendButton.click({ force: true });
+ const resultHeading = page.getByRole("heading", { level: 2, name: "Приглашение доставлено" });
+ await expect(resultHeading).toBeFocused({ timeout: 15_000 });
+ await page.unroute("**/api/v1/organizations/*/invitations/*/send");
+
+ const creates = commands.filter((request) =>
+ new URL(request.url()).pathname.endsWith("/invitations"),
+ );
+ const sends = commands.filter((request) => new URL(request.url()).pathname.endsWith("/send"));
+ expect(creates).toHaveLength(1);
+ expect(sends).toHaveLength(2);
+ const sendKeys = await Promise.all(
+ sends.map((request) => request.headerValue("idempotency-key")),
+ );
+ expect(sendKeys[0]).toBeTruthy();
+ expect(sendKeys[1]).toBe(sendKeys[0]);
+ expect(await creates[0]?.headerValue("idempotency-key")).not.toBe(sendKeys[0]);
+
+ const sent = delivered as SentInvitation | null;
+ if (!sent?.response_deadline_at) throw new Error("The send returned no deadline.");
+ expect(sent.state).toBe("delivered");
+ await expect(page.locator('[data-state="delivered"]')).toHaveText("Доставлено");
+ const deadline = page.locator('[data-term="deadline"] time');
+ await expect(deadline).toHaveAttribute("datetime", sent.response_deadline_at);
+
+ // One invitation in exactly one inbox, with the deadline the UI shows.
+ const inbox = await inboxItems(candidates);
+ expect(inbox).toHaveLength(1);
+ expect(inbox[0]).toMatchObject({
+ state: "delivered",
+ role_title: "Аналитик SOC, стажировка",
+ response_deadline_at: sent.response_deadline_at,
+ });
+
+ // The address keeps the invitation, so a reload shows the stored deadline.
+ await expect(page).toHaveURL(new RegExp(`invitation_id=${sent.id}`));
+ await page.reload();
+ await expect(page.locator('[data-state="delivered"]')).toHaveText("Доставлено");
+ await expect(page.locator('[data-term="deadline"] time')).toHaveAttribute(
+ "datetime",
+ sent.response_deadline_at,
+ );
+ await expectNoHorizontalOverflow(page);
+ expect(await inboxItems(candidates)).toHaveLength(1);
+ } finally {
+ await Promise.all(candidates.map((candidate) => candidate.context.close()));
+ }
+ });
+});
diff --git a/frontend/e2e/match-search.spec.ts b/frontend/e2e/match-search.spec.ts
index 9d99c5b..cf30c36 100644
--- a/frontend/e2e/match-search.spec.ts
+++ b/frontend/e2e/match-search.spec.ts
@@ -810,7 +810,7 @@ test.describe("employer candidate search with a stubbed API", () => {
await captureReview(page, "match-search-three-groups");
});
- test("invites an unconfirmed profile and carries the alias to the invitation section", async ({
+ test("invites an unconfirmed profile and carries the alias to the invitation form", async ({
page,
}) => {
await installFakeApi(page);
@@ -824,9 +824,11 @@ test.describe("employer candidate search with a stubbed API", () => {
const invite = page.getByRole("link", { name: /^Пригласить/ });
await expect(invite).toBeVisible();
await invite.click();
- await expect(page.getByRole("heading", { level: 1, name: "Приглашения" })).toBeVisible();
+ await expect(
+ page.getByRole("heading", { level: 1, name: "Приглашение кандидату" }),
+ ).toBeVisible();
const url = new URL(page.url());
- expect(url.pathname).toBe("/employer/invitations");
+ expect(url.pathname).toBe("/employer/invitations/new");
expect(url.searchParams.get("organization_id")).toBe(orgId);
expect(url.searchParams.get("candidate_handle")).toBe(handleA);
expect(url.searchParams.get("specialization")).toBe("network_engineer");
diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx
index 480e8d3..f6602f9 100644
--- a/frontend/src/app/router/routes.test.tsx
+++ b/frontend/src/app/router/routes.test.tsx
@@ -173,6 +173,7 @@ describe("route groups", () => {
["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"],
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
+ ["/employer/invitations/new", "Приглашение кандидату", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
const html = await renderHtml(path);
diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx
index d709375..2e3a4bc 100644
--- a/frontend/src/app/router/routes.tsx
+++ b/frontend/src/app/router/routes.tsx
@@ -7,6 +7,7 @@ import { CompanyPage } from "../../pages/company";
import { PrivacyPage } from "../../pages/privacy";
import { SessionGate } from "../../entities/session";
import { MatchesPage } from "../../pages/matches";
+import { InvitationComposePage } from "../../pages/invitation-compose";
import { NotFoundPage } from "../../pages/not-found";
import { NeedEditorPage } from "../../pages/need-editor";
import { NeedListPage } from "../../pages/needs";
@@ -131,6 +132,7 @@ export const routes: RouteObject[] = [
path: paths.employer.invitations,
element: ,
},
+ { path: paths.employer.invitationNew, element: },
{ path: paths.employer.notifications, element: },
{
path: "*",
diff --git a/frontend/src/entities/company/index.ts b/frontend/src/entities/company/index.ts
index 488b611..d957a12 100644
--- a/frontend/src/entities/company/index.ts
+++ b/frontend/src/entities/company/index.ts
@@ -13,4 +13,4 @@ export {
organizationTrustLevel,
candidateCardLevelLabels,
} from "./model/verification-labels";
-export { CandidateCardPreview } from "./ui/candidate-card-preview";
+export { CandidateCardPreview, CompanyCardView } from "./ui/candidate-card-preview";
diff --git a/frontend/src/entities/company/ui/candidate-card-preview.module.css b/frontend/src/entities/company/ui/candidate-card-preview.module.css
index 1e374e2..c41ffed 100644
--- a/frontend/src/entities/company/ui/candidate-card-preview.module.css
+++ b/frontend/src/entities/company/ui/candidate-card-preview.module.css
@@ -63,7 +63,8 @@
gap: var(--space-2);
}
-.representatives h4 {
+.representatives h4,
+.representatives h5 {
font-weight: var(--font-weight-bold);
}
diff --git a/frontend/src/entities/company/ui/candidate-card-preview.tsx b/frontend/src/entities/company/ui/candidate-card-preview.tsx
index 901147f..97b7f23 100644
--- a/frontend/src/entities/company/ui/candidate-card-preview.tsx
+++ b/frontend/src/entities/company/ui/candidate-card-preview.tsx
@@ -16,55 +16,74 @@ const contactLabels = {
telegram: "Telegram компании",
} as const;
-export function CandidateCardPreview({ card }: CandidateCardPreviewProps) {
+type CompanyCardViewProps = {
+ card: CandidateCard;
+ /** Level of the company name heading inside the surrounding outline. */
+ headingLevel?: 3 | 4;
+};
+
+/**
+ * The card of the organization exactly as a candidate sees it, built from
+ * `candidate_card` that the server returns to the owner. It shows no
+ * membership, role, account, or verification basis.
+ */
+export function CompanyCardView({ card, headingLevel = 3 }: CompanyCardViewProps) {
const contacts = (Object.keys(contactLabels) as (keyof typeof contactLabels)[]).flatMap((key) => {
const value = card.contacts[key];
return value ? [{ label: contactLabels[key], value }] : [];
});
+ const NameHeading = headingLevel === 3 ? "h3" : "h4";
+ const SubHeading = headingLevel === 3 ? "h4" : "h5";
+ return (
+
+
+
}
+ terms={{ ...terms, location: null, work_formats: ["remote"] }}
+ responsePeriodDays={7}
+ responseDeadlineAt="2026-10-16T10:00:00Z"
+ />,
+ );
+
+ expect(html).toContain("Карточка недоступна");
+ expect(html).toContain('");
+ expect(text(html)).toContain("Не требуется: только удаленная работа");
+ });
+});
diff --git a/frontend/src/widgets/invitation-preview/ui/invitation-preview.tsx b/frontend/src/widgets/invitation-preview/ui/invitation-preview.tsx
new file mode 100644
index 0000000..ae06cfc
--- /dev/null
+++ b/frontend/src/widgets/invitation-preview/ui/invitation-preview.tsx
@@ -0,0 +1,146 @@
+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 styles from "./invitation-preview.module.css";
+
+type InvitationPreviewProps = {
+ /** The company card as the candidate sees it, or null while it is unavailable. */
+ card: CandidateOrganizationCard | null;
+ /** What to show instead of the card, for example a loading or error state. */
+ cardFallback?: ReactNode;
+ terms: InvitationTerms;
+ responsePeriodDays: number;
+ /** The server deadline once the invitation is delivered; null for an unsent draft. */
+ responseDeadlineAt: string | null;
+ title?: string;
+};
+
+/**
+ * The invitation through the eyes of the candidate: the company card and
+ * every term, each condition of the package shown either with its
+ * description or as explicitly not provided. It renders data only and sends
+ * nothing; the same view serves the preview of a draft and a sent invitation.
+ */
+export function InvitationPreview({
+ card,
+ cardFallback,
+ terms,
+ responsePeriodDays,
+ responseDeadlineAt,
+ title = "Так приглашение увидит кандидат",
+}: InvitationPreviewProps) {
+ const location =
+ terms.location ??
+ (terms.work_formats.every((format) => format === "remote")
+ ? "Не требуется: только удаленная работа"
+ : "Не указано");
+
+ return (
+
+
+
{title}
+
+ Кандидат видит карточку компании и все условия до решения. Контакты кандидата компания
+ получит только после принятия приглашения.
+