feat(invitations): add the invitation compose screen with a candidate-side preview
This commit is contained in:
1 parent
1a067221f7
commit
cb08f212cc
35 files changed
+4170
-67
No files matched your search
+24
-10
@@ -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.
|
||||
|
||||
+24
-10
@@ -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` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе.
|
||||
|
||||
@@ -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<InboxMessage[]> {
|
||||
const inboxUrl = process.env.E2E_MAILBOX_URL;
|
||||
const token = process.env.E2E_MAILBOX_TOKEN;
|
||||
if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured.");
|
||||
const url = new URL(inboxUrl);
|
||||
url.searchParams.set("to", email);
|
||||
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
|
||||
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
|
||||
return ((await response.json()) as { messages: InboxMessage[] }).messages;
|
||||
}
|
||||
|
||||
async function verificationToken(email: string): Promise<string> {
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
const message = (await 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<void> {
|
||||
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<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 },
|
||||
);
|
||||
}
|
||||
|
||||
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<Candidate> {
|
||||
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<InboxPage["items"]> {
|
||||
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<void> {
|
||||
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()));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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: <PlaceholderPage screen="employerInvitations" />,
|
||||
},
|
||||
{ path: paths.employer.invitationNew, element: <InvitationComposePage /> },
|
||||
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
|
||||
{
|
||||
path: "*",
|
||||
|
||||
@@ -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";
|
||||
@@ -63,7 +63,8 @@
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.representatives h4 {
|
||||
.representatives h4,
|
||||
.representatives h5 {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<article className={styles.card} aria-label="Предпросмотр карточки компании">
|
||||
<header className={styles.header}>
|
||||
<div>
|
||||
<NameHeading className={styles.name}>{card.name}</NameHeading>
|
||||
<p className={styles.level}>
|
||||
<TrustLevel
|
||||
level={organizationTrustLevel[card.verification_level]}
|
||||
label={candidateCardLevelLabels[card.verification_level]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
{card.sphere ? <p className={styles.sphere}>{card.sphere}</p> : null}
|
||||
</header>
|
||||
{card.description ? <p className={styles.description}>{card.description}</p> : null}
|
||||
{contacts.length > 0 ? (
|
||||
<dl className={styles.contacts}>
|
||||
{contacts.map(({ label, value }) => (
|
||||
<div className={styles.contact} key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
{card.representatives && card.representatives.length > 0 ? (
|
||||
<div className={styles.representatives}>
|
||||
<SubHeading>Представители компании</SubHeading>
|
||||
<ul>
|
||||
{card.representatives.map((representative, index) => (
|
||||
<li key={`${representative.name}-${index}`}>
|
||||
<span>{representative.name}</span>
|
||||
<span>{representative.job_title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function CandidateCardPreview({ card }: CandidateCardPreviewProps) {
|
||||
return (
|
||||
<Section
|
||||
title="Так карточку увидит кандидат"
|
||||
description="Проверьте описание и контакты, которые увидит кандидат."
|
||||
>
|
||||
<article className={styles.card} aria-label="Предпросмотр карточки компании">
|
||||
<header className={styles.header}>
|
||||
<div>
|
||||
<h3 className={styles.name}>{card.name}</h3>
|
||||
<p className={styles.level}>
|
||||
<TrustLevel
|
||||
level={organizationTrustLevel[card.verification_level]}
|
||||
label={candidateCardLevelLabels[card.verification_level]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
{card.sphere ? <p className={styles.sphere}>{card.sphere}</p> : null}
|
||||
</header>
|
||||
{card.description ? <p className={styles.description}>{card.description}</p> : null}
|
||||
{contacts.length > 0 ? (
|
||||
<dl className={styles.contacts}>
|
||||
{contacts.map(({ label, value }) => (
|
||||
<div className={styles.contact} key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
{card.representatives && card.representatives.length > 0 ? (
|
||||
<div className={styles.representatives}>
|
||||
<h4>Представители компании</h4>
|
||||
<ul>
|
||||
{card.representatives.map((representative, index) => (
|
||||
<li key={`${representative.name}-${index}`}>
|
||||
<span>{representative.name}</span>
|
||||
<span>{representative.job_title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
<CompanyCardView card={card} />
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import {
|
||||
createOrganizationInvitation,
|
||||
getGetOrganizationInvitationQueryKey,
|
||||
getOrganizationInvitation,
|
||||
sendOrganizationInvitation,
|
||||
updateOrganizationInvitation,
|
||||
} from "../../../shared/api/endpoints/invitation/invitation";
|
||||
import {
|
||||
OrganizationInvitation as organizationInvitationSchema,
|
||||
type OrganizationInvitation,
|
||||
type OrganizationInvitationCreate,
|
||||
type OrganizationInvitationUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
// Transport adapters of the organization 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 delivered invitation.
|
||||
|
||||
function invalidResponse(): ApiRequestError {
|
||||
return new ApiRequestError({
|
||||
status: 200,
|
||||
code: invalidResponseCode,
|
||||
title: "The response does not match the API contract.",
|
||||
});
|
||||
}
|
||||
|
||||
function parseInvitation(value: unknown): OrganizationInvitation {
|
||||
const parsed = organizationInvitationSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidResponse();
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
type CommandOptions = {
|
||||
organizationId: string;
|
||||
csrfToken: string;
|
||||
signal?: AbortSignal | undefined;
|
||||
};
|
||||
|
||||
function requestOptions(csrfToken: string, signal: AbortSignal | undefined): RequestInit {
|
||||
return { headers: { "X-CSRF-Token": csrfToken }, ...(signal ? { signal } : {}) };
|
||||
}
|
||||
|
||||
/** Creates a draft under an Idempotency-Key; a retry with the same key and body replays it. */
|
||||
export async function createInvitationDraft(
|
||||
options: CommandOptions & { body: OrganizationInvitationCreate; idempotencyKey: string },
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await createOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.body,
|
||||
{ "Idempotency-Key": options.idempotencyKey },
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces the terms of a draft over the version the client read. */
|
||||
export async function updateInvitationDraft(
|
||||
options: CommandOptions & { invitationId: string; body: OrganizationInvitationUpdate },
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await updateOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.invitationId,
|
||||
options.body,
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Sends the current terms version of a draft under an Idempotency-Key. */
|
||||
export async function sendInvitationDraft(
|
||||
options: CommandOptions & {
|
||||
invitationId: string;
|
||||
expectedVersion: number;
|
||||
idempotencyKey: string;
|
||||
},
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await sendOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.invitationId,
|
||||
{ expected_version: options.expectedVersion },
|
||||
{ "Idempotency-Key": options.idempotencyKey },
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Reads one invitation of the organization and checks it against the contract. */
|
||||
export async function readOrganizationInvitation(
|
||||
organizationId: string,
|
||||
invitationId: string,
|
||||
signal: AbortSignal | undefined = undefined,
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await getOrganizationInvitation(organizationId, invitationId, signal ? { signal } : {}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Invitation reads stay separate for each signed-in account. */
|
||||
export const invitationQueryKeys = {
|
||||
detail: (accountId: string, organizationId: string, invitationId: string) =>
|
||||
[...getGetOrganizationInvitationQueryKey(organizationId, invitationId), accountId] as const,
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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.
|
||||
|
||||
export {
|
||||
createInvitationDraft,
|
||||
invitationQueryKeys,
|
||||
readOrganizationInvitation,
|
||||
sendInvitationDraft,
|
||||
updateInvitationDraft,
|
||||
} from "./api/organization-invitations";
|
||||
export { formatRubles, formatSalaryRange, formatServerMoment } from "./model/format";
|
||||
export {
|
||||
communicationChannelCodes,
|
||||
communicationChannelLabels,
|
||||
defaultResponsePeriod,
|
||||
invitationStateLabels,
|
||||
notProvidedLabel,
|
||||
offerTypeCodes,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
responsePeriods,
|
||||
salaryFitLabels,
|
||||
taxBasisLabels,
|
||||
type InvitationPackageKey,
|
||||
} from "./model/labels";
|
||||
export {
|
||||
salaryMax,
|
||||
salaryRangeIssue,
|
||||
salaryStep,
|
||||
type SalaryRangeIssue,
|
||||
} from "./model/salary-range";
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { SalaryRange } from "../../../shared/api/schemas";
|
||||
import { taxBasisLabels } from "./labels";
|
||||
|
||||
const rubles = new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 });
|
||||
|
||||
/** Whole rubles with the Russian digit grouping, for example "140 000 ₽". */
|
||||
export function formatRubles(amount: number): string {
|
||||
return `${rubles.format(amount)} ₽`;
|
||||
}
|
||||
|
||||
/** The salary range with its period and tax basis; the basis is never implied. */
|
||||
export function formatSalaryRange(salary: SalaryRange): string {
|
||||
return `от ${formatRubles(salary.salary_from)} до ${formatRubles(salary.salary_to)} в месяц, ${taxBasisLabels[salary.tax_basis].toLocaleLowerCase("ru-RU")}`;
|
||||
}
|
||||
|
||||
const moment = new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "long",
|
||||
timeStyle: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
/**
|
||||
* A server timestamp in UTC with the zone named, so the deadline reads the
|
||||
* same for both parties regardless of the browser's zone.
|
||||
*/
|
||||
export function formatServerMoment(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return `${moment.format(date)} UTC`;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
InvitationCommunicationChannel,
|
||||
InvitationOfferType,
|
||||
InvitationPackage,
|
||||
InvitationResponsePeriod,
|
||||
InvitationSalaryFit,
|
||||
InvitationState,
|
||||
SalaryTaxBasis,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export type InvitationPackageKey = keyof InvitationPackage;
|
||||
|
||||
export const offerTypeLabels: Readonly<Record<InvitationOfferType, string>> = {
|
||||
full_time: "Полная занятость",
|
||||
part_time: "Частичная занятость",
|
||||
contract: "Договор на проект или срок",
|
||||
internship: "Стажировка",
|
||||
};
|
||||
|
||||
export const offerTypeCodes = Object.keys(offerTypeLabels) as InvitationOfferType[];
|
||||
|
||||
export const communicationChannelLabels: Readonly<Record<InvitationCommunicationChannel, string>> =
|
||||
{
|
||||
email: "Электронная почта",
|
||||
phone: "Телефон",
|
||||
telegram: "Telegram",
|
||||
video_call: "Видеозвонок",
|
||||
};
|
||||
|
||||
export const communicationChannelCodes = Object.keys(
|
||||
communicationChannelLabels,
|
||||
) as InvitationCommunicationChannel[];
|
||||
|
||||
/** The four required conditions of the package in the order of the contract. */
|
||||
export const packageItemLabels: Readonly<Record<InvitationPackageKey, string>> = {
|
||||
bonus: "Премии и бонусы",
|
||||
equipment: "Оборудование",
|
||||
training: "Обучение",
|
||||
health_insurance: "ДМС",
|
||||
};
|
||||
|
||||
export const packageItemKeys = Object.keys(packageItemLabels) as InvitationPackageKey[];
|
||||
|
||||
/** Wording of an explicit `not_provided` condition, as the contract names it. */
|
||||
export const notProvidedLabel = "Не предусмотрено";
|
||||
|
||||
export const taxBasisLabels: Readonly<Record<SalaryTaxBasis, string>> = {
|
||||
net: "После налога (net)",
|
||||
gross: "До налога (gross)",
|
||||
};
|
||||
|
||||
export const responsePeriods: readonly InvitationResponsePeriod[] = [3, 7, 14];
|
||||
|
||||
export const defaultResponsePeriod: InvitationResponsePeriod = 7;
|
||||
|
||||
export function responsePeriodLabel(days: number): string {
|
||||
const lastTwo = days % 100;
|
||||
const last = days % 10;
|
||||
if (lastTwo >= 11 && lastTwo <= 14) return `${days} дней`;
|
||||
if (last === 1) return `${days} день`;
|
||||
if (last >= 2 && last <= 4) return `${days} дня`;
|
||||
return `${days} дней`;
|
||||
}
|
||||
|
||||
export const invitationStateLabels: Readonly<Record<InvitationState, string>> = {
|
||||
draft: "Черновик",
|
||||
delivered: "Доставлено",
|
||||
viewed: "Просмотрено кандидатом",
|
||||
counter: "Встречное предложение",
|
||||
accepted: "Принято",
|
||||
interview_scheduled: "Назначено интервью",
|
||||
interviewed: "Интервью проведено",
|
||||
negotiation: "Переговоры",
|
||||
terms_agreed: "Условия согласованы",
|
||||
no_deal: "Без сделки",
|
||||
declined: "Отклонено",
|
||||
expired: "Срок ответа истек",
|
||||
withdrawn: "Отозвано компанией",
|
||||
cancelled_by_candidate: "Отменено кандидатом",
|
||||
};
|
||||
|
||||
export const salaryFitLabels: Readonly<Record<InvitationSalaryFit, string>> = {
|
||||
within_range: "Ожидания кандидата не выше верхней границы вилки",
|
||||
up_to_10_percent_above: "Ожидания выше верхней границы не более чем на 10%",
|
||||
above: "Ожидания выше верхней границы более чем на 10%",
|
||||
withheld: "Индикатор временно скрыт: много изменений вилок за неделю",
|
||||
not_available: "Индикатор недоступен: кандидат не задал ожидания для этих условий",
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { salaryRangeIssue } from "./salary-range";
|
||||
|
||||
describe("salary range rules", () => {
|
||||
it.each([
|
||||
[100_000, 140_000],
|
||||
[95_000, 105_000],
|
||||
[80_000, 120_000],
|
||||
])("accepts [%i; %i], including the 10%% and 40%% edges", (from, to) => {
|
||||
expect(salaryRangeIssue(from, to)).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[100_500, 140_000, "bound"],
|
||||
[0, 140_000, "bound"],
|
||||
[100_000, 100_001_000, "bound"],
|
||||
[140_000, 100_000, "order"],
|
||||
[100_000, 100_000, "order"],
|
||||
[100_000, 105_000, "narrow"],
|
||||
[79_000, 121_000, "wide"],
|
||||
] as const)("rejects [%i; %i] as %s", (from, to, issue) => {
|
||||
expect(salaryRangeIssue(from, to)).toBe(issue);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// Client mirror of the SalaryRange rules of the contract, for immediate
|
||||
// feedback only: the server checks the same rules in integer arithmetic and
|
||||
// stays the source of truth.
|
||||
|
||||
export const salaryStep = 1000;
|
||||
export const salaryMax = 100_000_000;
|
||||
|
||||
/**
|
||||
* Why a salary range is not acceptable.
|
||||
*
|
||||
* - bound: a bound is not a positive whole multiple of 1000 within the limit.
|
||||
* - order: the lower bound is not below the upper bound.
|
||||
* - narrow: the width is below 10% of the midpoint.
|
||||
* - wide: the width is above 40% of the midpoint.
|
||||
*/
|
||||
export type SalaryRangeIssue = "bound" | "order" | "narrow" | "wide";
|
||||
|
||||
function validBound(value: number): boolean {
|
||||
return (
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= salaryStep &&
|
||||
value <= salaryMax &&
|
||||
value % salaryStep === 0
|
||||
);
|
||||
}
|
||||
|
||||
/** Checks `[from; to]`; widths of exactly 10% and 40% are accepted. */
|
||||
export function salaryRangeIssue(from: number, to: number): SalaryRangeIssue | null {
|
||||
if (!validBound(from) || !validBound(to)) return "bound";
|
||||
if (from >= to) return "order";
|
||||
const width = to - from;
|
||||
const total = from + to;
|
||||
if (20 * width < total) return "narrow";
|
||||
if (5 * width > total) return "wide";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Public API of the send-invitation feature: the draft of the terms, its
|
||||
// client validation, the idempotent create-update-send command, and the form
|
||||
// that runs it. The page supplies the preview and reacts to the result.
|
||||
|
||||
export {
|
||||
emptyInvitationDraft,
|
||||
invitationDraftFromNeed,
|
||||
invitationDraftFromTerms,
|
||||
toInvitationTerms,
|
||||
type InvitationDraft,
|
||||
} from "./model/draft";
|
||||
export { initialSendProgress, type SendProgress } from "./model/send-command";
|
||||
export {
|
||||
InvitationForm,
|
||||
type InvitationFormProps,
|
||||
type InvitationPreviewSnapshot,
|
||||
} from "./ui/invitation-form";
|
||||
@@ -0,0 +1,29 @@
|
||||
import { emptyInvitationDraft, type InvitationDraft } from "./draft";
|
||||
|
||||
/** A draft that passes validation: [100000; 140000] net and a mixed package. */
|
||||
export function completeDraft(overrides: Partial<InvitationDraft> = {}): InvitationDraft {
|
||||
const base = emptyInvitationDraft("backend");
|
||||
return {
|
||||
...base,
|
||||
roleTitle: "Middle Go-разработчик в команду платежей",
|
||||
grade: "middle",
|
||||
offerType: "full_time",
|
||||
tasks: "Развивать сервис выплат\n \nПеревести отчеты на события",
|
||||
team: "Пять бэкенд-разработчиков и QA-инженер.",
|
||||
techStack: "Go, PostgreSQL,\nKafka",
|
||||
workFormats: ["remote", "hybrid"],
|
||||
location: "Москва",
|
||||
channel: "video_call",
|
||||
channelDetails: "Созвон с тимлидом в течение трех рабочих дней",
|
||||
salaryFrom: "100000",
|
||||
salaryTo: "140000",
|
||||
taxBasis: "net",
|
||||
packageItems: {
|
||||
bonus: { status: "provided", description: "Квартальная премия до 20%" },
|
||||
equipment: { status: "provided", description: "Ноутбук и монитор" },
|
||||
training: { status: "not_provided", description: "" },
|
||||
health_insurance: { status: "not_provided", description: "" },
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import type {
|
||||
GradeCode,
|
||||
InvitationCommunicationChannel,
|
||||
InvitationOfferType,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
Need,
|
||||
SalaryTaxBasis,
|
||||
SpecializationCode,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
defaultResponsePeriod,
|
||||
packageItemKeys,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import { fromTransport } from "../../../entities/need";
|
||||
|
||||
// The form draft of an invitation. It keeps what the employer typed as
|
||||
// strings, so a half-filled field is never coerced into a default value;
|
||||
// toInvitationTerms turns a validated draft into the transport terms.
|
||||
|
||||
export type PackageChoice = "" | "provided" | "not_provided";
|
||||
|
||||
export interface PackageItemDraft {
|
||||
readonly status: PackageChoice;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface InvitationDraft {
|
||||
readonly roleTitle: string;
|
||||
readonly specialization: SpecializationCode | "";
|
||||
readonly grade: GradeCode | "";
|
||||
readonly offerType: InvitationOfferType | "";
|
||||
/** One task per line. */
|
||||
readonly tasks: string;
|
||||
readonly team: string;
|
||||
/** Technologies separated by commas or line breaks. */
|
||||
readonly techStack: string;
|
||||
readonly workFormats: readonly WorkFormat[];
|
||||
readonly location: string;
|
||||
readonly channel: InvitationCommunicationChannel | "";
|
||||
readonly channelDetails: string;
|
||||
readonly salaryFrom: string;
|
||||
readonly salaryTo: string;
|
||||
readonly taxBasis: SalaryTaxBasis | "";
|
||||
readonly packageItems: Readonly<Record<InvitationPackageKey, PackageItemDraft>>;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
}
|
||||
|
||||
const emptyPackageItem: PackageItemDraft = { status: "", description: "" };
|
||||
|
||||
/** A blank draft; no package condition is preselected, because each is an explicit choice. */
|
||||
export function emptyInvitationDraft(
|
||||
specialization: SpecializationCode | "" = "",
|
||||
): InvitationDraft {
|
||||
return {
|
||||
roleTitle: "",
|
||||
specialization,
|
||||
grade: "",
|
||||
offerType: "",
|
||||
tasks: "",
|
||||
team: "",
|
||||
techStack: "",
|
||||
workFormats: [],
|
||||
location: "",
|
||||
channel: "",
|
||||
channelDetails: "",
|
||||
salaryFrom: "",
|
||||
salaryTo: "",
|
||||
taxBasis: "",
|
||||
packageItems: Object.fromEntries(
|
||||
packageItemKeys.map((key) => [key, emptyPackageItem]),
|
||||
) as Record<InvitationPackageKey, PackageItemDraft>,
|
||||
responsePeriodDays: defaultResponsePeriod,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefills a draft from the confirmed requirements of a need. Values that
|
||||
* nobody confirmed stay empty, and the specialization of the search entry
|
||||
* wins over the need, because the invitation is for that entry.
|
||||
*/
|
||||
export function invitationDraftFromNeed(
|
||||
need: Need,
|
||||
specialization: SpecializationCode | "",
|
||||
): InvitationDraft {
|
||||
const values = fromTransport(need);
|
||||
const draft = emptyInvitationDraft(specialization);
|
||||
const confirmed = <T>(state: { status: string; value?: T }): T | undefined =>
|
||||
state.status === "confirmed" ? state.value : undefined;
|
||||
const salary = confirmed(values.salary);
|
||||
const workFormats = confirmed(values.workFormats);
|
||||
const needSpecialization = confirmed(values.specialization);
|
||||
return {
|
||||
...draft,
|
||||
roleTitle: need.title,
|
||||
specialization: specialization || needSpecialization || "",
|
||||
grade: confirmed(values.grade) ?? "",
|
||||
tasks: values.tasks
|
||||
.filter((task) => task.status === "confirmed")
|
||||
.map((task) => task.text)
|
||||
.join("\n"),
|
||||
techStack: values.requiredSkills
|
||||
.filter((skill) => skill.status === "confirmed")
|
||||
.map((skill) => skill.name)
|
||||
.join(", "),
|
||||
workFormats: workFormats ? [...workFormats] : [],
|
||||
location: confirmed(values.location) ?? "",
|
||||
salaryFrom: salary ? String(salary.from) : "",
|
||||
salaryTo: salary ? String(salary.to) : "",
|
||||
taxBasis: salary?.taxBasis ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Restores the draft of stored terms, for example when a saved draft is reopened. */
|
||||
export function invitationDraftFromTerms(
|
||||
terms: InvitationTerms,
|
||||
responsePeriodDays: InvitationResponsePeriod,
|
||||
): InvitationDraft {
|
||||
return {
|
||||
roleTitle: terms.role_title,
|
||||
specialization: terms.specialization,
|
||||
grade: terms.grade,
|
||||
offerType: terms.offer_type,
|
||||
tasks: terms.tasks.join("\n"),
|
||||
team: terms.team,
|
||||
techStack: terms.tech_stack.join(", "),
|
||||
workFormats: [...terms.work_formats],
|
||||
location: terms.location ?? "",
|
||||
channel: terms.communication_method.channel,
|
||||
channelDetails: terms.communication_method.details ?? "",
|
||||
salaryFrom: String(terms.salary.salary_from),
|
||||
salaryTo: String(terms.salary.salary_to),
|
||||
taxBasis: terms.salary.tax_basis,
|
||||
packageItems: Object.fromEntries(
|
||||
packageItemKeys.map((key) => {
|
||||
const item = terms.package[key];
|
||||
return [
|
||||
key,
|
||||
item.status === "provided"
|
||||
? { status: "provided", description: item.description }
|
||||
: { status: "not_provided", description: "" },
|
||||
];
|
||||
}),
|
||||
) as Record<InvitationPackageKey, PackageItemDraft>,
|
||||
responsePeriodDays,
|
||||
};
|
||||
}
|
||||
|
||||
/** Splits the task text into trimmed, non-empty lines. */
|
||||
export function taskLines(value: string): string[] {
|
||||
return value
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Splits the technology text at commas and line breaks. */
|
||||
export function techStackItems(value: string): string[] {
|
||||
return value
|
||||
.split(/[,\n]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function optionalLine(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed === "" ? null : trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the transport terms of a draft. Call it only for a draft without
|
||||
* validation issues: it assumes every required choice is made.
|
||||
*/
|
||||
export function toInvitationTerms(draft: InvitationDraft): InvitationTerms {
|
||||
if (
|
||||
!draft.specialization ||
|
||||
!draft.grade ||
|
||||
!draft.offerType ||
|
||||
!draft.channel ||
|
||||
!draft.taxBasis
|
||||
) {
|
||||
throw new Error("The invitation draft has an unanswered required choice.");
|
||||
}
|
||||
return {
|
||||
role_title: draft.roleTitle.trim(),
|
||||
specialization: draft.specialization,
|
||||
grade: draft.grade,
|
||||
offer_type: draft.offerType,
|
||||
tasks: taskLines(draft.tasks),
|
||||
team: draft.team.trim(),
|
||||
tech_stack: techStackItems(draft.techStack),
|
||||
work_formats: [...draft.workFormats],
|
||||
// A remote-only role may still name a place; the server requires one
|
||||
// only for the office and hybrid formats.
|
||||
location: optionalLine(draft.location),
|
||||
communication_method: {
|
||||
channel: draft.channel,
|
||||
details: optionalLine(draft.channelDetails),
|
||||
},
|
||||
salary: {
|
||||
salary_from: Number(draft.salaryFrom),
|
||||
salary_to: Number(draft.salaryTo),
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: draft.taxBasis,
|
||||
},
|
||||
package: Object.fromEntries(
|
||||
packageItemKeys.map((key) => {
|
||||
const item = draft.packageItems[key];
|
||||
return [
|
||||
key,
|
||||
item.status === "provided"
|
||||
? { status: "provided", description: item.description.trim() }
|
||||
: { status: "not_provided" },
|
||||
];
|
||||
}),
|
||||
) as InvitationTerms["package"],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import { formatRetryAfter } from "../../../entities/match";
|
||||
import { issuesOfProblem, type InvitationIssue } from "./validate";
|
||||
import type { SendStage } from "./send-command";
|
||||
|
||||
/**
|
||||
* What the form shows after a failed attempt.
|
||||
*
|
||||
* - fields: the server rejected values; the issues are bound to fields.
|
||||
* - retry: the outcome is unknown or temporary; the next click repeats the
|
||||
* same command with the same Idempotency-Key.
|
||||
* - blocked: the server refused the command for a reason the form cannot fix.
|
||||
* - access: the session, the membership, or the role no longer allows it.
|
||||
* - csrf: the CSRF token is stale; the session must be read again.
|
||||
*/
|
||||
export type SendFailure =
|
||||
| {
|
||||
readonly kind: "fields";
|
||||
readonly issues: readonly InvitationIssue[];
|
||||
readonly message: string;
|
||||
}
|
||||
| { readonly kind: "retry"; readonly message: string }
|
||||
| { readonly kind: "blocked"; readonly message: string }
|
||||
| { readonly kind: "access"; readonly message: string }
|
||||
| { readonly kind: "csrf"; readonly message: string };
|
||||
|
||||
const sameKeyHint =
|
||||
"Нажмите «Отправить приглашение» еще раз: повтор использует тот же ключ и не создаст второе приглашение.";
|
||||
|
||||
function isAmbiguous(error: ApiRequestError): boolean {
|
||||
return error.status === 0 || error.status >= 500 || error.code === invalidResponseCode;
|
||||
}
|
||||
|
||||
/** Describes a failed send command without any value the employer did not type. */
|
||||
export function describeSendFailure(stage: SendStage, error: unknown): SendFailure {
|
||||
if (!(error instanceof ApiRequestError)) {
|
||||
return { kind: "retry", message: `Не удалось завершить отправку. ${sameKeyHint}` };
|
||||
}
|
||||
if (isAmbiguous(error)) {
|
||||
return {
|
||||
kind: "retry",
|
||||
message: `Сервер не подтвердил результат. ${sameKeyHint}`,
|
||||
};
|
||||
}
|
||||
if (error.status === 403 && error.code === "csrf_check_failed") {
|
||||
return {
|
||||
kind: "csrf",
|
||||
message: "Проверка входа устарела. Мы обновили ее; отправьте приглашение еще раз.",
|
||||
};
|
||||
}
|
||||
if (error.status === 401 || error.status === 403 || error.status === 404) {
|
||||
return {
|
||||
kind: "access",
|
||||
message:
|
||||
error.status === 401
|
||||
? "Сессия завершилась. Войдите снова; заполненные условия останутся на странице до перезагрузки."
|
||||
: "Нет доступа к приглашениям этой компании. Приглашать кандидатов может только владелец.",
|
||||
};
|
||||
}
|
||||
if (error.status === 400) {
|
||||
if (error.fieldErrors.some((field) => field.pointer === "/candidate_handle")) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
"Кандидат больше недоступен компании. Вернитесь к поиску и выберите кандидата заново.",
|
||||
};
|
||||
}
|
||||
if (error.fieldErrors.some((field) => field.pointer.startsWith("/need"))) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
"Потребность не найдена или ее версия устарела. Откройте приглашение из поиска заново.",
|
||||
};
|
||||
}
|
||||
const issues = issuesOfProblem(error.fieldErrors);
|
||||
return {
|
||||
kind: "fields",
|
||||
issues,
|
||||
message:
|
||||
issues.length > 0
|
||||
? "Сервер не принял условия. Исправьте отмеченные поля."
|
||||
: "Сервер не принял запрос. Проверьте условия и повторите.",
|
||||
};
|
||||
}
|
||||
if (error.status === 409 && error.code === "idempotency_in_progress") {
|
||||
return {
|
||||
kind: "retry",
|
||||
message: `Предыдущая попытка еще обрабатывается. Подождите несколько секунд. ${sameKeyHint}`,
|
||||
};
|
||||
}
|
||||
if (error.status === 409) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
stage === "send"
|
||||
? "Сейчас этому кандидату нельзя отправить приглашение: профиль стал недоступен компании или действует ограничение. Приглашение не отправлено."
|
||||
: "Черновик уже нельзя изменить. Обновите страницу, чтобы увидеть его состояние.",
|
||||
};
|
||||
}
|
||||
if (error.status === 412) {
|
||||
return {
|
||||
kind: "retry",
|
||||
message:
|
||||
"Черновик изменился в другом окне. Мы загрузили его текущую версию; ваши условия применятся при следующей отправке.",
|
||||
};
|
||||
}
|
||||
if (error.status === 429) {
|
||||
const wait = formatRetryAfter(error.retryAfterSeconds);
|
||||
return {
|
||||
kind: "retry",
|
||||
message:
|
||||
stage === "send"
|
||||
? `Исчерпан лимит приглашений компании на неделю. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`
|
||||
: `Слишком много изменений зарплатных вилок. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "blocked",
|
||||
message: "Сервер отклонил запрос. Обновите страницу и проверьте состояние приглашения.",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import type {
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
OrganizationInvitationCreate,
|
||||
OrganizationInvitationUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { toInvitationTerms } from "./draft";
|
||||
import { completeDraft } from "./draft.fixtures";
|
||||
import { describeSendFailure } from "./failure";
|
||||
import {
|
||||
initialSendProgress,
|
||||
runSendCommand,
|
||||
type SendOutcome,
|
||||
type SendRequest,
|
||||
} from "./send-command";
|
||||
|
||||
const organizationId = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01";
|
||||
const invitationId = "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f";
|
||||
const candidateHandle = `cv1_${"A".repeat(43)}`;
|
||||
const base = `http://localhost/api/v1/organizations/${organizationId}/invitations`;
|
||||
const deadline = "2026-10-16T10:00:00Z";
|
||||
|
||||
const server = setupServer();
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
function stubRelativeFetch(): void {
|
||||
const realFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
realFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
}
|
||||
|
||||
function invitation(
|
||||
terms: InvitationTerms,
|
||||
overrides: Partial<OrganizationInvitation> = {},
|
||||
): OrganizationInvitation {
|
||||
return {
|
||||
id: invitationId,
|
||||
organization_id: organizationId,
|
||||
candidate_handle: candidateHandle,
|
||||
need: null,
|
||||
state: "draft",
|
||||
expiry_reason: null,
|
||||
version: 1,
|
||||
terms_version: 1,
|
||||
terms,
|
||||
response_period_days: 7,
|
||||
response_deadline_at: null,
|
||||
salary_raise_used: false,
|
||||
salary_fit: "not_available",
|
||||
contact_access: { status: "not_granted", fields: [] },
|
||||
created_at: "2026-10-09T10:00:00Z",
|
||||
updated_at: "2026-10-09T10:00:00Z",
|
||||
delivered_at: null,
|
||||
viewed_at: null,
|
||||
responded_at: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type Recorded = {
|
||||
method: string;
|
||||
path: string;
|
||||
key: string | null;
|
||||
csrf: string | null;
|
||||
body: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* A small fake of the invitation endpoints with the replay rules of the
|
||||
* contract: a known key replays the stored answer, and `lose` drops the
|
||||
* response of the next matching request after the server applied it.
|
||||
*/
|
||||
function fakeBackend(options: { lose?: "create" | "send"; sendStatus?: number } = {}) {
|
||||
const requests: Recorded[] = [];
|
||||
let stored: OrganizationInvitation | null = null;
|
||||
let deliveries = 0;
|
||||
let lose = options.lose;
|
||||
const createReplies = new Map<string, OrganizationInvitation>();
|
||||
const sendReplies = new Map<string, OrganizationInvitation>();
|
||||
|
||||
async function record(request: Request): Promise<Recorded> {
|
||||
const entry: Recorded = {
|
||||
method: request.method,
|
||||
path: new URL(request.url).pathname,
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
csrf: request.headers.get("X-CSRF-Token"),
|
||||
body: request.method === "GET" ? null : await request.json(),
|
||||
};
|
||||
requests.push(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
server.use(
|
||||
http.post(base, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
const key = entry.key ?? "";
|
||||
let reply = createReplies.get(key);
|
||||
if (!reply) {
|
||||
const body = entry.body as OrganizationInvitationCreate;
|
||||
reply = invitation(body.terms, { response_period_days: body.response_period_days ?? 7 });
|
||||
stored = reply;
|
||||
createReplies.set(key, reply);
|
||||
}
|
||||
if (lose === "create") {
|
||||
lose = undefined;
|
||||
return HttpResponse.error();
|
||||
}
|
||||
return HttpResponse.json(reply, { status: 201 });
|
||||
}),
|
||||
http.patch(`${base}/${invitationId}`, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
const body = entry.body as OrganizationInvitationUpdate;
|
||||
if (!stored || body.expected_version !== stored.version) {
|
||||
return HttpResponse.json(
|
||||
{ type: "about:blank", title: "Version conflict", status: 412, code: "version_conflict" },
|
||||
{ status: 412, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}
|
||||
stored = invitation(body.terms ?? stored.terms, {
|
||||
version: stored.version + 1,
|
||||
terms_version: stored.terms_version + 1,
|
||||
});
|
||||
return HttpResponse.json(stored);
|
||||
}),
|
||||
http.get(`${base}/${invitationId}`, async ({ request }) => {
|
||||
await record(request);
|
||||
return HttpResponse.json(stored);
|
||||
}),
|
||||
http.post(`${base}/${invitationId}/send`, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
if (options.sendStatus) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: "about:blank",
|
||||
title: "Rejected",
|
||||
status: options.sendStatus,
|
||||
code: "version_conflict",
|
||||
},
|
||||
{ status: options.sendStatus, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}
|
||||
const key = entry.key ?? "";
|
||||
let reply = sendReplies.get(key);
|
||||
if (!reply && stored) {
|
||||
deliveries += 1;
|
||||
stored = {
|
||||
...stored,
|
||||
state: "delivered",
|
||||
version: stored.version + 1,
|
||||
delivered_at: "2026-10-09T10:00:00Z",
|
||||
response_deadline_at: deadline,
|
||||
};
|
||||
reply = stored;
|
||||
sendReplies.set(key, reply);
|
||||
}
|
||||
if (lose === "send") {
|
||||
lose = undefined;
|
||||
return HttpResponse.error();
|
||||
}
|
||||
return HttpResponse.json(reply);
|
||||
}),
|
||||
);
|
||||
return { requests, deliveries: () => deliveries };
|
||||
}
|
||||
|
||||
const terms = toInvitationTerms(completeDraft());
|
||||
|
||||
function request(overrides: Partial<SendRequest> = {}): SendRequest {
|
||||
return {
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need: null,
|
||||
terms,
|
||||
responsePeriodDays: 7,
|
||||
csrfToken: "csrf-token",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function keys(): () => string {
|
||||
let next = 0;
|
||||
return () => `key-${++next}`;
|
||||
}
|
||||
|
||||
describe("send invitation command", () => {
|
||||
it("creates the draft and sends it with separate keys and the CSRF token", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend();
|
||||
const onDraft = vi.fn();
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, {
|
||||
newKey: keys(),
|
||||
onDraft,
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe("sent");
|
||||
if (outcome.kind !== "sent") return;
|
||||
expect(outcome.invitation.state).toBe("delivered");
|
||||
expect(outcome.invitation.response_deadline_at).toBe(deadline);
|
||||
expect(outcome.progress).toMatchObject({ createKey: null, sendKey: null });
|
||||
expect(onDraft).toHaveBeenCalledOnce();
|
||||
expect(backend.requests.map((item) => [item.method, item.key, item.csrf])).toEqual([
|
||||
["POST", "key-1", "csrf-token"],
|
||||
["POST", "key-2", "csrf-token"],
|
||||
]);
|
||||
expect(backend.requests[0]?.body).toEqual({
|
||||
candidate_handle: candidateHandle,
|
||||
need: null,
|
||||
response_period_days: 7,
|
||||
terms,
|
||||
});
|
||||
expect(backend.requests[1]?.body).toEqual({ expected_version: 1 });
|
||||
});
|
||||
|
||||
it("repeats a send whose response was lost with the same key and delivers once", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ lose: "send" });
|
||||
const newKey = keys();
|
||||
|
||||
const first = await runSendCommand(request(), initialSendProgress, { newKey });
|
||||
expect(first).toMatchObject({ kind: "failed", stage: "send" });
|
||||
if (first.kind !== "failed") return;
|
||||
expect(describeSendFailure(first.stage, first.error).kind).toBe("retry");
|
||||
|
||||
const second = await runSendCommand(request(), first.progress, { newKey });
|
||||
|
||||
expect(second.kind).toBe("sent");
|
||||
const sends = backend.requests.filter((item) => item.path.endsWith("/send"));
|
||||
expect(sends.map((item) => item.key)).toEqual(["key-2", "key-2"]);
|
||||
expect(backend.requests.filter((item) => item.path.endsWith("/invitations"))).toHaveLength(1);
|
||||
expect(backend.deliveries()).toBe(1);
|
||||
});
|
||||
|
||||
it("repeats a create whose response was lost with the same key", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ lose: "create" });
|
||||
const newKey = keys();
|
||||
|
||||
const first = await runSendCommand(request(), initialSendProgress, { newKey });
|
||||
expect(first).toMatchObject({ kind: "failed", stage: "create" });
|
||||
const second = await runSendCommand(
|
||||
request(),
|
||||
(first as Extract<SendOutcome, { kind: "failed" }>).progress,
|
||||
{ newKey },
|
||||
);
|
||||
|
||||
expect(second.kind).toBe("sent");
|
||||
const creates = backend.requests.filter((item) => item.path.endsWith("/invitations"));
|
||||
expect(creates.map((item) => item.key)).toEqual(["key-1", "key-1"]);
|
||||
});
|
||||
|
||||
it("binds server field errors of a rejected draft to the form and sends nothing", async () => {
|
||||
stubRelativeFetch();
|
||||
const sent: string[] = [];
|
||||
server.use(
|
||||
http.post(base, () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
type: "about:blank",
|
||||
title: "Validation failed",
|
||||
status: 400,
|
||||
code: "validation_failed",
|
||||
errors: [
|
||||
{
|
||||
in: "body",
|
||||
pointer: "/terms/communication_method",
|
||||
code: "required",
|
||||
message: "x",
|
||||
},
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "x" },
|
||||
],
|
||||
},
|
||||
{ status: 400, headers: { "Content-Type": "application/problem+json" } },
|
||||
),
|
||||
),
|
||||
http.post(`${base}/${invitationId}/send`, () => {
|
||||
sent.push("send");
|
||||
return HttpResponse.json({}, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "failed", stage: "create" });
|
||||
if (outcome.kind !== "failed") return;
|
||||
const failure = describeSendFailure(outcome.stage, outcome.error);
|
||||
expect(failure.kind).toBe("fields");
|
||||
expect(failure.kind === "fields" ? failure.issues.map((issue) => issue.field) : []).toEqual([
|
||||
"channel",
|
||||
"salaryTo",
|
||||
]);
|
||||
expect(outcome.progress.draft).toBeNull();
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it("updates a saved draft whose terms changed before sending it under a new key", async () => {
|
||||
stubRelativeFetch();
|
||||
const recorded: { method: string; body: unknown }[] = [];
|
||||
const newKey = keys();
|
||||
// A draft that was saved but not sent, for example reopened from the address.
|
||||
const saved = invitation(terms);
|
||||
const changed = { ...terms, role_title: "Senior Go-разработчик" };
|
||||
server.use(
|
||||
http.patch(`${base}/${invitationId}`, async ({ request: patch }) => {
|
||||
const body = (await patch.json()) as OrganizationInvitationUpdate;
|
||||
recorded.push({ method: "PATCH", body });
|
||||
return HttpResponse.json(invitation(changed, { version: 2, terms_version: 2 }));
|
||||
}),
|
||||
http.post(`${base}/${invitationId}/send`, async ({ request: send }) => {
|
||||
recorded.push({
|
||||
method: `POST ${send.headers.get("Idempotency-Key")}`,
|
||||
body: await send.json(),
|
||||
});
|
||||
return HttpResponse.json(
|
||||
invitation(changed, {
|
||||
state: "delivered",
|
||||
version: 3,
|
||||
terms_version: 2,
|
||||
delivered_at: "2026-10-09T10:00:00Z",
|
||||
response_deadline_at: deadline,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = await runSendCommand(
|
||||
request({ terms: changed }),
|
||||
{ ...initialSendProgress, draft: saved },
|
||||
{ newKey },
|
||||
);
|
||||
|
||||
expect(outcome.kind).toBe("sent");
|
||||
expect(recorded.map((item) => [item.method, item.body])).toEqual([
|
||||
["PATCH", { expected_version: 1, need: null, response_period_days: 7, terms: changed }],
|
||||
["POST key-1", { expected_version: 2 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("reloads the draft after a version conflict and keeps the form's terms for the retry", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ sendStatus: 412 });
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "failed", stage: "send" });
|
||||
if (outcome.kind !== "failed") return;
|
||||
expect(backend.requests.map((item) => item.method)).toEqual(["POST", "POST", "GET"]);
|
||||
expect(outcome.progress.draft?.id).toBe(invitationId);
|
||||
expect(describeSendFailure("send", outcome.error).message).toContain("другом окне");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type {
|
||||
InvitationNeedReference,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
OrganizationInvitationCreate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
createInvitationDraft,
|
||||
readOrganizationInvitation,
|
||||
sendInvitationDraft,
|
||||
updateInvitationDraft,
|
||||
} from "../../../entities/invitation";
|
||||
|
||||
// Sending an invitation is three contract operations: create the draft
|
||||
// (Idempotency-Key), bring its terms up to date when the form changed after
|
||||
// the draft was created (expected_version), and send it (Idempotency-Key).
|
||||
// The progress object is the client side of that command: it remembers the
|
||||
// draft and the key of each keyed step, so a repeated click, a retry after a
|
||||
// lost response, or a retry after a server error replays the same key and
|
||||
// never creates a second draft or a second delivery. A key is bound to what
|
||||
// it protects (the create body, or the draft id and version) and changes only
|
||||
// when that changes, which is when the server would answer 422 for the old key.
|
||||
|
||||
/** An Idempotency-Key and the request it was issued for. */
|
||||
export interface KeyBinding {
|
||||
readonly fingerprint: string;
|
||||
readonly key: string;
|
||||
}
|
||||
|
||||
export interface SendProgress {
|
||||
readonly createKey: KeyBinding | null;
|
||||
/** The draft as the server last returned it, or null before it exists. */
|
||||
readonly draft: OrganizationInvitation | null;
|
||||
readonly sendKey: KeyBinding | null;
|
||||
}
|
||||
|
||||
export const initialSendProgress: SendProgress = { createKey: null, draft: null, sendKey: null };
|
||||
|
||||
export interface SendRequest {
|
||||
readonly organizationId: string;
|
||||
readonly candidateHandle: string;
|
||||
readonly need: InvitationNeedReference | null;
|
||||
readonly terms: InvitationTerms;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
readonly csrfToken: string;
|
||||
}
|
||||
|
||||
export type SendStage = "create" | "update" | "send";
|
||||
|
||||
export type SendOutcome =
|
||||
| {
|
||||
readonly kind: "sent";
|
||||
/** The invitation after the send; its state is no longer `draft`. */
|
||||
readonly invitation: OrganizationInvitation;
|
||||
readonly progress: SendProgress;
|
||||
}
|
||||
| {
|
||||
readonly kind: "failed";
|
||||
readonly stage: SendStage;
|
||||
readonly error: unknown;
|
||||
readonly progress: SendProgress;
|
||||
};
|
||||
|
||||
export interface SendDependencies {
|
||||
readonly newKey: () => string;
|
||||
/** Called once the draft exists on the server, before it is sent. */
|
||||
readonly onDraft?: ((draft: OrganizationInvitation) => void) | undefined;
|
||||
}
|
||||
|
||||
export function newIdempotencyKey(): string {
|
||||
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
|
||||
throw new Error("Secure random key generation is unavailable.");
|
||||
}
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
/** JSON with object keys in a fixed order, so equal values give equal text. */
|
||||
export function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
||||
if (value !== null && typeof value === "object") {
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, item]) => item !== undefined)
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
|
||||
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function bind(previous: KeyBinding | null, fingerprint: string, newKey: () => string): KeyBinding {
|
||||
return previous?.fingerprint === fingerprint ? previous : { fingerprint, key: newKey() };
|
||||
}
|
||||
|
||||
function draftMatches(draft: OrganizationInvitation, request: SendRequest): boolean {
|
||||
return (
|
||||
stableJson(draft.terms) === stableJson(request.terms) &&
|
||||
draft.response_period_days === request.responsePeriodDays &&
|
||||
stableJson(draft.need) === stableJson(request.need)
|
||||
);
|
||||
}
|
||||
|
||||
function versionConflict(error: unknown): boolean {
|
||||
return error instanceof ApiRequestError && error.status === 412;
|
||||
}
|
||||
|
||||
/** Reads the current draft after a version conflict; keeps the old one when the read fails. */
|
||||
async function reloadDraft(
|
||||
request: SendRequest,
|
||||
progress: SendProgress,
|
||||
draft: OrganizationInvitation,
|
||||
): Promise<SendProgress> {
|
||||
try {
|
||||
const latest = await readOrganizationInvitation(request.organizationId, draft.id);
|
||||
return { ...progress, draft: latest };
|
||||
} catch {
|
||||
return progress;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the send command from the given progress. It never throws for a
|
||||
* request failure: the outcome carries the stage, the error, and the progress
|
||||
* to pass to the next attempt.
|
||||
*/
|
||||
export async function runSendCommand(
|
||||
request: SendRequest,
|
||||
initial: SendProgress,
|
||||
dependencies: SendDependencies,
|
||||
): Promise<SendOutcome> {
|
||||
let progress = initial;
|
||||
|
||||
if (progress.draft === null) {
|
||||
const body: OrganizationInvitationCreate = {
|
||||
candidate_handle: request.candidateHandle,
|
||||
need: request.need,
|
||||
response_period_days: request.responsePeriodDays,
|
||||
terms: request.terms,
|
||||
};
|
||||
const createKey = bind(progress.createKey, stableJson(body), dependencies.newKey);
|
||||
progress = { ...progress, createKey };
|
||||
try {
|
||||
const draft = await createInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
body,
|
||||
idempotencyKey: createKey.key,
|
||||
});
|
||||
progress = { ...progress, draft };
|
||||
dependencies.onDraft?.(draft);
|
||||
} catch (error: unknown) {
|
||||
return { kind: "failed", stage: "create", error, progress };
|
||||
}
|
||||
}
|
||||
|
||||
let draft = progress.draft;
|
||||
if (draft === null) throw new Error("The draft must exist after its creation.");
|
||||
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
|
||||
|
||||
if (!draftMatches(draft, request)) {
|
||||
try {
|
||||
draft = await updateInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
invitationId: draft.id,
|
||||
body: {
|
||||
expected_version: draft.version,
|
||||
need: request.need,
|
||||
response_period_days: request.responsePeriodDays,
|
||||
terms: request.terms,
|
||||
},
|
||||
});
|
||||
progress = { ...progress, draft };
|
||||
} catch (error: unknown) {
|
||||
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
|
||||
return { kind: "failed", stage: "update", error, progress };
|
||||
}
|
||||
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
|
||||
}
|
||||
|
||||
const sendKey = bind(progress.sendKey, `${draft.id}:${draft.version}`, dependencies.newKey);
|
||||
progress = { ...progress, sendKey };
|
||||
try {
|
||||
const sent = await sendInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
invitationId: draft.id,
|
||||
expectedVersion: draft.version,
|
||||
idempotencyKey: sendKey.key,
|
||||
});
|
||||
// The command is complete: the next command starts with fresh keys.
|
||||
return {
|
||||
kind: "sent",
|
||||
invitation: sent,
|
||||
progress: { createKey: null, draft: sent, sendKey: null },
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
|
||||
return { kind: "failed", stage: "send", error, progress };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { InvitationTerms as InvitationTermsSchema } from "../../../shared/api/schemas";
|
||||
import {
|
||||
emptyInvitationDraft,
|
||||
invitationDraftFromTerms,
|
||||
toInvitationTerms,
|
||||
type InvitationDraft,
|
||||
} from "./draft";
|
||||
import { completeDraft } from "./draft.fixtures";
|
||||
import { fieldOfPointer, issuesOfProblem, validateInvitationDraft } from "./validate";
|
||||
|
||||
const fieldsOf = (draft: InvitationDraft) => validateInvitationDraft(draft).map((i) => i.field);
|
||||
|
||||
describe("invitation draft validation", () => {
|
||||
it("accepts a complete draft and builds terms the contract accepts", () => {
|
||||
const draft = completeDraft();
|
||||
|
||||
expect(validateInvitationDraft(draft)).toEqual([]);
|
||||
const terms = toInvitationTerms(draft);
|
||||
expect(InvitationTermsSchema.safeParse(terms).success).toBe(true);
|
||||
expect(terms.tasks).toEqual(["Развивать сервис выплат", "Перевести отчеты на события"]);
|
||||
expect(terms.tech_stack).toEqual(["Go", "PostgreSQL", "Kafka"]);
|
||||
expect(terms.salary).toEqual({
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
});
|
||||
expect(terms.package.training).toEqual({ status: "not_provided" });
|
||||
expect(terms.communication_method).toEqual({
|
||||
channel: "video_call",
|
||||
details: "Созвон с тимлидом в течение трех рабочих дней",
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks a blank draft on every required term in the order of the form", () => {
|
||||
expect(fieldsOf(emptyInvitationDraft())).toEqual([
|
||||
"roleTitle",
|
||||
"specialization",
|
||||
"grade",
|
||||
"offerType",
|
||||
"tasks",
|
||||
"team",
|
||||
"techStack",
|
||||
"workFormats",
|
||||
"channel",
|
||||
"salaryFrom",
|
||||
"salaryTo",
|
||||
"taxBasis",
|
||||
"package.bonus",
|
||||
"package.equipment",
|
||||
"package.training",
|
||||
"package.health_insurance",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ salaryTo: "" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "" }, ["salaryFrom"]],
|
||||
[{ taxBasis: "" as const }, ["taxBasis"]],
|
||||
[{ salaryFrom: "100500" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "140000", salaryTo: "100000" }, ["salaryTo"]],
|
||||
[{ salaryTo: "105000" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "79000", salaryTo: "121000" }, ["salaryTo"]],
|
||||
])("does not allow sending an incomplete or invalid salary range %j", (overrides, fields) => {
|
||||
expect(fieldsOf(completeDraft(overrides))).toEqual(fields);
|
||||
});
|
||||
|
||||
it("requires the communication method, a place for office formats, and each package choice", () => {
|
||||
expect(fieldsOf(completeDraft({ channel: "" }))).toEqual(["channel"]);
|
||||
expect(fieldsOf(completeDraft({ location: "" }))).toEqual(["location"]);
|
||||
expect(fieldsOf(completeDraft({ location: "", workFormats: ["remote"] }))).toEqual([]);
|
||||
const draft = completeDraft();
|
||||
expect(
|
||||
fieldsOf({
|
||||
...draft,
|
||||
packageItems: {
|
||||
...draft.packageItems,
|
||||
training: { status: "", description: "" },
|
||||
bonus: { status: "provided", description: " " },
|
||||
},
|
||||
}),
|
||||
).toEqual(["package.bonus", "package.training"]);
|
||||
});
|
||||
|
||||
it("finds a technology repeated in another letter case", () => {
|
||||
const issues = validateInvitationDraft(completeDraft({ techStack: "Go, PostgreSQL, GO" }));
|
||||
expect(issues).toEqual([{ field: "techStack", message: "Технология «GO» указана дважды." }]);
|
||||
});
|
||||
|
||||
it("restores the same terms from a stored invitation", () => {
|
||||
const terms = toInvitationTerms(completeDraft());
|
||||
expect(toInvitationTerms(invitationDraftFromTerms(terms, 14))).toEqual(terms);
|
||||
expect(invitationDraftFromTerms(terms, 14).responsePeriodDays).toBe(14);
|
||||
});
|
||||
});
|
||||
|
||||
describe("server field errors", () => {
|
||||
it.each([
|
||||
["/terms/salary/salary_to", "salaryTo"],
|
||||
["/terms/salary/tax_basis", "taxBasis"],
|
||||
["/terms/communication_method", "channel"],
|
||||
["/terms/communication_method/channel", "channel"],
|
||||
["/terms/communication_method/details", "channelDetails"],
|
||||
["/terms/tech_stack/1", "techStack"],
|
||||
["/terms/tasks/0", "tasks"],
|
||||
["/terms/location", "location"],
|
||||
["/terms/package/training", "package.training"],
|
||||
["/terms/package/bonus/description", "package.bonus"],
|
||||
["/response_period_days", "responsePeriodDays"],
|
||||
["/candidate_handle", null],
|
||||
["/expected_version", null],
|
||||
["", null],
|
||||
])("maps the pointer %s to %s", (pointer, field) => {
|
||||
expect(fieldOfPointer(pointer)).toBe(field);
|
||||
});
|
||||
|
||||
it("binds each body error to its field once, in the order of the form", () => {
|
||||
const issues = issuesOfProblem([
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Width." },
|
||||
{ in: "body", pointer: "/terms/communication_method", code: "required", message: "Missing." },
|
||||
{ in: "body", pointer: "/terms/package/training", code: "required", message: "Missing." },
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Again." },
|
||||
{ in: "header", pointer: "/Idempotency-Key", code: "invalid", message: "Key." },
|
||||
]);
|
||||
|
||||
expect(issues.map((issue) => issue.field)).toEqual(["channel", "salaryTo", "package.training"]);
|
||||
expect(issues[2]?.message).toContain("незаполненным");
|
||||
expect(JSON.stringify(issues)).not.toMatch(/Width|Missing|Again/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import type { ProblemFieldError } from "../../../shared/api/schemas";
|
||||
import { OrganizationInvitationCreate } from "../../../shared/api/schemas";
|
||||
import {
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
salaryRangeIssue,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import { taskLines, techStackItems, toInvitationTerms, type InvitationDraft } from "./draft";
|
||||
|
||||
// Client validation mirrors the contract for immediate feedback: the per-field
|
||||
// limits and the cross-field rules of the terms (salary range, place of work,
|
||||
// repeated technology). The server stays the source of truth; its RFC 9457
|
||||
// field errors come back through fieldOfPointer and land on the same fields.
|
||||
|
||||
export type InvitationField =
|
||||
| "roleTitle"
|
||||
| "specialization"
|
||||
| "grade"
|
||||
| "offerType"
|
||||
| "tasks"
|
||||
| "team"
|
||||
| "techStack"
|
||||
| "workFormats"
|
||||
| "location"
|
||||
| "channel"
|
||||
| "channelDetails"
|
||||
| "salaryFrom"
|
||||
| "salaryTo"
|
||||
| "taxBasis"
|
||||
| `package.${InvitationPackageKey}`
|
||||
| "responsePeriodDays";
|
||||
|
||||
/** Field order of the form, used to order the issue summary and to pick the first field. */
|
||||
export const invitationFieldOrder: readonly InvitationField[] = [
|
||||
"roleTitle",
|
||||
"specialization",
|
||||
"grade",
|
||||
"offerType",
|
||||
"tasks",
|
||||
"team",
|
||||
"techStack",
|
||||
"workFormats",
|
||||
"location",
|
||||
"channel",
|
||||
"channelDetails",
|
||||
"salaryFrom",
|
||||
"salaryTo",
|
||||
"taxBasis",
|
||||
...packageItemKeys.map((key) => `package.${key}` as const),
|
||||
"responsePeriodDays",
|
||||
];
|
||||
|
||||
export interface InvitationIssue {
|
||||
readonly field: InvitationField;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
const singleLine = /^\S(?:.*\S)?$/;
|
||||
|
||||
const salaryIssueMessages = {
|
||||
bound: "Суммы должны быть целыми, положительными и кратными 1 000 рублей.",
|
||||
order: "Верхняя граница вилки должна быть больше нижней.",
|
||||
narrow: "Вилка слишком узкая: ширина должна быть не меньше 10% от середины.",
|
||||
wide: "Вилка слишком широкая: ширина должна быть не больше 40% от середины.",
|
||||
} as const;
|
||||
|
||||
function lineIssue(value: string, max: number, empty: string, field: InvitationField) {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === "") return { field, message: empty };
|
||||
if (trimmed.length > max) return { field, message: `Не больше ${max} символов.` };
|
||||
if (!singleLine.test(trimmed)) return { field, message: "Текст должен быть в одну строку." };
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkSalary(draft: InvitationDraft): InvitationIssue[] {
|
||||
const issues: InvitationIssue[] = [];
|
||||
const from = draft.salaryFrom.trim();
|
||||
const to = draft.salaryTo.trim();
|
||||
if (from === "") issues.push({ field: "salaryFrom", message: "Укажите нижнюю границу вилки." });
|
||||
if (to === "") issues.push({ field: "salaryTo", message: "Укажите верхнюю границу вилки." });
|
||||
if (!draft.taxBasis) {
|
||||
issues.push({ field: "taxBasis", message: "Выберите базу суммы: до или после налога." });
|
||||
}
|
||||
if (from === "" || to === "") return issues;
|
||||
const issue = salaryRangeIssue(Number(from), Number(to));
|
||||
if (issue) issues.push({ field: "salaryTo", message: salaryIssueMessages[issue] });
|
||||
return issues;
|
||||
}
|
||||
|
||||
function checkTechStack(value: string): InvitationIssue | null {
|
||||
const items = techStackItems(value);
|
||||
if (items.length === 0) {
|
||||
return { field: "techStack", message: "Укажите хотя бы одну технологию." };
|
||||
}
|
||||
if (items.length > 30) return { field: "techStack", message: "Не больше 30 технологий." };
|
||||
if (items.some((item) => item.length > 100)) {
|
||||
return { field: "techStack", message: "Название технологии не длиннее 100 символов." };
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
for (const item of items) {
|
||||
const folded = item.toLocaleLowerCase("ru-RU");
|
||||
if (seen.has(folded)) {
|
||||
return { field: "techStack", message: `Технология «${item}» указана дважды.` };
|
||||
}
|
||||
seen.add(folded);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkTasks(value: string): InvitationIssue | null {
|
||||
const lines = taskLines(value);
|
||||
if (lines.length === 0) return { field: "tasks", message: "Опишите хотя бы одну задачу." };
|
||||
if (lines.length > 20) return { field: "tasks", message: "Не больше 20 задач." };
|
||||
if (lines.some((line) => line.length > 300)) {
|
||||
return { field: "tasks", message: "Каждая задача не длиннее 300 символов." };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every issue of a draft in the order of the form; an empty list means it can be sent. */
|
||||
export function validateInvitationDraft(draft: InvitationDraft): InvitationIssue[] {
|
||||
const issues: (InvitationIssue | null)[] = [
|
||||
lineIssue(draft.roleTitle, 200, "Укажите название роли.", "roleTitle"),
|
||||
draft.specialization ? null : { field: "specialization", message: "Выберите специализацию." },
|
||||
draft.grade ? null : { field: "grade", message: "Выберите грейд." },
|
||||
draft.offerType ? null : { field: "offerType", message: "Выберите тип предложения." },
|
||||
checkTasks(draft.tasks),
|
||||
draft.team.trim() === ""
|
||||
? { field: "team", message: "Опишите команду." }
|
||||
: draft.team.trim().length > 1000
|
||||
? { field: "team", message: "Не больше 1000 символов." }
|
||||
: null,
|
||||
checkTechStack(draft.techStack),
|
||||
draft.workFormats.length === 0
|
||||
? { field: "workFormats", message: "Выберите хотя бы один формат работы." }
|
||||
: null,
|
||||
];
|
||||
|
||||
const officeFormat = draft.workFormats.includes("office") || draft.workFormats.includes("hybrid");
|
||||
if (draft.location.trim() !== "" || officeFormat) {
|
||||
issues.push(
|
||||
lineIssue(draft.location, 100, "Для офиса или гибрида укажите место работы.", "location"),
|
||||
);
|
||||
}
|
||||
issues.push(
|
||||
draft.channel
|
||||
? null
|
||||
: { field: "channel", message: "Выберите способ связи после принятия приглашения." },
|
||||
);
|
||||
if (draft.channelDetails.trim() !== "") {
|
||||
issues.push(lineIssue(draft.channelDetails, 300, "", "channelDetails"));
|
||||
}
|
||||
issues.push(...checkSalary(draft));
|
||||
for (const key of packageItemKeys) {
|
||||
const item = draft.packageItems[key];
|
||||
const field = `package.${key}` as const;
|
||||
if (!item.status) {
|
||||
issues.push({
|
||||
field,
|
||||
message: `${packageItemLabels[key]}: выберите «Предусмотрено» или «Не предусмотрено».`,
|
||||
});
|
||||
} else if (item.status === "provided") {
|
||||
const issue = lineIssue(
|
||||
item.description,
|
||||
300,
|
||||
`${packageItemLabels[key]}: опишите условие.`,
|
||||
field,
|
||||
);
|
||||
issues.push(issue);
|
||||
}
|
||||
}
|
||||
|
||||
const found = issues.filter((issue): issue is InvitationIssue => issue !== null);
|
||||
if (found.length > 0) return found;
|
||||
|
||||
// Safety net: the generated request schema must accept the built terms.
|
||||
const parsed = OrganizationInvitationCreate.safeParse({
|
||||
candidate_handle: `cv1_${"A".repeat(43)}`,
|
||||
terms: toInvitationTerms(draft),
|
||||
});
|
||||
if (parsed.success) return [];
|
||||
return parsed.error.issues.map((issue) => ({
|
||||
field: fieldOfPath(issue.path) ?? "roleTitle",
|
||||
message: "Проверьте это значение.",
|
||||
}));
|
||||
}
|
||||
|
||||
const termsFields: Readonly<Record<string, InvitationField>> = {
|
||||
role_title: "roleTitle",
|
||||
specialization: "specialization",
|
||||
grade: "grade",
|
||||
offer_type: "offerType",
|
||||
tasks: "tasks",
|
||||
team: "team",
|
||||
tech_stack: "techStack",
|
||||
work_formats: "workFormats",
|
||||
location: "location",
|
||||
};
|
||||
|
||||
function fieldOfTermsPath(path: readonly string[]): InvitationField | null {
|
||||
const [head, next] = path;
|
||||
if (head === undefined) return null;
|
||||
const direct = termsFields[head];
|
||||
if (direct) return direct;
|
||||
if (head === "communication_method") {
|
||||
return next === "details" ? "channelDetails" : "channel";
|
||||
}
|
||||
if (head === "salary") {
|
||||
if (next === "salary_from") return "salaryFrom";
|
||||
if (next === "tax_basis") return "taxBasis";
|
||||
return "salaryTo";
|
||||
}
|
||||
if (head === "package") {
|
||||
const key = packageItemKeys.find((item) => item === next);
|
||||
return key ? `package.${key}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps a request body path, such as ["terms", "salary", "salary_to"], to its form field. */
|
||||
export function fieldOfPath(path: readonly PropertyKey[]): InvitationField | null {
|
||||
const parts = path.map(String);
|
||||
if (parts[0] === "terms") return fieldOfTermsPath(parts.slice(1));
|
||||
if (parts[0] === "response_period_days") return "responsePeriodDays";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps an RFC 6901 pointer of a problem, such as "/terms/tech_stack/1", to its form field. */
|
||||
export function fieldOfPointer(pointer: string): InvitationField | null {
|
||||
if (!pointer.startsWith("/")) return null;
|
||||
const path = pointer
|
||||
.slice(1)
|
||||
.split("/")
|
||||
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
||||
return fieldOfPath(path);
|
||||
}
|
||||
|
||||
const serverMessages: Partial<Record<InvitationField, string>> = {
|
||||
salaryTo:
|
||||
"Сервер не принял вилку: границы кратны 1 000 рублей, нижняя меньше верхней, ширина от 10% до 40%.",
|
||||
location: "Сервер требует место работы для офиса или гибрида.",
|
||||
techStack: "Сервер не принял список технологий: проверьте повторы и длину названий.",
|
||||
channel: "Сервер не принял способ связи: выберите канал.",
|
||||
};
|
||||
|
||||
/** Field issues of a server problem; pointers outside the terms are left to the caller. */
|
||||
export function issuesOfProblem(errors: readonly ProblemFieldError[]): InvitationIssue[] {
|
||||
const issues: InvitationIssue[] = [];
|
||||
for (const error of errors) {
|
||||
if (error.in !== "body") continue;
|
||||
const field = fieldOfPointer(error.pointer);
|
||||
if (!field || issues.some((issue) => issue.field === field)) continue;
|
||||
issues.push({
|
||||
field,
|
||||
message:
|
||||
serverMessages[field] ??
|
||||
(error.code === "required"
|
||||
? "Сервер считает это поле незаполненным. Заполните его."
|
||||
: "Сервер не принял это значение. Исправьте его."),
|
||||
});
|
||||
}
|
||||
return issues.sort(
|
||||
(left, right) =>
|
||||
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.intro,
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.issue-summary h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.group > legend {
|
||||
max-width: 100%;
|
||||
padding: 0 var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field > label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field :is(input, select, textarea):focus-visible,
|
||||
.choice input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field [aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.choices {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3) var(--space-5);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.choices > legend {
|
||||
padding: 0 var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.choice {
|
||||
display: inline-flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
min-height: 2.75rem;
|
||||
}
|
||||
|
||||
.field-error,
|
||||
.form-error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.notice,
|
||||
.stale {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.choices > .field,
|
||||
.choices > .field-error {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.issue-summary:focus,
|
||||
.preview:focus,
|
||||
.notice:focus,
|
||||
.form-error:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
|
||||
import type {
|
||||
GradeCode,
|
||||
InvitationCommunicationChannel,
|
||||
InvitationNeedReference,
|
||||
InvitationOfferType,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
SalaryTaxBasis,
|
||||
SpecializationCode,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import {
|
||||
communicationChannelCodes,
|
||||
communicationChannelLabels,
|
||||
notProvidedLabel,
|
||||
offerTypeCodes,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
responsePeriods,
|
||||
taxBasisLabels,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import {
|
||||
gradeCodes,
|
||||
gradeLabels,
|
||||
specializationCodes,
|
||||
specializationLabels,
|
||||
workFormatCodes,
|
||||
workFormatLabels,
|
||||
} from "../../../entities/match";
|
||||
import { toInvitationTerms, type InvitationDraft, type PackageChoice } from "../model/draft";
|
||||
import { describeSendFailure, type SendFailure } from "../model/failure";
|
||||
import {
|
||||
newIdempotencyKey,
|
||||
runSendCommand,
|
||||
stableJson,
|
||||
type SendProgress,
|
||||
} from "../model/send-command";
|
||||
import {
|
||||
invitationFieldOrder,
|
||||
validateInvitationDraft,
|
||||
type InvitationField,
|
||||
type InvitationIssue,
|
||||
} from "../model/validate";
|
||||
import styles from "./invitation-form.module.css";
|
||||
|
||||
/** Terms of a preview, frozen at the moment the employer asked for it. */
|
||||
export interface InvitationPreviewSnapshot {
|
||||
readonly terms: InvitationTerms;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
}
|
||||
|
||||
export type InvitationFormProps = {
|
||||
organizationId: string;
|
||||
candidateHandle: string;
|
||||
need: InvitationNeedReference | null;
|
||||
csrfToken: string;
|
||||
initialDraft: InvitationDraft;
|
||||
/** Progress of an earlier attempt, for example a saved draft reopened from the address. */
|
||||
initialProgress: SendProgress;
|
||||
/** False once the session that rendered the form is no longer the current one. */
|
||||
isSessionCurrent: () => boolean;
|
||||
/** Renders the preview of the given terms; the form never sends anything for it. */
|
||||
renderPreview: (snapshot: InvitationPreviewSnapshot) => ReactNode;
|
||||
onDraftSaved: (draft: OrganizationInvitation) => void;
|
||||
onSent: (invitation: OrganizationInvitation) => void;
|
||||
onCsrfFailed: () => void;
|
||||
};
|
||||
|
||||
type Notice = { tone: "error" | "info"; text: string };
|
||||
type FocusTarget = "summary" | "preview" | "notice";
|
||||
|
||||
function describedBy(...ids: (string | false | undefined)[]): string | undefined {
|
||||
const present = ids.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
return present.length > 0 ? present.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function FieldError({ id, message }: { id: string; message: string | undefined }) {
|
||||
return message ? (
|
||||
<p className={styles["field-error"]} id={id}>
|
||||
{message}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The terms of an invitation for one search entry, with a local preview and
|
||||
* the send command. The form validates like the contract before any request;
|
||||
* the server answer is still authoritative and its field errors are shown on
|
||||
* the same fields. A click that repeats an unfinished command reuses its
|
||||
* Idempotency-Key, and a click while a command runs does nothing.
|
||||
*/
|
||||
export function InvitationForm({
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need,
|
||||
csrfToken,
|
||||
initialDraft,
|
||||
initialProgress,
|
||||
isSessionCurrent,
|
||||
renderPreview,
|
||||
onDraftSaved,
|
||||
onSent,
|
||||
onCsrfFailed,
|
||||
}: InvitationFormProps) {
|
||||
const prefix = `invitation-${useId().replaceAll(":", "")}`;
|
||||
const [draft, setDraft] = useState<InvitationDraft>(initialDraft);
|
||||
const [issues, setIssues] = useState<readonly InvitationIssue[]>([]);
|
||||
const [summaryVisible, setSummaryVisible] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice | null>(null);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [preview, setPreview] = useState<{
|
||||
snapshot: InvitationPreviewSnapshot;
|
||||
source: string;
|
||||
} | null>(null);
|
||||
const progress = useRef<SendProgress>(initialProgress);
|
||||
const inFlight = useRef(false);
|
||||
const mounted = useRef(false);
|
||||
const summaryRef = useRef<HTMLDivElement>(null);
|
||||
const previewRef = useRef<HTMLElement>(null);
|
||||
const noticeRef = useRef<HTMLParagraphElement>(null);
|
||||
// A new object per request, so asking for the same target twice moves focus twice.
|
||||
const [focusRequest, setFocusRequest] = useState<{ target: FocusTarget } | null>(null);
|
||||
const setFocusTarget = (target: FocusTarget) => setFocusRequest({ target });
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Focus moves after the target is rendered: to the issue list, the preview, or the notice.
|
||||
useEffect(() => {
|
||||
if (focusRequest?.target === "summary") summaryRef.current?.focus();
|
||||
if (focusRequest?.target === "preview") previewRef.current?.focus();
|
||||
if (focusRequest?.target === "notice") noticeRef.current?.focus();
|
||||
}, [focusRequest]);
|
||||
|
||||
const fieldId = (field: InvitationField) => `${prefix}-${field.replace(".", "-")}`;
|
||||
const errorId = (field: InvitationField) => `${fieldId(field)}-error`;
|
||||
const issueOf = (field: InvitationField) => issues.find((item) => item.field === field)?.message;
|
||||
const invalid = (field: InvitationField) => Boolean(issueOf(field));
|
||||
const previewStale = preview !== null && preview.source !== stableJson(draft);
|
||||
|
||||
function change(next: Partial<InvitationDraft>, fields: readonly InvitationField[]): void {
|
||||
setDraft((current) => ({ ...current, ...next }));
|
||||
if (fields.length > 0) {
|
||||
setIssues((current) => current.filter((item) => !fields.includes(item.field)));
|
||||
}
|
||||
}
|
||||
|
||||
function changePackage(
|
||||
key: InvitationPackageKey,
|
||||
next: Partial<InvitationDraft["packageItems"][InvitationPackageKey]>,
|
||||
) {
|
||||
change(
|
||||
{ packageItems: { ...draft.packageItems, [key]: { ...draft.packageItems[key], ...next } } },
|
||||
[`package.${key}`],
|
||||
);
|
||||
}
|
||||
|
||||
function toggleFormat(format: WorkFormat, checked: boolean): void {
|
||||
const formats = checked
|
||||
? workFormatCodes.filter((code) => code === format || draft.workFormats.includes(code))
|
||||
: draft.workFormats.filter((code) => code !== format);
|
||||
change({ workFormats: formats }, ["workFormats", "location"]);
|
||||
}
|
||||
|
||||
function showIssues(found: readonly InvitationIssue[]): void {
|
||||
const ordered = [...found].sort(
|
||||
(left, right) =>
|
||||
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
|
||||
);
|
||||
setIssues(ordered);
|
||||
setSummaryVisible(true);
|
||||
setFocusTarget("summary");
|
||||
}
|
||||
|
||||
function validated(): InvitationPreviewSnapshot | null {
|
||||
const found = validateInvitationDraft(draft);
|
||||
if (found.length > 0) {
|
||||
showIssues(found);
|
||||
return null;
|
||||
}
|
||||
setIssues([]);
|
||||
setSummaryVisible(false);
|
||||
return { terms: toInvitationTerms(draft), responsePeriodDays: draft.responsePeriodDays };
|
||||
}
|
||||
|
||||
function showPreview(): void {
|
||||
if (sending) return;
|
||||
setNotice(null);
|
||||
const snapshot = validated();
|
||||
if (!snapshot) return;
|
||||
setPreview({ snapshot, source: stableJson(draft) });
|
||||
setFocusTarget("preview");
|
||||
}
|
||||
|
||||
function applyFailure(failure: SendFailure): void {
|
||||
if (failure.kind === "fields") {
|
||||
setNotice({ tone: "error", text: failure.message });
|
||||
if (failure.issues.length > 0) showIssues(failure.issues);
|
||||
else setFocusTarget("notice");
|
||||
return;
|
||||
}
|
||||
if (failure.kind === "csrf") onCsrfFailed();
|
||||
setNotice({ tone: failure.kind === "retry" ? "info" : "error", text: failure.message });
|
||||
setFocusTarget("notice");
|
||||
}
|
||||
|
||||
async function send(): Promise<void> {
|
||||
// A click while the command runs neither starts a second request nor
|
||||
// issues a new key; the running command finishes for both clicks.
|
||||
if (inFlight.current) return;
|
||||
setNotice(null);
|
||||
const snapshot = validated();
|
||||
if (!snapshot) return;
|
||||
if (!isSessionCurrent()) {
|
||||
setNotice({
|
||||
tone: "error",
|
||||
text: "Вход изменился. Обновите страницу и проверьте, от чьего имени отправляется приглашение.",
|
||||
});
|
||||
setFocusTarget("notice");
|
||||
return;
|
||||
}
|
||||
inFlight.current = true;
|
||||
setSending(true);
|
||||
try {
|
||||
const outcome = await runSendCommand(
|
||||
{
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need,
|
||||
terms: snapshot.terms,
|
||||
responsePeriodDays: snapshot.responsePeriodDays,
|
||||
csrfToken,
|
||||
},
|
||||
progress.current,
|
||||
{ newKey: newIdempotencyKey, onDraft: onDraftSaved },
|
||||
);
|
||||
progress.current = outcome.progress;
|
||||
if (!mounted.current) return;
|
||||
if (outcome.kind === "sent") {
|
||||
onSent(outcome.invitation);
|
||||
return;
|
||||
}
|
||||
applyFailure(describeSendFailure(outcome.stage, outcome.error));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (mounted.current) setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}
|
||||
|
||||
const salaryHintId = `${fieldId("salaryFrom")}-hint`;
|
||||
const locationHintId = `${fieldId("location")}-hint`;
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit} noValidate aria-describedby={`${prefix}-intro`}>
|
||||
<p className={styles.intro} id={`${prefix}-intro`}>
|
||||
Кандидат увидит все условия до решения и до раскрытия контактов. Все поля обязательны, кроме
|
||||
комментария к способу связи; каждое условие пакета выберите явно.
|
||||
</p>
|
||||
{summaryVisible && issues.length > 0 ? (
|
||||
<div
|
||||
className={styles["issue-summary"]}
|
||||
ref={summaryRef}
|
||||
role="alert"
|
||||
aria-labelledby={`${prefix}-issues-title`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h2 id={`${prefix}-issues-title`}>Проверьте условия приглашения</h2>
|
||||
<ul>
|
||||
{issues.map((item) => (
|
||||
<li key={item.field}>{item.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<fieldset className={styles.fields} disabled={sending}>
|
||||
<legend className={styles["visually-hidden"]}>Условия приглашения</legend>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Роль</legend>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("roleTitle")}>Название роли</label>
|
||||
<input
|
||||
id={fieldId("roleTitle")}
|
||||
value={draft.roleTitle}
|
||||
maxLength={200}
|
||||
aria-invalid={invalid("roleTitle")}
|
||||
aria-describedby={describedBy(invalid("roleTitle") && errorId("roleTitle"))}
|
||||
onChange={(event) => change({ roleTitle: event.currentTarget.value }, ["roleTitle"])}
|
||||
/>
|
||||
<FieldError id={errorId("roleTitle")} message={issueOf("roleTitle")} />
|
||||
</div>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("specialization")}>Специализация</label>
|
||||
<select
|
||||
id={fieldId("specialization")}
|
||||
value={draft.specialization}
|
||||
aria-invalid={invalid("specialization")}
|
||||
aria-describedby={describedBy(
|
||||
invalid("specialization") && errorId("specialization"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change({ specialization: event.currentTarget.value as SpecializationCode | "" }, [
|
||||
"specialization",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбрана</option>
|
||||
{specializationCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{specializationLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("specialization")} message={issueOf("specialization")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("grade")}>Грейд</label>
|
||||
<select
|
||||
id={fieldId("grade")}
|
||||
value={draft.grade}
|
||||
aria-invalid={invalid("grade")}
|
||||
aria-describedby={describedBy(invalid("grade") && errorId("grade"))}
|
||||
onChange={(event) =>
|
||||
change({ grade: event.currentTarget.value as GradeCode | "" }, ["grade"])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{gradeCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{gradeLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("grade")} message={issueOf("grade")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("offerType")}>Тип предложения</label>
|
||||
<select
|
||||
id={fieldId("offerType")}
|
||||
value={draft.offerType}
|
||||
aria-invalid={invalid("offerType")}
|
||||
aria-describedby={describedBy(invalid("offerType") && errorId("offerType"))}
|
||||
onChange={(event) =>
|
||||
change({ offerType: event.currentTarget.value as InvitationOfferType | "" }, [
|
||||
"offerType",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{offerTypeCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{offerTypeLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("offerType")} message={issueOf("offerType")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Работа и команда</legend>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("tasks")}>Задачи</label>
|
||||
<p className={styles.hint} id={`${fieldId("tasks")}-hint`}>
|
||||
По одной задаче в строке, до 20 задач.
|
||||
</p>
|
||||
<textarea
|
||||
id={fieldId("tasks")}
|
||||
rows={4}
|
||||
value={draft.tasks}
|
||||
aria-invalid={invalid("tasks")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("tasks")}-hint`,
|
||||
invalid("tasks") && errorId("tasks"),
|
||||
)}
|
||||
onChange={(event) => change({ tasks: event.currentTarget.value }, ["tasks"])}
|
||||
/>
|
||||
<FieldError id={errorId("tasks")} message={issueOf("tasks")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("team")}>Команда</label>
|
||||
<p className={styles.hint} id={`${fieldId("team")}-hint`}>
|
||||
Размер, роли и способ работы. Без персональных данных сотрудников.
|
||||
</p>
|
||||
<textarea
|
||||
id={fieldId("team")}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={draft.team}
|
||||
aria-invalid={invalid("team")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("team")}-hint`,
|
||||
invalid("team") && errorId("team"),
|
||||
)}
|
||||
onChange={(event) => change({ team: event.currentTarget.value }, ["team"])}
|
||||
/>
|
||||
<FieldError id={errorId("team")} message={issueOf("team")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("techStack")}>Технологии</label>
|
||||
<p className={styles.hint} id={`${fieldId("techStack")}-hint`}>
|
||||
Через запятую, например: Go, PostgreSQL, Kafka. Регистр не различается.
|
||||
</p>
|
||||
<input
|
||||
id={fieldId("techStack")}
|
||||
value={draft.techStack}
|
||||
aria-invalid={invalid("techStack")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("techStack")}-hint`,
|
||||
invalid("techStack") && errorId("techStack"),
|
||||
)}
|
||||
onChange={(event) => change({ techStack: event.currentTarget.value }, ["techStack"])}
|
||||
/>
|
||||
<FieldError id={errorId("techStack")} message={issueOf("techStack")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Формат и место работы</legend>
|
||||
<fieldset
|
||||
className={styles.choices}
|
||||
aria-describedby={describedBy(invalid("workFormats") && errorId("workFormats"))}
|
||||
>
|
||||
<legend>Формат работы</legend>
|
||||
{workFormatCodes.map((code) => (
|
||||
<label key={code} className={styles.choice}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.workFormats.includes(code)}
|
||||
aria-invalid={invalid("workFormats")}
|
||||
onChange={(event) => toggleFormat(code, event.currentTarget.checked)}
|
||||
/>
|
||||
{workFormatLabels[code]}
|
||||
</label>
|
||||
))}
|
||||
<FieldError id={errorId("workFormats")} message={issueOf("workFormats")} />
|
||||
</fieldset>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("location")}>Место работы</label>
|
||||
<p className={styles.hint} id={locationHintId}>
|
||||
Город или адрес офиса. Обязательно для офиса и гибрида.
|
||||
</p>
|
||||
<input
|
||||
id={fieldId("location")}
|
||||
value={draft.location}
|
||||
maxLength={100}
|
||||
aria-invalid={invalid("location")}
|
||||
aria-describedby={describedBy(
|
||||
locationHintId,
|
||||
invalid("location") && errorId("location"),
|
||||
)}
|
||||
onChange={(event) => change({ location: event.currentTarget.value }, ["location"])}
|
||||
/>
|
||||
<FieldError id={errorId("location")} message={issueOf("location")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Способ связи после принятия</legend>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("channel")}>Канал связи</label>
|
||||
<select
|
||||
id={fieldId("channel")}
|
||||
value={draft.channel}
|
||||
aria-invalid={invalid("channel")}
|
||||
aria-describedby={describedBy(invalid("channel") && errorId("channel"))}
|
||||
onChange={(event) =>
|
||||
change(
|
||||
{ channel: event.currentTarget.value as InvitationCommunicationChannel | "" },
|
||||
["channel"],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{communicationChannelCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{communicationChannelLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("channel")} message={issueOf("channel")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("channelDetails")}>Комментарий (необязательно)</label>
|
||||
<input
|
||||
id={fieldId("channelDetails")}
|
||||
value={draft.channelDetails}
|
||||
maxLength={300}
|
||||
aria-invalid={invalid("channelDetails")}
|
||||
aria-describedby={describedBy(
|
||||
invalid("channelDetails") && errorId("channelDetails"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change({ channelDetails: event.currentTarget.value }, ["channelDetails"])
|
||||
}
|
||||
/>
|
||||
<FieldError id={errorId("channelDetails")} message={issueOf("channelDetails")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group} aria-describedby={salaryHintId}>
|
||||
<legend>Зарплатная вилка, рублей в месяц</legend>
|
||||
<p className={styles.hint} id={salaryHintId}>
|
||||
Целые рубли с шагом 1 000. Нижняя граница меньше верхней, ширина вилки от 10% до 40% от
|
||||
середины. База суммы указывается явно.
|
||||
</p>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("salaryFrom")}>От, ₽</label>
|
||||
<input
|
||||
id={fieldId("salaryFrom")}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1000}
|
||||
step={1000}
|
||||
value={draft.salaryFrom}
|
||||
aria-invalid={invalid("salaryFrom")}
|
||||
aria-describedby={describedBy(invalid("salaryFrom") && errorId("salaryFrom"))}
|
||||
onChange={(event) =>
|
||||
change({ salaryFrom: event.currentTarget.value }, ["salaryFrom", "salaryTo"])
|
||||
}
|
||||
/>
|
||||
<FieldError id={errorId("salaryFrom")} message={issueOf("salaryFrom")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("salaryTo")}>До, ₽</label>
|
||||
<input
|
||||
id={fieldId("salaryTo")}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1000}
|
||||
step={1000}
|
||||
value={draft.salaryTo}
|
||||
aria-invalid={invalid("salaryTo")}
|
||||
aria-describedby={describedBy(invalid("salaryTo") && errorId("salaryTo"))}
|
||||
onChange={(event) => change({ salaryTo: event.currentTarget.value }, ["salaryTo"])}
|
||||
/>
|
||||
<FieldError id={errorId("salaryTo")} message={issueOf("salaryTo")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("taxBasis")}>База суммы</label>
|
||||
<select
|
||||
id={fieldId("taxBasis")}
|
||||
value={draft.taxBasis}
|
||||
aria-invalid={invalid("taxBasis")}
|
||||
aria-describedby={describedBy(invalid("taxBasis") && errorId("taxBasis"))}
|
||||
onChange={(event) =>
|
||||
change({ taxBasis: event.currentTarget.value as SalaryTaxBasis | "" }, [
|
||||
"taxBasis",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбрана</option>
|
||||
<option value="net">{taxBasisLabels.net}</option>
|
||||
<option value="gross">{taxBasisLabels.gross}</option>
|
||||
</select>
|
||||
<FieldError id={errorId("taxBasis")} message={issueOf("taxBasis")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Пакет</legend>
|
||||
<p className={styles.hint}>
|
||||
Для каждого условия выберите, предусмотрено ли оно. Пропустить условие нельзя.
|
||||
</p>
|
||||
{packageItemKeys.map((key) => {
|
||||
const field = `package.${key}` as const;
|
||||
const item = draft.packageItems[key];
|
||||
const choiceName = `${fieldId(field)}-status`;
|
||||
return (
|
||||
<fieldset
|
||||
key={key}
|
||||
className={styles.choices}
|
||||
aria-describedby={describedBy(invalid(field) && errorId(field))}
|
||||
>
|
||||
<legend>{packageItemLabels[key]}</legend>
|
||||
{(["provided", "not_provided"] as const).map((status) => (
|
||||
<label key={status} className={styles.choice}>
|
||||
<input
|
||||
type="radio"
|
||||
name={choiceName}
|
||||
value={status}
|
||||
checked={item.status === status}
|
||||
aria-invalid={invalid(field)}
|
||||
onChange={() => changePackage(key, { status: status as PackageChoice })}
|
||||
/>
|
||||
{status === "provided" ? "Предусмотрено" : notProvidedLabel}
|
||||
</label>
|
||||
))}
|
||||
{item.status === "provided" ? (
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId(field)}>{`${packageItemLabels[key]}: описание`}</label>
|
||||
<input
|
||||
id={fieldId(field)}
|
||||
value={item.description}
|
||||
maxLength={300}
|
||||
aria-invalid={invalid(field)}
|
||||
aria-describedby={describedBy(invalid(field) && errorId(field))}
|
||||
onChange={(event) =>
|
||||
changePackage(key, { description: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<FieldError id={errorId(field)} message={issueOf(field)} />
|
||||
</fieldset>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("responsePeriodDays")}>Срок ответа кандидата</label>
|
||||
<p className={styles.hint} id={`${fieldId("responsePeriodDays")}-hint`}>
|
||||
Срок начинается с момента доставки приглашения.
|
||||
</p>
|
||||
<select
|
||||
id={fieldId("responsePeriodDays")}
|
||||
value={draft.responsePeriodDays}
|
||||
aria-invalid={invalid("responsePeriodDays")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("responsePeriodDays")}-hint`,
|
||||
invalid("responsePeriodDays") && errorId("responsePeriodDays"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change(
|
||||
{
|
||||
responsePeriodDays: Number(event.currentTarget.value) as InvitationResponsePeriod,
|
||||
},
|
||||
["responsePeriodDays"],
|
||||
)
|
||||
}
|
||||
>
|
||||
{responsePeriods.map((days) => (
|
||||
<option key={days} value={days}>
|
||||
{responsePeriodLabel(days)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("responsePeriodDays")} message={issueOf("responsePeriodDays")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{preview ? (
|
||||
<section
|
||||
ref={previewRef}
|
||||
className={styles.preview}
|
||||
tabIndex={-1}
|
||||
aria-label="Предпросмотр приглашения"
|
||||
>
|
||||
{previewStale ? (
|
||||
<p className={styles.stale} role="status">
|
||||
Условия изменены после предпросмотра. Нажмите «Обновить предпросмотр», чтобы увидеть
|
||||
текущие.
|
||||
</p>
|
||||
) : null}
|
||||
{renderPreview(preview.snapshot)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<p
|
||||
ref={noticeRef}
|
||||
className={notice.tone === "error" ? styles["form-error"] : styles.notice}
|
||||
role={notice.tone === "error" ? "alert" : "status"}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
{sending ? (
|
||||
<p className={styles.notice} role="status">
|
||||
Отправляем приглашение...
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" isBusy={sending} onClick={showPreview}>
|
||||
{preview ? "Обновить предпросмотр" : "Показать предпросмотр"}
|
||||
</Button>
|
||||
<Button type="submit" isBusy={sending}>
|
||||
Отправить приглашение
|
||||
</Button>
|
||||
</div>
|
||||
<p className={styles.hint}>
|
||||
Предпросмотр ничего не отправляет. Отправка создает черновик и сразу доставляет его в
|
||||
кабинет кандидата; запускается срок ответа.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { InvitationComposePage } from "./ui/invitation-compose-page";
|
||||
@@ -0,0 +1,91 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
max-width: 56rem;
|
||||
}
|
||||
|
||||
.entry,
|
||||
.summary {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.entry {
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 14rem) minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fact > dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.fact > dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.result {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.title:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.state {
|
||||
display: inline-block;
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-pill);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
@media (width < 36rem) {
|
||||
.fact {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.entry {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { MyOrganizationList, Session } from "../../../shared/api/schemas";
|
||||
import { needQueryKeys } from "../../../entities/need";
|
||||
import { InvitationComposePage } from "./invitation-compose-page";
|
||||
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
|
||||
const handle = `cv1_${"B".repeat(43)}`;
|
||||
const session = {
|
||||
account: {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee02",
|
||||
email: "owner@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
function render(path: string, role: "owner" | "recruiter" = "owner"): string {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
const page: MyOrganizationList = {
|
||||
items: [
|
||||
{
|
||||
organization: { id: organizationId, name: "Северный ветер", verification_level: "e0" },
|
||||
membership: {
|
||||
organization_id: organizationId,
|
||||
role,
|
||||
state: "active",
|
||||
joined_at: "2026-09-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
};
|
||||
queryClient.setQueryData(needQueryKeys.directory(session.account.id), {
|
||||
pages: [page],
|
||||
pageParams: [undefined],
|
||||
});
|
||||
return renderToString(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<InvitationComposePage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const entryPath = `/employer/invitations/new?organization_id=${organizationId}&candidate_handle=${handle}&specialization=backend`;
|
||||
|
||||
describe("invitation compose page", () => {
|
||||
it("offers the terms form for a search entry of an owned organization", () => {
|
||||
const html = render(entryPath);
|
||||
|
||||
expect(html).toContain("Приглашение кандидату</h1>");
|
||||
expect(html).toContain("cv1_BBBB");
|
||||
expect(html).not.toContain(handle);
|
||||
expect(html).toContain("Северный ветер");
|
||||
for (const label of [
|
||||
"Название роли",
|
||||
"Специализация",
|
||||
"Грейд",
|
||||
"Тип предложения",
|
||||
"Задачи",
|
||||
"Команда",
|
||||
"Технологии",
|
||||
"Формат работы",
|
||||
"Место работы",
|
||||
"Канал связи",
|
||||
"От, ₽",
|
||||
"До, ₽",
|
||||
"База суммы",
|
||||
"Премии и бонусы",
|
||||
"Оборудование",
|
||||
"Обучение",
|
||||
"ДМС",
|
||||
"Срок ответа кандидата",
|
||||
]) {
|
||||
expect(html).toContain(label);
|
||||
}
|
||||
// The specialization of the search entry is preselected; nothing else is.
|
||||
expect(html).toMatch(/<option value="backend" selected="">Backend<\/option>/);
|
||||
expect(html).not.toMatch(/type="radio"[^>]*checked=""/);
|
||||
expect(html).toContain("Показать предпросмотр");
|
||||
expect(html).toContain("Отправить приглашение");
|
||||
expect(html).not.toContain("Так приглашение увидит кандидат");
|
||||
expect(html).not.toContain('role="alert"');
|
||||
});
|
||||
|
||||
it("does not offer the invitation to a member who is not the owner", () => {
|
||||
const html = render(entryPath, "recruiter");
|
||||
|
||||
expect(html).toContain("Нужны права владельца компании");
|
||||
expect(html).not.toContain("Отправить приглашение");
|
||||
});
|
||||
|
||||
it("asks to pick a candidate in the search when the address names none", () => {
|
||||
const html = render(`/employer/invitations/new?organization_id=${organizationId}`);
|
||||
|
||||
expect(html).toContain("Кандидат не выбран");
|
||||
expect(html).toContain(`href="/employer/candidates?organization_id=${organizationId}"`);
|
||||
expect(html).not.toContain("Отправить приглашение");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
import { useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { getOrganizationNeed } from "../../../shared/api/endpoints/need/need";
|
||||
import { useGetOrganization } from "../../../shared/api/endpoints/organization/organization";
|
||||
import {
|
||||
CandidateHandleRegExp,
|
||||
type InvitationNeedReference,
|
||||
type Organization,
|
||||
type OrganizationInvitation,
|
||||
type Session,
|
||||
type SpecializationCode,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Mono,
|
||||
Page,
|
||||
StatusView,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
formatServerMoment,
|
||||
invitationQueryKeys,
|
||||
invitationStateLabels,
|
||||
readOrganizationInvitation,
|
||||
salaryFitLabels,
|
||||
} from "../../../entities/invitation";
|
||||
import { shortHandle, specializationCodes, specializationLabels } from "../../../entities/match";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
needQueryKeys,
|
||||
useNeedOrganizationDirectory,
|
||||
type NeedOrganization,
|
||||
} from "../../../entities/need";
|
||||
import {
|
||||
emptyInvitationDraft,
|
||||
initialSendProgress,
|
||||
invitationDraftFromNeed,
|
||||
invitationDraftFromTerms,
|
||||
InvitationForm,
|
||||
type InvitationPreviewSnapshot,
|
||||
} from "../../../features/send-invitation";
|
||||
import { InvitationPreview } from "../../../widgets/invitation-preview";
|
||||
import styles from "./invitation-compose-page.module.css";
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function specializationOf(value: string | null): SpecializationCode | "" {
|
||||
return specializationCodes.find((code) => code === value) ?? "";
|
||||
}
|
||||
|
||||
type OrganizationQuery = UseQueryResult<Organization, ApiRequestError>;
|
||||
|
||||
/** What the preview shows while the company card is not available. */
|
||||
function cardFallbackOf(organization: OrganizationQuery) {
|
||||
if (organization.isPending) return <LoadingState label="Загружаем карточку компании..." />;
|
||||
if (organization.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={organization.error}
|
||||
title="Не удалось загрузить карточку компании"
|
||||
isRetrying={organization.isFetching}
|
||||
onRetry={() => void organization.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type SentInvitationProps = {
|
||||
invitation: OrganizationInvitation;
|
||||
organization: OrganizationQuery;
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
/** The invitation after sending, with the state and the deadline the server stored. */
|
||||
function SentInvitation({ invitation, organization, organizationId }: SentInvitationProps) {
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
headingRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className={styles.result} aria-labelledby="invitation-result-title">
|
||||
<h2 id="invitation-result-title" ref={headingRef} tabIndex={-1} className={styles.title}>
|
||||
{invitation.state === "delivered" ? "Приглашение доставлено" : "Приглашение уже отправлено"}
|
||||
</h2>
|
||||
<dl className={styles.summary}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Состояние</dt>
|
||||
<dd>
|
||||
<strong className={styles.state} data-state={invitation.state}>
|
||||
{invitationStateLabels[invitation.state]}
|
||||
</strong>
|
||||
</dd>
|
||||
</div>
|
||||
{invitation.delivered_at ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Доставлено</dt>
|
||||
<dd>
|
||||
<time dateTime={invitation.delivered_at}>
|
||||
{formatServerMoment(invitation.delivered_at)}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{invitation.response_deadline_at ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Кандидат может ответить до</dt>
|
||||
<dd data-term="deadline">
|
||||
<time dateTime={invitation.response_deadline_at}>
|
||||
{formatServerMoment(invitation.response_deadline_at)}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={styles.fact}>
|
||||
<dt>Версия условий</dt>
|
||||
<dd>{invitation.terms_version}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Зарплатный индикатор</dt>
|
||||
<dd>{salaryFitLabels[invitation.salary_fit]}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className={styles.hint}>
|
||||
Срок ответа задал сервер при доставке; письмо кандидату его не сдвигает. Контакты кандидата
|
||||
появятся только после принятия приглашения.
|
||||
</p>
|
||||
<InvitationPreview
|
||||
title="Отправленные условия"
|
||||
card={organization.data?.candidate_card ?? null}
|
||||
cardFallback={cardFallbackOf(organization)}
|
||||
terms={invitation.terms}
|
||||
responsePeriodDays={invitation.response_period_days}
|
||||
responseDeadlineAt={invitation.response_deadline_at}
|
||||
/>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink
|
||||
variant="secondary"
|
||||
to={`${paths.employer.candidates}?organization_id=${encodeURIComponent(organizationId)}`}
|
||||
>
|
||||
Вернуться к поиску кандидатов
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type WorkspaceProps = {
|
||||
session: Session;
|
||||
organization: NeedOrganization;
|
||||
candidateHandle: string;
|
||||
specialization: SpecializationCode | "";
|
||||
needId: string | null;
|
||||
/** Saved draft to reopen, from the address the page was opened with. */
|
||||
initialInvitationId: string | null;
|
||||
onDropNeed: () => void;
|
||||
onRestart: () => void;
|
||||
onDraftSaved: (draft: OrganizationInvitation) => void;
|
||||
};
|
||||
|
||||
/** One invitation for one search entry; remounted when the organization or the entry changes. */
|
||||
function InvitationWorkspace({
|
||||
session,
|
||||
organization,
|
||||
candidateHandle,
|
||||
specialization,
|
||||
needId,
|
||||
initialInvitationId,
|
||||
onDropNeed,
|
||||
onRestart,
|
||||
onDraftSaved,
|
||||
}: WorkspaceProps) {
|
||||
const queryClient = useQueryClient();
|
||||
// The id that this page writes into the address after creating a draft
|
||||
// changes nothing here: the workspace already holds that draft.
|
||||
const [resumeId] = useState(initialInvitationId);
|
||||
const [sent, setSent] = useState<OrganizationInvitation | null>(null);
|
||||
const accountId = session.account.id;
|
||||
const organizationId = organization.organization.id;
|
||||
const sessionCurrent = isNeedSessionCurrent(queryClient, session);
|
||||
|
||||
const company = useGetOrganization(organizationId, {
|
||||
query: {
|
||||
enabled: sessionCurrent,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
const resume = useQuery({
|
||||
queryKey: invitationQueryKeys.detail(accountId, organizationId, resumeId ?? "none"),
|
||||
queryFn: ({ signal }) => readOrganizationInvitation(organizationId, resumeId ?? "", signal),
|
||||
enabled: sessionCurrent && resumeId !== null,
|
||||
gcTime: 0,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
const need = useQuery({
|
||||
queryKey: [...needQueryKeys.detail(accountId, organizationId, needId ?? "none"), "invite"],
|
||||
queryFn: ({ signal }) => getOrganizationNeed(organizationId, needId ?? "", { signal }),
|
||||
enabled: sessionCurrent && needId !== null && resumeId === null,
|
||||
gcTime: 0,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const header = (
|
||||
<dl className={styles.entry}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Кандидат</dt>
|
||||
<dd>
|
||||
<Mono>{shortHandle(candidateHandle)}</Mono>
|
||||
{specialization ? `, ${specializationLabels[specialization]}` : null}
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Компания</dt>
|
||||
<dd>{organization.organization.name}</dd>
|
||||
</div>
|
||||
{need.data ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Потребность</dt>
|
||||
<dd>{`${need.data.title}, версия требований ${need.data.requirements_version}`}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
);
|
||||
|
||||
if (sent) {
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
<SentInvitation invitation={sent} organization={company} organizationId={organizationId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (resumeId !== null) {
|
||||
if (resume.isPending) return <LoadingState label="Открываем сохраненный черновик..." />;
|
||||
if (resume.isError) {
|
||||
return isAccessLoss(resume.error) ? (
|
||||
<StatusView
|
||||
kind="forbidden"
|
||||
title="Черновик не найден"
|
||||
description="Черновик не найден в этой компании или доступ к нему закрыт."
|
||||
action={
|
||||
<Button variant="secondary" onClick={onRestart}>
|
||||
Начать новое приглашение
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={resume.error}
|
||||
title="Не удалось открыть черновик"
|
||||
isRetrying={resume.isFetching}
|
||||
onRetry={() => void resume.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (resume.data.candidate_handle !== candidateHandle) {
|
||||
return (
|
||||
<StatusView
|
||||
kind="error"
|
||||
title="Черновик относится к другому кандидату"
|
||||
description="Откройте приглашение заново из поиска кандидатов."
|
||||
action={
|
||||
<Button variant="secondary" onClick={onRestart}>
|
||||
Начать новое приглашение
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (resume.data.state !== "draft") {
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
<SentInvitation
|
||||
invitation={resume.data}
|
||||
organization={company}
|
||||
organizationId={organizationId}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
} else if (needId !== null) {
|
||||
if (need.isPending) return <LoadingState label="Загружаем потребность..." />;
|
||||
if (need.isError) {
|
||||
return (
|
||||
<div className={styles.content}>
|
||||
<ErrorState
|
||||
error={need.error}
|
||||
title={
|
||||
isAccessLoss(need.error)
|
||||
? "Потребность не найдена"
|
||||
: "Не удалось загрузить потребность"
|
||||
}
|
||||
isRetrying={need.isFetching}
|
||||
onRetry={isAccessLoss(need.error) ? undefined : () => void need.refetch()}
|
||||
/>
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" onClick={onDropNeed}>
|
||||
Пригласить без потребности
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const draft = resume.data ?? null;
|
||||
const needReference: InvitationNeedReference | null = draft
|
||||
? draft.need
|
||||
: need.data
|
||||
? { need_id: need.data.id, requirements_version: need.data.requirements_version }
|
||||
: null;
|
||||
const initialDraft = draft
|
||||
? invitationDraftFromTerms(draft.terms, draft.response_period_days)
|
||||
: need.data
|
||||
? invitationDraftFromNeed(need.data, specialization)
|
||||
: emptyInvitationDraft(specialization);
|
||||
|
||||
const renderPreview = (snapshot: InvitationPreviewSnapshot) => (
|
||||
<InvitationPreview
|
||||
card={company.data?.candidate_card ?? null}
|
||||
cardFallback={cardFallbackOf(company)}
|
||||
terms={snapshot.terms}
|
||||
responsePeriodDays={snapshot.responsePeriodDays}
|
||||
responseDeadlineAt={null}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
{draft ? (
|
||||
<p className={styles.notice} role="status">
|
||||
{`Открыт сохраненный черновик, версия ${draft.version}. Он еще не отправлен.`}
|
||||
</p>
|
||||
) : null}
|
||||
<InvitationForm
|
||||
organizationId={organizationId}
|
||||
candidateHandle={candidateHandle}
|
||||
need={needReference}
|
||||
csrfToken={session.csrf_token}
|
||||
initialDraft={initialDraft}
|
||||
initialProgress={draft ? { ...initialSendProgress, draft } : initialSendProgress}
|
||||
isSessionCurrent={() => isNeedSessionCurrent(queryClient, session)}
|
||||
renderPreview={renderPreview}
|
||||
onDraftSaved={onDraftSaved}
|
||||
onSent={(invitation) => {
|
||||
queryClient.setQueryData(
|
||||
invitationQueryKeys.detail(accountId, organizationId, invitation.id),
|
||||
invitation,
|
||||
);
|
||||
setSent(invitation);
|
||||
}}
|
||||
onCsrfFailed={() =>
|
||||
void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() })
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The invitation of one search entry by the owner of an organization: the
|
||||
* terms form, the preview of the company card and the terms as the candidate
|
||||
* sees them, and the send result with the server deadline. The candidate is
|
||||
* named only by the organization-scoped handle from the search.
|
||||
*/
|
||||
export function InvitationComposePage() {
|
||||
const queryClient = useQueryClient();
|
||||
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
|
||||
const session = sessionQuery.data;
|
||||
const sessionReady =
|
||||
Boolean(session && session.account.scenario === "employer") &&
|
||||
isNeedSessionCurrent(queryClient, session);
|
||||
const directory = useNeedOrganizationDirectory(session, sessionReady);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const organizationId = searchParams.get("organization_id");
|
||||
const candidateHandle = searchParams.get("candidate_handle");
|
||||
const specialization = specializationOf(searchParams.get("specialization"));
|
||||
const needId = searchParams.get("need_id");
|
||||
const validEntry = Boolean(
|
||||
organizationId && candidateHandle && CandidateHandleRegExp.test(candidateHandle),
|
||||
);
|
||||
|
||||
const pages = directory.data?.pages;
|
||||
const owners = useMemo(() => activeNeedOrganizations(pages ?? []), [pages]);
|
||||
const selected = owners.find((item) => item.organization.id === organizationId);
|
||||
const member = (pages ?? [])
|
||||
.flatMap((page) => page.items)
|
||||
.find((item) => item.organization.id === organizationId);
|
||||
const hasMore = directory.hasNextPage;
|
||||
const fetchNext = directory.fetchNextPage;
|
||||
const fetching = directory.isFetchingNextPage;
|
||||
|
||||
// The organization of the address may sit on a later page of the directory.
|
||||
useEffect(() => {
|
||||
if (!directory.data || directory.isError || fetching) return;
|
||||
if (hasMore && !member) void fetchNext();
|
||||
}, [directory.data, directory.isError, fetchNext, fetching, hasMore, member]);
|
||||
|
||||
const loading =
|
||||
!sessionQuery.isError &&
|
||||
(!sessionReady || directory.isPending || (hasMore && !member && !directory.isError));
|
||||
|
||||
function updateParams(change: (params: URLSearchParams) => void): void {
|
||||
setSearchParams(
|
||||
(current) => {
|
||||
const next = new URLSearchParams(current);
|
||||
change(next);
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
const searchLink = organizationId
|
||||
? `${paths.employer.candidates}?organization_id=${encodeURIComponent(organizationId)}`
|
||||
: paths.employer.candidates;
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Приглашение кандидату"
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead="Заполните условия, проверьте, как приглашение увидит кандидат, и отправьте его. Кандидат получит приглашение в кабинет сразу после отправки."
|
||||
width="wide"
|
||||
>
|
||||
{!validEntry ? (
|
||||
<EmptyState
|
||||
title="Кандидат не выбран"
|
||||
description="Приглашение создается из результата поиска: откройте поиск кандидатов и нажмите «Пригласить» у нужной записи."
|
||||
action={<ButtonLink to={searchLink}>Перейти к поиску кандидатов</ButtonLink>}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{sessionQuery.isError ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directory.isError ? (
|
||||
isAccessDenied(directory.error) ? (
|
||||
<ForbiddenState error={directory.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directory.error}
|
||||
isRetrying={directory.isFetching}
|
||||
onRetry={() => void directory.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? <LoadingState label="Проверяем компанию..." /> : null}
|
||||
{session && sessionReady && directory.data && !directory.isError && !loading ? (
|
||||
<div className={styles.content}>
|
||||
{selected && candidateHandle ? (
|
||||
<InvitationWorkspace
|
||||
key={`${session.account.id}:${selected.organization.id}:${candidateHandle}:${generation}`}
|
||||
session={session}
|
||||
organization={selected}
|
||||
candidateHandle={candidateHandle}
|
||||
specialization={specialization}
|
||||
needId={needId}
|
||||
initialInvitationId={generation === 0 ? searchParams.get("invitation_id") : null}
|
||||
onDropNeed={() => updateParams((params) => params.delete("need_id"))}
|
||||
onRestart={() => {
|
||||
updateParams((params) => params.delete("invitation_id"));
|
||||
setGeneration((current) => current + 1);
|
||||
}}
|
||||
onDraftSaved={(draft) =>
|
||||
updateParams((params) => params.set("invitation_id", draft.id))
|
||||
}
|
||||
/>
|
||||
) : member ? (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Приглашать кандидатов в этой версии может только владелец компании."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="Компания не найдена среди ваших"
|
||||
description="Откройте приглашение из поиска кандидатов компании, где вы владелец."
|
||||
action={
|
||||
<ButtonLink to={paths.employer.candidates}>К поиску кандидатов</ButtonLink>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -42,8 +42,9 @@ export const paths = {
|
||||
candidatesForNeed: (needId: string, organizationId: string) =>
|
||||
`/employer/candidates?organization_id=${encodeURIComponent(organizationId)}&need_id=${encodeURIComponent(needId)}`,
|
||||
invitations: "/employer/invitations",
|
||||
invitationNew: "/employer/invitations/new",
|
||||
/**
|
||||
* Opens the invitations section for one search result. The handle is the
|
||||
* Opens the invitation form for one search result. The handle is the
|
||||
* organization-scoped alias from the search, never a candidate identifier.
|
||||
*/
|
||||
inviteCandidate: (input: {
|
||||
@@ -58,7 +59,7 @@ export const paths = {
|
||||
specialization: input.specialization,
|
||||
});
|
||||
if (input.needId) query.set("need_id", input.needId);
|
||||
return `/employer/invitations?${query.toString()}`;
|
||||
return `/employer/invitations/new?${query.toString()}`;
|
||||
},
|
||||
notifications: "/employer/notifications",
|
||||
supportCases: "/employer/support/cases",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Public API of the invitation-preview widget: the company card and the
|
||||
// terms of an invitation as the candidate sees them.
|
||||
|
||||
export { InvitationPreview } from "./ui/invitation-preview";
|
||||
@@ -0,0 +1,97 @@
|
||||
.root {
|
||||
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-canvas);
|
||||
}
|
||||
|
||||
.heading {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.company {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.terms {
|
||||
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);
|
||||
}
|
||||
|
||||
.role {
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.facts,
|
||||
.package {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 14rem) minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fact > dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.fact > dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.package .fact {
|
||||
grid-template-columns: minmax(7rem, 10rem) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.multiline {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
@media (width < 36rem) {
|
||||
.root,
|
||||
.terms {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.fact,
|
||||
.package .fact {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CandidateOrganizationCard, InvitationTerms } from "../../../shared/api/schemas";
|
||||
import { InvitationPreview } from "./invitation-preview";
|
||||
|
||||
const card: CandidateOrganizationCard = {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee01",
|
||||
name: "Северный ветер",
|
||||
description: "Платежная инфраструктура для малого бизнеса",
|
||||
sphere: "Финтех",
|
||||
contacts: { website: "https://north.example", email: null, phone: null, telegram: null },
|
||||
verification_level: "e0",
|
||||
};
|
||||
|
||||
const terms: 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" },
|
||||
},
|
||||
};
|
||||
|
||||
const text = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");
|
||||
|
||||
describe("invitation preview", () => {
|
||||
it("shows the company card and every term as the candidate sees them", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationPreview
|
||||
card={card}
|
||||
terms={terms}
|
||||
responsePeriodDays={7}
|
||||
responseDeadlineAt={null}
|
||||
/>,
|
||||
);
|
||||
const content = text(html);
|
||||
|
||||
for (const value of [
|
||||
"Северный ветер",
|
||||
"Платежная инфраструктура для малого бизнеса",
|
||||
"Уровень E0",
|
||||
"Middle Go-разработчик",
|
||||
"Backend, Middle",
|
||||
"Полная занятость",
|
||||
"Развивать сервис выплат",
|
||||
"Перевести отчеты на события",
|
||||
"Go, PostgreSQL",
|
||||
"Удаленно, Гибридно",
|
||||
"Москва",
|
||||
"Видеозвонок. Созвон с тимлидом",
|
||||
"Квартальная премия до 20%",
|
||||
"Ноутбук и монитор",
|
||||
"7 дней с момента доставки",
|
||||
]) {
|
||||
expect(content).toContain(value);
|
||||
}
|
||||
expect(content).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
|
||||
expect(html.match(/Не предусмотрено/g)).toHaveLength(2);
|
||||
expect(html).toContain('data-package="training"');
|
||||
expect(html).not.toContain("<time");
|
||||
});
|
||||
|
||||
it("shows the server deadline of a sent invitation and a fallback without the card", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationPreview
|
||||
card={null}
|
||||
cardFallback={<p>Карточка недоступна</p>}
|
||||
terms={{ ...terms, location: null, work_formats: ["remote"] }}
|
||||
responsePeriodDays={7}
|
||||
responseDeadlineAt="2026-10-16T10:00:00Z"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Карточка недоступна");
|
||||
expect(html).toContain('<time dateTime="2026-10-16T10:00:00Z">16 октября 2026');
|
||||
expect(html).toContain("10:00 UTC</time>");
|
||||
expect(text(html)).toContain("Не требуется: только удаленная работа");
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<div className={styles.root}>
|
||||
<div className={styles.heading}>
|
||||
<h3 className={styles.title}>{title}</h3>
|
||||
<p className={styles.hint}>
|
||||
Кандидат видит карточку компании и все условия до решения. Контакты кандидата компания
|
||||
получит только после принятия приглашения.
|
||||
</p>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ describe("match list", () => {
|
||||
|
||||
it("links every entry to the invitation with the organization-scoped handle, also unconfirmed ones", () => {
|
||||
const html = render(matchModelFixture());
|
||||
const links = [...html.matchAll(/href="(\/employer\/invitations\?[^"]+)"/g)].map(
|
||||
const links = [...html.matchAll(/href="(\/employer\/invitations\/new\?[^"]+)"/g)].map(
|
||||
(match) => new URL((match[1] ?? "").replaceAll("&", "&"), "http://x"),
|
||||
);
|
||||
|
||||
|
||||
Reference in new issue
Block a user