feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
+31
-9
@@ -2,10 +2,10 @@
|
||||
|
||||
[Русский](README.md) | English
|
||||
|
||||
A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the manual candidate profile, and the company profile use the API. The cabinets share navigation and screen states; remaining business screens are connected as they are implemented.
|
||||
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 standalone results page, candidate directory, and employer invitations 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, consents, the company page, technical status, and remaining screen placeholders.
|
||||
- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, company and employer needs pages, support cases, technical status, and remaining placeholders.
|
||||
- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus 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/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.
|
||||
@@ -17,13 +17,13 @@ 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` and `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
|
||||
| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
|
||||
| Group | Paths | Shell |
|
||||
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
|
||||
| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
|
||||
| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `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/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. The server checks authorization again for every operation.
|
||||
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.
|
||||
|
||||
`/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it.
|
||||
|
||||
@@ -49,15 +49,31 @@ After saving, the form reloads the session and shows the account step returned b
|
||||
|
||||
A 412 conflict retains the draft and offers explicit reload or replacement against the latest read version. Session errors hide private answers; responses from a previous account cannot repopulate the cache. Onboarding links follow the step returned by the server. `/candidate/questionnaire` is the destination for the saved questionnaire step.
|
||||
|
||||
## Candidate assessment
|
||||
|
||||
`/candidate/assessment` reads availability and creates attempts through the API; `/candidate/assessment/:attemptId` resumes an attempt, submits answers, and finalizes it through server commands. Real assessment requires current C3 consent. `demo_express` is labeled as a demonstration and does not award a qualification score or confirmed category. The attempt screen displays the server result, but the separate `/candidate/results` route is still a placeholder; result history and confirmed category assignment are not implemented. The client does not calculate scores.
|
||||
|
||||
The screen includes an informational notice about technical signals, but the browser does not yet collect or submit them. The server signal-ingest API exists separately; it is not connected to the UI.
|
||||
|
||||
## Privacy settings
|
||||
|
||||
`/candidate/privacy` currently shows consent management and a link to request manual assessment. Publication, search status, hidden organizations, preview, and history are available through the backend API, but a dedicated UI for these settings is not implemented. The employer candidate directory is also a placeholder; the server-side anonymous-card read API does not imply that this screen exists.
|
||||
|
||||
## Company profile
|
||||
|
||||
`pages/company` selects a company from the paginated active memberships of the current account. Only an owner may read or edit its profile. The form keeps its draft in memory, displays the server verification level without a promotion action, and builds its preview only from `candidate_card`.
|
||||
|
||||
Creation uses one idempotency key for retries of the same body after a lost response. A 412 version conflict preserves the draft; the user explicitly loads current data, reviews the reapplied changes, and saves again. Background refresh does not reset the draft. A 401/403/404 response hides the profile and clears its cached query, then reloads the company directory. This complements server membership checks rather than replacing them.
|
||||
|
||||
## Employer needs
|
||||
|
||||
`/employer/needs` shows a paginated list of organizations where the current account has an active owner membership and their needs. `/employer/needs/new?organization_id=...` creates a need, and `/employer/needs/:needId?organization_id=...` edits one. A URL or cached response grants no access: the client checks the current session and owner directory, and the server checks membership for every request. Cached data is scoped to the account and organization; a response from a prior session cannot populate the new cache. A 401/403/404 removes the organization's private queries.
|
||||
|
||||
The editor draft stays in memory. Fields and skills extracted from the source remain suggestions with provenance until the user confirms, edits, or deletes them. Unknown values are not replaced with defaults. Readiness questions appear next to missing fields; recommendation status and categories come from the API, with no fabricated results. If a create response is uncertain, retry sends the unchanged body with the same idempotency key. A 412 conflict retains the draft, offers the latest version, and requires review of reapplied changes before another save.
|
||||
|
||||
## Need entity
|
||||
|
||||
`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. The need UI is not implemented yet.
|
||||
`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. Need pages and forms live in `pages/needs`, `pages/need-editor`, and `features/edit-need`.
|
||||
|
||||
- `fromTransport` builds a draft from a `Need`. Each requirement field is an explicit state: `unknown` without a value, `extracted` as a stored suggestion with its provenance and quote, and `confirmed` as a confirmed value. An unknown field never becomes an empty string, an empty list, or a default value; a skill outside the taxonomy keeps `taxonomy_code: null`. Data that breaks the rule "value and source are null exactly when unknown" is rejected with `NeedTransportError`.
|
||||
- `toUpdateBody(need, draft)` sends only the fields whose request value changed, plus the `expected_version` of the read version. An untouched suggestion is not sent; when its field or list is sent for another reason, it goes with status `extracted`. A cleared field is sent as null, an emptied list as `[]`, and an untouched list is absent.
|
||||
@@ -67,6 +83,12 @@ Creation uses one idempotency key for retries of the same body after a lost resp
|
||||
|
||||
The tests take their fixtures from the named contract examples in `api/core/openapi.bundle.yml` and check every body with the generated `NeedCreate` and `NeedUpdate` schemas.
|
||||
|
||||
## 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.
|
||||
|
||||
Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The case page displays the status and rubric version returned by the server; the client does not create an outcome.
|
||||
|
||||
## API client generation
|
||||
|
||||
`make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values.
|
||||
|
||||
+31
-9
@@ -2,10 +2,10 @@
|
||||
|
||||
Русский | [English](README.en.md)
|
||||
|
||||
SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, ручной профиль кандидата и профиль компании работают с API. Кабинеты имеют общую навигацию и состояния экранов; оставшиеся бизнес-экраны подключаются по мере реализации.
|
||||
SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. Отдельная страница результатов, каталог кандидатов и приглашения остаются заготовками.
|
||||
|
||||
- `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута.
|
||||
- `src/pages/` - публичные страницы, вход и регистрация, согласия, компания, технический статус и оставшиеся заготовки экранов.
|
||||
- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, компания и потребности работодателя, обращения в поддержку, технический статус и оставшиеся заготовки экранов.
|
||||
- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`.
|
||||
- `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)) и `company`; `src/features/` - действия пользователя и формы.
|
||||
- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
|
||||
@@ -17,13 +17,13 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
|
||||
## Маршруты
|
||||
|
||||
| Группа | Пути | Оболочка |
|
||||
| ------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------------- |
|
||||
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
|
||||
| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` |
|
||||
| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` |
|
||||
| Группа | Пути | Оболочка |
|
||||
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
|
||||
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
|
||||
| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `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/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. Границы кабинетов читают текущую сессию и направляют гостя на вход. Сервер повторно проверяет полномочия для каждой операции.
|
||||
У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере.
|
||||
|
||||
`/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает.
|
||||
|
||||
@@ -49,15 +49,31 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
|
||||
Конфликт 412 сохраняет черновик и предлагает явное перечитывание или замену по последней прочитанной версии. Ошибки сессии скрывают приватные ответы; ответ прежнего аккаунта не заполняет кеш заново. Переходы onboarding следуют шагу, возвращенному сервером. Сохраненный шаг анкеты открывает `/candidate/questionnaire`.
|
||||
|
||||
## Проверка кандидата
|
||||
|
||||
`/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. `demo_express` помечен как демонстрационный и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки, но отдельный маршрут `/candidate/results` пока остается заглушкой; история результатов и присвоение подтвержденных категорий не реализованы. Клиент не вычисляет баллы.
|
||||
|
||||
На экране есть уведомление о технических сигналах, но браузер пока не собирает и не отправляет их. Серверный API приема сигналов существует отдельно; это не означает, что сигнализация подключена к интерфейсу.
|
||||
|
||||
## Настройки приватности
|
||||
|
||||
`/candidate/privacy` сейчас показывает управление согласиями и переход к запросу ручной оценки. Публикация карточки, статус поиска, список скрытых организаций, предпросмотр и история доступны через backend API, но отдельный интерфейс для этих настроек еще не реализован. Каталог кандидатов работодателя также остается заглушкой; наличие серверного API чтения анонимной карточки не означает наличия такого экрана.
|
||||
|
||||
## Профиль компании
|
||||
|
||||
`pages/company` выбирает компанию из постраничного списка действующих membership текущего аккаунта. Читать и менять профиль может только owner. Форма сохраняет черновик в памяти, показывает серверный уровень проверки без возможности повысить его и строит предпросмотр только из `candidate_card`.
|
||||
|
||||
Создание использует один ключ идемпотентности для повторов того же тела после потерянного ответа. При конфликте версии 412 черновик сохраняется; пользователь отдельно загружает текущие данные, проверяет перенесенные изменения и повторяет сохранение. Фоновое обновление не сбрасывает черновик. Ответ 401/403/404 скрывает профиль и очищает его запрос из кеша; список компаний перечитывается. Это дополняет серверную проверку membership, а не заменяет ее.
|
||||
|
||||
## Потребности работодателя
|
||||
|
||||
`/employer/needs` показывает постраничный список компаний, где у текущего аккаунта есть активная роль owner, и их потребности. `/employer/needs/new?organization_id=...` создает потребность, а `/employer/needs/:needId?organization_id=...` открывает ее для редактирования. URL и кеш не дают полномочий: клиент сверяет текущую сессию и каталог владельца, а сервер проверяет membership для каждого запроса. Данные кеша привязаны к аккаунту и компании; ответы предыдущей сессии не возвращаются в новый кеш. При 401/403/404 приватные запросы компании удаляются.
|
||||
|
||||
Черновик редактора хранится в памяти. Извлеченные из описания поля и навыки остаются предложениями с происхождением, пока пользователь не подтвердит, не изменит или не удалит их. Неизвестные значения не подменяются дефолтами. Вопросы готовности показываются рядом с незаполненными полями; статус рекомендаций и категории берутся из API, без выдуманных результатов. Создание повторяет неизмененное тело с тем же ключом идемпотентности после неопределенного ответа. Конфликт версии 412 сохраняет черновик, предлагает загрузить актуальную версию и требует проверить перенесенные изменения до повтора.
|
||||
|
||||
## Сущность потребности
|
||||
|
||||
`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. UI потребностей еще не реализован.
|
||||
`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. Страницы и формы потребностей находятся в `pages/needs`, `pages/need-editor` и `features/edit-need`.
|
||||
|
||||
- `fromTransport` строит черновик из `Need`. Каждое поле требования - явное состояние: `unknown` без значения, `extracted` - сохраненное предложение с происхождением и цитатой, `confirmed` - подтвержденное значение. Неизвестное поле никогда не превращается в пустую строку, пустой список или значение по умолчанию; навык вне таксономии сохраняет `taxonomy_code: null`. Данные, нарушающие правило "value и source равны null ровно при unknown", отклоняются ошибкой `NeedTransportError`.
|
||||
- `toUpdateBody(need, draft)` отправляет только поля, чье значение в запросе изменилось, и `expected_version` прочитанной версии. Нетронутое предложение не отправляется; если его поле или список отправляются по другой причине, оно уходит со статусом `extracted`. Очищенное поле уходит как null, опустошенный список - как `[]`, нетронутый список отсутствует.
|
||||
@@ -67,6 +83,12 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
|
||||
Тесты берут фикстуры из именованных примеров контракта в `api/core/openapi.bundle.yml` и проверяют каждое тело сгенерированными схемами `NeedCreate` и `NeedUpdate`.
|
||||
|
||||
## Поддержка и ручная оценка
|
||||
|
||||
`/candidate/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе.
|
||||
|
||||
Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Страница обращения показывает статус и сведения о версии рубрики, возвращенные сервером; результат не создается на клиенте.
|
||||
|
||||
## Генерация API-клиента
|
||||
|
||||
`make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения.
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
|
||||
|
||||
type InboxMessage = {
|
||||
text?: string;
|
||||
html?: string;
|
||||
};
|
||||
|
||||
type InboxResponse = {
|
||||
messages: InboxMessage[];
|
||||
};
|
||||
|
||||
type AttemptSnapshot = {
|
||||
id: string;
|
||||
kind: "root" | "demo_express";
|
||||
current_item: { id: string; prompt: string } | null;
|
||||
progress: { answered_items: number; max_items: number };
|
||||
};
|
||||
|
||||
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
|
||||
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
||||
const password = "correct horse battery staple 2026";
|
||||
|
||||
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
|
||||
|
||||
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 readInbox(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 fixture 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 InboxResponse).messages;
|
||||
}
|
||||
|
||||
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
const message = (await readInbox(email)).at(-1);
|
||||
if (message) return message;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
throw new Error("The local registration mailbox did not receive the verification message.");
|
||||
}
|
||||
|
||||
function verificationToken(message: InboxMessage): string {
|
||||
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 local registration message had no verification link.");
|
||||
return token;
|
||||
}
|
||||
|
||||
async function registerVerifiedCandidate(page: Page): Promise<void> {
|
||||
const email = `assessment-${crypto.randomUUID()}@example.test`;
|
||||
await page.goto("/register");
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(/C4/)).toHaveCount(0);
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
await page.getByRole("radio", { name: /Кандидат/ }).check();
|
||||
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
||||
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
||||
|
||||
const message = await waitForVerificationMessage(email);
|
||||
const verificationUrl = new URL("/verify-email", baseUrl());
|
||||
verificationUrl.hash = `token=${verificationToken(message)}`;
|
||||
await page.goto(verificationUrl.toString());
|
||||
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
|
||||
await expect.poll(() => page.evaluate(() => window.location.hash)).toBe("");
|
||||
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
|
||||
const confirmResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/identity/email-verifications",
|
||||
);
|
||||
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
||||
expect((await confirmResponse).status()).toBe(200);
|
||||
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
||||
|
||||
await page.goto("/candidate/questionnaire");
|
||||
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",
|
||||
);
|
||||
await page.getByRole("button", { name: "Войти" }).click();
|
||||
expect((await loginResponse).status()).toBe(201);
|
||||
}
|
||||
|
||||
async function grantC3(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/privacy");
|
||||
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
|
||||
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
new URL(item.url()).pathname === "/api/v1/me/consents/c3",
|
||||
);
|
||||
await page.getByRole("button", { name: "Дать согласие C3" }).click();
|
||||
expect((await response).status()).toBe(200);
|
||||
}
|
||||
|
||||
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
|
||||
await page.goto("/candidate/questionnaire");
|
||||
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
|
||||
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
|
||||
await page.getByLabel("Моя оценка уровня").selectOption("junior");
|
||||
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
const response = page.waitForResponse(
|
||||
(item) =>
|
||||
item.request().method() === "PUT" &&
|
||||
new URL(item.url()).pathname === "/api/v1/me/questionnaire",
|
||||
);
|
||||
await page.getByRole("button", { name: "Сохранить анкету" }).click();
|
||||
expect((await response).status()).toBe(200);
|
||||
}
|
||||
|
||||
async function focusWithKeyboard(page: Page, target: Locator): Promise<void> {
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||
await page.keyboard.press("Tab");
|
||||
if (await target.evaluate((element) => element === document.activeElement)) {
|
||||
const visible = await target.evaluate((element) => {
|
||||
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
|
||||
const style = getComputedStyle(element);
|
||||
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
|
||||
});
|
||||
expect(visible).toBe(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("Keyboard navigation did not reach the assessment action.");
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page, width: number): Promise<void> {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||||
);
|
||||
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
|
||||
}
|
||||
|
||||
async function navigateInApp(page: Page, path: string): Promise<void> {
|
||||
await page.evaluate((target) => {
|
||||
window.history.pushState(window.history.state, "", target);
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
}, path);
|
||||
}
|
||||
|
||||
function attemptPath(
|
||||
response: { url(): string; request(): { method(): string } },
|
||||
method: string,
|
||||
): boolean {
|
||||
return (
|
||||
response.request().method() === method &&
|
||||
/^\/api\/v1\/me\/assessment-attempts\/[^/]+$/.test(new URL(response.url()).pathname)
|
||||
);
|
||||
}
|
||||
|
||||
async function answerRequiredNumericItems(
|
||||
page: Page,
|
||||
attemptId: string,
|
||||
itemCount: number,
|
||||
): Promise<number> {
|
||||
let submitted = 0;
|
||||
for (let sequence = 1; sequence <= itemCount; sequence += 1) {
|
||||
await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible();
|
||||
const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ });
|
||||
await focusWithKeyboard(page, answerField);
|
||||
await page.keyboard.type("1");
|
||||
|
||||
const answerResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`,
|
||||
);
|
||||
const submitButton = page.getByRole("button", { name: "Отправить ответ" });
|
||||
await focusWithKeyboard(page, submitButton);
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await answerResponsePromise).status()).toBe(200);
|
||||
submitted += 1;
|
||||
}
|
||||
return submitted;
|
||||
}
|
||||
|
||||
test("candidate can review, resume, and finish separate assessment modes", async ({ page }) => {
|
||||
test.skip(
|
||||
!questionnaireFixtureEnabled || !mailFixtureEnabled,
|
||||
"Requires the isolated reviewed assessment-bank and mail fixtures.",
|
||||
);
|
||||
test.setTimeout(120_000);
|
||||
|
||||
await registerVerifiedCandidate(page);
|
||||
await grantC3(page);
|
||||
await saveAssessmentQuestionnaire(page);
|
||||
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible();
|
||||
await expect(page.getByText(/Метод:/)).toBeVisible();
|
||||
await expect(page.getByText("Лимит времени", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Камера, микрофон и запись экрана не используются/)).toBeVisible();
|
||||
await page.getByLabel("Язык задания").selectOption("python");
|
||||
await expect(page.getByLabel("Язык задания")).toHaveValue("python");
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
await expectNoHorizontalOverflow(page, 1280);
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
|
||||
const createRealResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать полную проверку" }).click();
|
||||
const createRealResponse = await createRealResponsePromise;
|
||||
expect(createRealResponse.status()).toBe(201);
|
||||
expect(createRealResponse.request().postDataJSON()).toMatchObject({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "python",
|
||||
});
|
||||
const realAttempt = (await createRealResponse.json()) as AttemptSnapshot;
|
||||
expect(realAttempt.kind).toBe("root");
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${realAttempt.id}$`));
|
||||
|
||||
const startRealResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`,
|
||||
);
|
||||
const firstResume = page.getByRole("button", { name: "Начать или продолжить" });
|
||||
await focusWithKeyboard(page, firstResume);
|
||||
await page.keyboard.press("Enter");
|
||||
const firstResumeResponse = await startRealResponsePromise;
|
||||
expect(firstResumeResponse.status()).toBe(200);
|
||||
const firstRealSnapshot = (await firstResumeResponse.json()) as AttemptSnapshot;
|
||||
expect(firstRealSnapshot.current_item?.id).toBeTruthy();
|
||||
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
|
||||
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
await page.screenshot({
|
||||
path: `${artifactsDirectory}/assessment-attempt-360.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await expectNoHorizontalOverflow(page, 1280);
|
||||
await page.screenshot({
|
||||
path: `${artifactsDirectory}/assessment-attempt-1280.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
|
||||
const reloadResponsePromise = page.waitForResponse((response) => attemptPath(response, "GET"));
|
||||
await page.reload();
|
||||
const reloadedRealResponse = await reloadResponsePromise;
|
||||
expect(reloadedRealResponse.status()).toBe(200);
|
||||
const reloadedRealSnapshot = (await reloadedRealResponse.json()) as AttemptSnapshot;
|
||||
expect(reloadedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id);
|
||||
const resumeAgainPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${realAttempt.id}/sessions`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать или продолжить" }).click();
|
||||
const resumeAgainResponse = await resumeAgainPromise;
|
||||
expect(resumeAgainResponse.status()).toBe(200);
|
||||
const resumedRealSnapshot = (await resumeAgainResponse.json()) as AttemptSnapshot;
|
||||
expect(resumedRealSnapshot.current_item?.id).toBe(firstRealSnapshot.current_item?.id);
|
||||
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
expect(resumedRealSnapshot.progress.max_items).toBeGreaterThan(0);
|
||||
expect(resumedRealSnapshot.progress.answered_items).toBe(0);
|
||||
expect(
|
||||
await answerRequiredNumericItems(page, realAttempt.id, resumedRealSnapshot.progress.max_items),
|
||||
).toBe(resumedRealSnapshot.progress.max_items);
|
||||
await expect(page.getByRole("button", { name: "Завершить проверку" })).toBeVisible();
|
||||
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toHaveCount(0);
|
||||
|
||||
const finalizeRealResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${realAttempt.id}/finalize`,
|
||||
);
|
||||
const resultResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
response.status() === 200 &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${realAttempt.id}/result`,
|
||||
);
|
||||
const finalizeRootButton = page.getByRole("button", { name: "Завершить проверку" });
|
||||
await focusWithKeyboard(page, finalizeRootButton);
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await finalizeRealResponsePromise).status()).toBe(200);
|
||||
const resultResponse = await resultResponsePromise;
|
||||
expect(resultResponse.status()).toBe(200);
|
||||
expect(await resultResponse.json()).toMatchObject({
|
||||
attempt_id: realAttempt.id,
|
||||
kind: "root",
|
||||
task_language: "python",
|
||||
});
|
||||
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
|
||||
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible();
|
||||
const createExpressResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать демонстрацию" }).click();
|
||||
const createExpressResponse = await createExpressResponsePromise;
|
||||
expect(createExpressResponse.status()).toBe(201);
|
||||
const expressAttempt = (await createExpressResponse.json()) as AttemptSnapshot;
|
||||
expect(expressAttempt.kind).toBe("demo_express");
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${expressAttempt.id}$`));
|
||||
|
||||
const startExpressResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать или продолжить" }).click();
|
||||
const startExpressResponse = await startExpressResponsePromise;
|
||||
expect(startExpressResponse.status()).toBe(200);
|
||||
const firstExpressSnapshot = (await startExpressResponse.json()) as AttemptSnapshot;
|
||||
expect(firstExpressSnapshot.current_item?.id).toBeTruthy();
|
||||
|
||||
await navigateInApp(page, `/candidate/assessment/${realAttempt.id}`);
|
||||
await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toHaveCount(0);
|
||||
await expect(page.getByRole("heading", { name: "Демонстрационная проверка" })).toHaveCount(0);
|
||||
await navigateInApp(page, `/candidate/assessment/${expressAttempt.id}`);
|
||||
await expect(page.getByRole("button", { name: "Начать или продолжить" })).toBeVisible();
|
||||
const resumedExpressResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать или продолжить" }).click();
|
||||
const resumedExpressResponse = await resumedExpressResponsePromise;
|
||||
expect(resumedExpressResponse.status()).toBe(200);
|
||||
const resumedExpressSnapshot = (await resumedExpressResponse.json()) as AttemptSnapshot;
|
||||
expect(resumedExpressSnapshot.current_item?.id).toBe(firstExpressSnapshot.current_item?.id);
|
||||
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
|
||||
|
||||
const answerCommands: { key: string | undefined; body: string | null }[] = [];
|
||||
const captureAnswerCommand = (request: Request) => {
|
||||
if (
|
||||
request.method() !== "POST" ||
|
||||
new URL(request.url()).pathname !==
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`
|
||||
) {
|
||||
return;
|
||||
}
|
||||
answerCommands.push({
|
||||
key: request.headers()["idempotency-key"],
|
||||
body: request.postData(),
|
||||
});
|
||||
};
|
||||
page.on("request", captureAnswerCommand);
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
const numberAnswer = page.getByRole("textbox", { name: /^Числовой ответ/ });
|
||||
await focusWithKeyboard(page, numberAnswer);
|
||||
await numberAnswer.fill("1");
|
||||
const firstSubmitButton = page.getByRole("button", { name: "Отправить ответ" });
|
||||
await focusWithKeyboard(page, firstSubmitButton);
|
||||
await page.context().setOffline(true);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("alert")).toContainText("Не удалось связаться с сервером");
|
||||
await expect.poll(() => answerCommands.length).toBe(1);
|
||||
const offlineCommand = answerCommands[0];
|
||||
expect(offlineCommand?.key).toBeTruthy();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Повторить отправку того же ответа" }),
|
||||
).toBeVisible();
|
||||
await page.context().setOffline(false);
|
||||
|
||||
let forwardedResponses = 0;
|
||||
await page.route("**/api/v1/me/assessment-attempts/*/answers", async (route: Route) => {
|
||||
const response = await route.fetch();
|
||||
forwardedResponses += 1;
|
||||
if (forwardedResponses === 1) {
|
||||
await route.fulfill({ response, body: "{}" });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
|
||||
const firstAnswerResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click();
|
||||
expect((await firstAnswerResponsePromise).status()).toBe(200);
|
||||
await expect(page.getByRole("alert")).toBeVisible();
|
||||
const retryResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
|
||||
);
|
||||
const savedAfterAnswerPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Повторить отправку того же ответа" }).click();
|
||||
expect((await retryResponsePromise).status()).toBe(200);
|
||||
const savedAfterAnswer = await savedAfterAnswerPromise;
|
||||
expect(savedAfterAnswer.status()).toBe(200);
|
||||
const savedAfterAnswerSnapshot = (await savedAfterAnswer.json()) as AttemptSnapshot;
|
||||
expect(savedAfterAnswerSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id);
|
||||
expect(savedAfterAnswerSnapshot.progress.answered_items).toBe(1);
|
||||
expect(answerCommands).toHaveLength(3);
|
||||
expect(answerCommands[0]?.key).toBeTruthy();
|
||||
expect(answerCommands[1]?.key).toBe(answerCommands[0]?.key);
|
||||
expect(answerCommands[1]?.body).toBe(answerCommands[0]?.body);
|
||||
expect(answerCommands[2]?.key).toBe(answerCommands[0]?.key);
|
||||
expect(answerCommands[2]?.body).toBe(answerCommands[0]?.body);
|
||||
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
|
||||
|
||||
await page.unroute("**/api/v1/me/assessment-attempts/*/answers");
|
||||
const expressReloadResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${expressAttempt.id}`,
|
||||
);
|
||||
await page.reload();
|
||||
const expressReloadResponse = await expressReloadResponsePromise;
|
||||
expect(expressReloadResponse.status()).toBe(200);
|
||||
const reloadedExpressSnapshot = (await expressReloadResponse.json()) as AttemptSnapshot;
|
||||
expect(reloadedExpressSnapshot.current_item?.id).not.toBe(firstExpressSnapshot.current_item?.id);
|
||||
expect(reloadedExpressSnapshot.progress.answered_items).toBe(1);
|
||||
const resumeSavedProgressPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/sessions`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать или продолжить" }).click();
|
||||
const resumeSavedProgressResponse = await resumeSavedProgressPromise;
|
||||
expect(resumeSavedProgressResponse.status()).toBe(200);
|
||||
const resumedExpressProgress = (await resumeSavedProgressResponse.json()) as AttemptSnapshot;
|
||||
expect(resumedExpressProgress.current_item?.id).toBe(reloadedExpressSnapshot.current_item?.id);
|
||||
expect(resumedExpressProgress.progress.answered_items).toBe(1);
|
||||
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
|
||||
|
||||
for (const sequence of [2, 3]) {
|
||||
const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ });
|
||||
await focusWithKeyboard(page, answerField);
|
||||
await page.keyboard.type("1");
|
||||
const answerResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/answers`,
|
||||
);
|
||||
const submitButton = page.getByRole("button", { name: "Отправить ответ" });
|
||||
await focusWithKeyboard(page, submitButton);
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await answerResponsePromise).status()).toBe(200);
|
||||
if (sequence < 3)
|
||||
await expect(page.getByRole("heading", { name: `Задание ${sequence + 1}` })).toBeVisible();
|
||||
}
|
||||
|
||||
const finalizeResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname ===
|
||||
`/api/v1/me/assessment-attempts/${expressAttempt.id}/finalize`,
|
||||
);
|
||||
const finalizeButton = page.getByRole("button", { name: "Завершить проверку" });
|
||||
await focusWithKeyboard(page, finalizeButton);
|
||||
await page.keyboard.press("Enter");
|
||||
expect((await finalizeResponsePromise).status()).toBe(200);
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.",
|
||||
),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0);
|
||||
page.off("request", captureAnswerCommand);
|
||||
});
|
||||
@@ -294,6 +294,12 @@ test.describe("company cabinet", () => {
|
||||
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
|
||||
response.status() === 412,
|
||||
);
|
||||
const csrfFailureResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PATCH" &&
|
||||
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
|
||||
response.status() === 403,
|
||||
);
|
||||
const refreshedSessionPromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
@@ -301,6 +307,8 @@ test.describe("company cabinet", () => {
|
||||
response.status() === 200,
|
||||
);
|
||||
await page.getByRole("button", { name: "Сохранить изменения" }).click();
|
||||
const csrfFailureResponse = await csrfFailureResponsePromise;
|
||||
expect(await csrfFailureResponse.json()).toMatchObject({ code: "csrf_check_failed" });
|
||||
await expect(page.getByRole("alert")).toContainText("Проверка входа обновлена");
|
||||
await refreshedSessionPromise;
|
||||
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
import { expect, test, type Locator, type Page, type Response } from "@playwright/test";
|
||||
|
||||
type InboxMessage = {
|
||||
id: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
};
|
||||
|
||||
type InboxResponse = {
|
||||
messages: InboxMessage[];
|
||||
};
|
||||
|
||||
type CurrentSessionResponse = {
|
||||
account: { id: string };
|
||||
};
|
||||
|
||||
type OrganizationResponse = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type NeedResponse = {
|
||||
id: string;
|
||||
title: string;
|
||||
source_text?: string | null;
|
||||
version: number;
|
||||
requirements_version: number;
|
||||
requirements: {
|
||||
specialization: { status: string; value: string | null; source?: { origin: string } | null };
|
||||
required_skills: {
|
||||
name: string;
|
||||
status: string;
|
||||
source?: { origin: string } | null;
|
||||
}[];
|
||||
tasks: { text: string; status: string; source?: { origin: string } | null }[];
|
||||
grade: {
|
||||
status: string;
|
||||
value: string | null;
|
||||
source?: { origin: string } | null;
|
||||
};
|
||||
salary: {
|
||||
status: string;
|
||||
value: { tax_basis: string } | null;
|
||||
source?: { origin: string } | null;
|
||||
};
|
||||
};
|
||||
readiness: { status: string; missing_fields: { field: string; question: string }[] };
|
||||
recommendations: { status: string; categories: unknown[] };
|
||||
};
|
||||
|
||||
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
||||
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
|
||||
const password = "correct horse battery staple 2026";
|
||||
|
||||
function baseUrl(): string {
|
||||
const value = process.env.E2E_BASE_URL;
|
||||
if (!value) throw new Error("The local browser test origin is not configured.");
|
||||
return value;
|
||||
}
|
||||
|
||||
function needCollectionPath(organizationId: string): string {
|
||||
return `/api/v1/organizations/${organizationId}/needs`;
|
||||
}
|
||||
|
||||
function needPath(organizationId: string, needId: string): string {
|
||||
return `${needCollectionPath(organizationId)}/${needId}`;
|
||||
}
|
||||
|
||||
async function readInbox(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 fixture 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 InboxResponse).messages;
|
||||
}
|
||||
|
||||
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
const message = (await readInbox(email)).at(-1);
|
||||
if (message) return message;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
throw new Error("The local registration mailbox did not receive the expected message.");
|
||||
}
|
||||
|
||||
function verificationToken(message: InboxMessage): string {
|
||||
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 local registration message had no verification link.");
|
||||
return token;
|
||||
}
|
||||
|
||||
async function registerVerifiedEmployer(page: Page): Promise<{ email: string; userId: string }> {
|
||||
const email = `company-${crypto.randomUUID().slice(0, 8)}@example.test`;
|
||||
await page.goto("/register");
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
await page.getByRole("radio", { name: /Работодатель/ }).check();
|
||||
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
||||
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
||||
|
||||
const message = await waitForVerificationMessage(email);
|
||||
const verificationUrl = new URL("/verify-email", baseUrl());
|
||||
verificationUrl.hash = `token=${verificationToken(message)}`;
|
||||
await page.goto(verificationUrl.toString());
|
||||
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
|
||||
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
|
||||
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
||||
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
||||
|
||||
await page.goto("/employer/company");
|
||||
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
const loginResponsePromise = 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 expect(page.getByRole("heading", { name: "Компания" })).toBeVisible();
|
||||
const loginResponse = await loginResponsePromise;
|
||||
const currentSession = (await loginResponse.json()) as CurrentSessionResponse;
|
||||
return { email, userId: currentSession.account.id };
|
||||
}
|
||||
|
||||
async function signInEmployer(page: Page, email: string): Promise<void> {
|
||||
await page.goto("/employer/needs");
|
||||
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||||
const loginResponsePromise = 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 loginResponsePromise;
|
||||
}
|
||||
|
||||
async function createOrganization(page: Page, name: string): Promise<OrganizationResponse> {
|
||||
const result = await page.evaluate(
|
||||
async ({ organizationName, key }) => {
|
||||
const sessionResponse = await fetch("/api/v1/identity/sessions/current", {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!sessionResponse.ok) return { status: sessionResponse.status, body: null };
|
||||
const session = (await sessionResponse.json()) as { csrf_token?: string };
|
||||
if (!session.csrf_token) return { status: 401, body: null };
|
||||
const response = await fetch("/api/v1/organizations", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": key,
|
||||
"X-CSRF-Token": session.csrf_token,
|
||||
},
|
||||
body: JSON.stringify({ name: organizationName }),
|
||||
});
|
||||
return {
|
||||
status: response.status,
|
||||
body: (await response.json()) as OrganizationResponse,
|
||||
};
|
||||
},
|
||||
{ organizationName: name, key: crypto.randomUUID() },
|
||||
);
|
||||
if (result.status !== 201 || !result.body) {
|
||||
throw new Error("Could not create the synthetic organization for the need flow.");
|
||||
}
|
||||
return result.body;
|
||||
}
|
||||
|
||||
async function revokeMembership(
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
successorUserId: string,
|
||||
): Promise<void> {
|
||||
const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL;
|
||||
const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN;
|
||||
if (!fixtureURL || !fixtureToken)
|
||||
throw new Error("The isolated company fixture is not configured.");
|
||||
const response = await fetch(new URL(fixtureURL), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${fixtureToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
organization_id: organizationId,
|
||||
user_id: userId,
|
||||
successor_user_id: successorUserId,
|
||||
}),
|
||||
});
|
||||
if (response.status !== 204) {
|
||||
throw new Error(
|
||||
`The isolated company fixture could not transfer the synthetic membership (status ${response.status}).`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function findSkillRow(section: Locator, name: string): Promise<Locator> {
|
||||
const rows = section.getByRole("listitem");
|
||||
for (let index = 0; index < (await rows.count()); index += 1) {
|
||||
const row = rows.nth(index);
|
||||
if ((await row.locator("input").inputValue()) === name) return row;
|
||||
}
|
||||
throw new Error(`The parsed need did not contain the expected skill ${name}.`);
|
||||
}
|
||||
|
||||
function isResponse(response: Response, method: string, path: string, status: number): boolean {
|
||||
return (
|
||||
response.request().method() === method &&
|
||||
new URL(response.url()).pathname === path &&
|
||||
response.status() === status
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizedPageError(error: Error, privateValues: string[]): string {
|
||||
let message = error.message.split("\n", 1)[0] ?? "";
|
||||
for (const value of privateValues) {
|
||||
if (value !== "") message = message.replaceAll(value, "[redacted]");
|
||||
}
|
||||
message = message
|
||||
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[email]")
|
||||
.replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, "[id]");
|
||||
return `${error.name}: ${message.slice(0, 180)}`;
|
||||
}
|
||||
|
||||
test.use({ trace: "off", screenshot: "off", video: "off" });
|
||||
|
||||
test.describe("employer needs", () => {
|
||||
test.skip(
|
||||
!mailFixtureEnabled || !companyFixtureEnabled,
|
||||
"Requires the isolated mail and company fixtures.",
|
||||
);
|
||||
|
||||
test("creates, edits, reloads, handles conflicts, and removes private data after owner access ends", async ({
|
||||
browser,
|
||||
page,
|
||||
}) => {
|
||||
const owner = await registerVerifiedEmployer(page);
|
||||
const suffix = crypto.randomUUID().slice(0, 8);
|
||||
const organization = await createOrganization(page, `Need team ${suffix}`);
|
||||
const sourceText =
|
||||
"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.";
|
||||
const pageErrors: string[] = [];
|
||||
page.on("pageerror", (error) => {
|
||||
pageErrors.push(sanitizedPageError(error, [owner.email, sourceText, suffix]));
|
||||
});
|
||||
|
||||
await page.goto(`/employer/needs?organization_id=${encodeURIComponent(organization.id)}`);
|
||||
await expect(
|
||||
page.getByRole("status").getByText("Потребностей пока нет", { exact: true }),
|
||||
).toBeVisible();
|
||||
await page.getByRole("link", { name: "Создать потребность" }).first().click();
|
||||
await expect(page.getByLabel("Название потребности")).toBeVisible();
|
||||
await expect(page.getByText("Вакансия для сохранения потребности не требуется.")).toBeVisible();
|
||||
await expect(page.getByLabel("Грейд")).toHaveValue("");
|
||||
await expect(page.getByLabel("База суммы")).toHaveValue("");
|
||||
await expect(
|
||||
page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."),
|
||||
).toBeVisible();
|
||||
await page.getByLabel("Название потребности").fill(`Payments backend ${suffix}`);
|
||||
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
|
||||
await page.getByLabel("Описание работы").fill(sourceText);
|
||||
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
|
||||
|
||||
const organizationNeedsPath = needCollectionPath(organization.id);
|
||||
const createResponsePromise = page.waitForResponse((response) =>
|
||||
isResponse(response, "POST", organizationNeedsPath, 201),
|
||||
);
|
||||
await page.getByRole("button", { name: "Создать потребность" }).click();
|
||||
const createResponse = await createResponsePromise;
|
||||
const createRequest = createResponse.request();
|
||||
expect(createRequest.headers()["x-csrf-token"]).toBeTruthy();
|
||||
expect(createRequest.headers()["idempotency-key"]).toBeTruthy();
|
||||
const created = (await createResponse.json()) as NeedResponse;
|
||||
expect(created.version).toBe(1);
|
||||
expect(created.requirements_version).toBe(1);
|
||||
expect(created.requirements.grade.status).toBe("unknown");
|
||||
expect(created.requirements.grade.value).toBeNull();
|
||||
expect(created.readiness.missing_fields.map((field) => field.field)).toContain("salary");
|
||||
expect(created.recommendations.status).toBe("not_available");
|
||||
|
||||
const requiredSkills = page
|
||||
.getByRole("heading", { name: "Обязательные навыки" })
|
||||
.locator("xpath=..");
|
||||
await expect(requiredSkills.getByRole("listitem")).toHaveCount(3);
|
||||
const goRow = await findSkillRow(requiredSkills, "Go");
|
||||
const postgresRow = await findSkillRow(requiredSkills, "PostgreSQL");
|
||||
const temporalRow = await findSkillRow(requiredSkills, "Temporal");
|
||||
await goRow.getByRole("button", { name: "Подтвердить", exact: true }).click();
|
||||
await temporalRow.locator("input").fill("TemporalDB");
|
||||
await postgresRow.getByRole("button", { name: "Удалить", exact: true }).click();
|
||||
|
||||
const needId = created.id;
|
||||
const itemPath = needPath(organization.id, needId);
|
||||
const firstSavePromise = page.waitForResponse((response) =>
|
||||
isResponse(response, "PATCH", itemPath, 200),
|
||||
);
|
||||
await page.getByRole("button", { name: "Сохранить изменения" }).click();
|
||||
const firstSave = (await firstSavePromise).json() as Promise<NeedResponse>;
|
||||
const saved = await firstSave;
|
||||
expect(saved.version).toBe(2);
|
||||
expect(saved.requirements.required_skills.map((skill) => skill.name)).toEqual([
|
||||
"Go",
|
||||
"TemporalDB",
|
||||
]);
|
||||
expect(saved.recommendations.status).toBe("pending");
|
||||
expect(saved.recommendations.categories).toEqual([]);
|
||||
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
|
||||
|
||||
const reloadResponsePromise = page.waitForResponse((response) =>
|
||||
isResponse(response, "GET", itemPath, 200),
|
||||
);
|
||||
await page.reload();
|
||||
const reloaded = (await reloadResponsePromise).json() as Promise<NeedResponse>;
|
||||
const reloadedNeed = await reloaded;
|
||||
expect(reloadedNeed.requirements.required_skills.map((skill) => skill.name)).not.toContain(
|
||||
"PostgreSQL",
|
||||
);
|
||||
await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText);
|
||||
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
|
||||
|
||||
const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
||||
const secondPage = await secondContext.newPage();
|
||||
try {
|
||||
await signInEmployer(secondPage, owner.email);
|
||||
await secondPage.goto(
|
||||
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
|
||||
);
|
||||
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(
|
||||
`Payments backend ${suffix}`,
|
||||
);
|
||||
|
||||
const firstWindowTitle = `Payments backend first ${suffix}`;
|
||||
await page.getByLabel("Название потребности").fill(firstWindowTitle);
|
||||
const firstWindowSave = page.waitForResponse((response) =>
|
||||
isResponse(response, "PATCH", itemPath, 200),
|
||||
);
|
||||
await page.getByRole("button", { name: "Сохранить изменения" }).click();
|
||||
const firstWindowResponse = await firstWindowSave;
|
||||
const firstWindowSaved = (await firstWindowResponse.json()) as NeedResponse;
|
||||
expect(firstWindowSaved.title).toBe(firstWindowTitle);
|
||||
await expect(page.getByLabel("Название потребности")).toHaveValue(firstWindowTitle);
|
||||
|
||||
const secondWindowDraft = `Payments backend second ${suffix}`;
|
||||
await secondPage.getByLabel("Название потребности").fill(secondWindowDraft);
|
||||
const conflictResponsePromise = secondPage.waitForResponse((response) =>
|
||||
isResponse(response, "PATCH", itemPath, 412),
|
||||
);
|
||||
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
|
||||
expect((await conflictResponsePromise).status()).toBe(412);
|
||||
await expect(secondPage.getByRole("heading", { name: "Версия изменилась" })).toBeVisible();
|
||||
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
|
||||
|
||||
const latestResponsePromise = secondPage.waitForResponse((response) =>
|
||||
isResponse(response, "GET", itemPath, 200),
|
||||
);
|
||||
await secondPage.getByRole("button", { name: "Загрузить и применить мой черновик" }).click();
|
||||
await latestResponsePromise;
|
||||
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
|
||||
await expect(
|
||||
secondPage.getByRole("heading", { name: "Проверьте объединенный черновик" }),
|
||||
).toBeVisible();
|
||||
await secondPage.getByRole("button", { name: "Продолжить сохранение" }).click();
|
||||
const rebasedSavePromise = secondPage.waitForResponse((response) =>
|
||||
isResponse(response, "PATCH", itemPath, 200),
|
||||
);
|
||||
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
|
||||
const rebasedSaveResponse = await rebasedSavePromise;
|
||||
const rebased = (await rebasedSaveResponse.json()) as NeedResponse;
|
||||
expect(rebased.title).toBe(secondWindowDraft);
|
||||
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
|
||||
|
||||
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
|
||||
await page.setViewportSize({ width: 360, height: 900 });
|
||||
const hasHorizontalOverflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||||
);
|
||||
expect(hasHorizontalOverflow).toBe(false);
|
||||
await page.screenshot({
|
||||
path: `${artifactsDirectory}/need-editor-mobile.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.screenshot({
|
||||
path: `${artifactsDirectory}/need-editor-desktop.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
|
||||
const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
||||
try {
|
||||
const successorPage = await successorContext.newPage();
|
||||
const successor = await registerVerifiedEmployer(successorPage);
|
||||
await successorPage.goto(
|
||||
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
|
||||
);
|
||||
await expect(
|
||||
successorPage.getByText("Потребность недоступна", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(successorPage.getByLabel("Название потребности")).toHaveCount(0);
|
||||
const beforeTransferStatus = await successorPage.evaluate(
|
||||
async ({ orgId, id }) => {
|
||||
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
return response.status;
|
||||
},
|
||||
{ orgId: organization.id, id: needId },
|
||||
);
|
||||
expect(beforeTransferStatus).toBe(404);
|
||||
|
||||
await revokeMembership(organization.id, owner.userId, successor.userId);
|
||||
|
||||
async function expectOwnerAccessRemoved(targetPage: Page): Promise<void> {
|
||||
await test.step("Refresh directory after owner access is revoked", async () => {
|
||||
const directoryResponsePromise = targetPage.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/organizations" &&
|
||||
response.status() === 200,
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await targetPage.bringToFront();
|
||||
await targetPage.evaluate(() => {
|
||||
window.dispatchEvent(new Event("visibilitychange"));
|
||||
});
|
||||
await directoryResponsePromise;
|
||||
await expect(
|
||||
targetPage.getByText("Потребность недоступна", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(targetPage.getByLabel("Название потребности")).toHaveCount(0);
|
||||
await expect(targetPage.getByLabel("Описание работы")).toHaveCount(0);
|
||||
await expect(targetPage.getByText(sourceText, { exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
await expectOwnerAccessRemoved(page);
|
||||
await expectOwnerAccessRemoved(secondPage);
|
||||
const revokedStatus = await page.evaluate(
|
||||
async ({ orgId, id }) => {
|
||||
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
return response.status;
|
||||
},
|
||||
{ orgId: organization.id, id: needId },
|
||||
);
|
||||
expect(revokedStatus).toBe(404);
|
||||
|
||||
const successorNeedResponse = successorPage.waitForResponse((response) =>
|
||||
isResponse(response, "GET", itemPath, 200),
|
||||
);
|
||||
await successorPage.goto(
|
||||
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
|
||||
);
|
||||
await successorNeedResponse;
|
||||
await expect(successorPage.getByLabel("Название потребности")).toHaveValue(
|
||||
secondWindowDraft,
|
||||
);
|
||||
} finally {
|
||||
await successorContext.close();
|
||||
}
|
||||
} finally {
|
||||
await secondContext.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("creates a manual need without source text and keeps recommendations pending", async ({
|
||||
page,
|
||||
}) => {
|
||||
await registerVerifiedEmployer(page);
|
||||
const suffix = crypto.randomUUID().slice(0, 8);
|
||||
const organization = await createOrganization(page, `Manual need ${suffix}`);
|
||||
const collectionPath = needCollectionPath(organization.id);
|
||||
await page.goto(`/employer/needs/new?organization_id=${encodeURIComponent(organization.id)}`);
|
||||
await expect(page.getByLabel("Название потребности")).toBeVisible();
|
||||
await page.getByLabel("Название потребности").fill(`Manual Go developer ${suffix}`);
|
||||
await expect(page.getByLabel("Описание работы")).toHaveValue("");
|
||||
await page.getByLabel("Специализация").selectOption("backend");
|
||||
await page.getByLabel("Грейд").selectOption("junior");
|
||||
|
||||
const requiredSkills = page
|
||||
.getByRole("heading", { name: "Обязательные навыки" })
|
||||
.locator("xpath=..");
|
||||
await requiredSkills.getByLabel("Добавить навык").fill("Go");
|
||||
await requiredSkills.getByRole("button", { name: "Добавить", exact: true }).click();
|
||||
const tasks = page.getByRole("heading", { name: "Задачи команды" }).locator("xpath=..");
|
||||
await tasks.getByLabel("Добавить задачу").fill("Развивать сервис уведомлений");
|
||||
await tasks.getByRole("button", { name: "Добавить", exact: true }).click();
|
||||
await page.getByLabel("От, рублей в месяц").fill("100000");
|
||||
await page.getByLabel("До, рублей в месяц").fill("130000");
|
||||
await page.getByLabel("База суммы").selectOption("net");
|
||||
|
||||
const createResponsePromise = page.waitForResponse((response) =>
|
||||
isResponse(response, "POST", collectionPath, 201),
|
||||
);
|
||||
await page.getByRole("button", { name: "Создать потребность" }).click();
|
||||
const createResponse = await createResponsePromise;
|
||||
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
|
||||
expect(createBody).not.toHaveProperty("source_text");
|
||||
expect(createBody).not.toHaveProperty("vacancy_id");
|
||||
const created = (await createResponse.json()) as NeedResponse;
|
||||
expect(created.source_text).toBeNull();
|
||||
expect(created.requirements.specialization).toMatchObject({
|
||||
status: "confirmed",
|
||||
value: "backend",
|
||||
source: { origin: "manual" },
|
||||
});
|
||||
expect(created.requirements.grade).toMatchObject({
|
||||
status: "confirmed",
|
||||
value: "junior",
|
||||
source: { origin: "manual" },
|
||||
});
|
||||
expect(created.requirements.required_skills).toHaveLength(1);
|
||||
expect(created.requirements.required_skills[0]).toMatchObject({
|
||||
name: "Go",
|
||||
status: "confirmed",
|
||||
source: { origin: "manual" },
|
||||
});
|
||||
expect(created.requirements.tasks).toHaveLength(1);
|
||||
expect(created.requirements.tasks[0]).toMatchObject({
|
||||
text: "Развивать сервис уведомлений",
|
||||
status: "confirmed",
|
||||
source: { origin: "manual" },
|
||||
});
|
||||
expect(created.requirements.salary).toMatchObject({
|
||||
status: "confirmed",
|
||||
value: { tax_basis: "net" },
|
||||
source: { origin: "manual" },
|
||||
});
|
||||
expect(created.recommendations).toMatchObject({ status: "pending", categories: [] });
|
||||
expect(created.readiness.status).toBe("incomplete");
|
||||
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
|
||||
|
||||
const detailPath = needPath(organization.id, created.id);
|
||||
const reloadResponsePromise = page.waitForResponse((response) =>
|
||||
isResponse(response, "GET", detailPath, 200),
|
||||
);
|
||||
await page.reload();
|
||||
const reloadResponse = await reloadResponsePromise;
|
||||
const persisted = (await reloadResponse.json()) as NeedResponse;
|
||||
expect(persisted.source_text).toBeNull();
|
||||
expect(persisted.requirements.grade.source?.origin).toBe("manual");
|
||||
expect(persisted.requirements.required_skills[0]?.source?.origin).toBe("manual");
|
||||
expect(persisted.requirements.salary.source?.origin).toBe("manual");
|
||||
expect(persisted.recommendations).toMatchObject({ status: "pending", categories: [] });
|
||||
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,445 @@
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
type InboxMessage = {
|
||||
id: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
};
|
||||
|
||||
type InboxResponse = {
|
||||
messages: InboxMessage[];
|
||||
};
|
||||
|
||||
type SupportCaseResponse = {
|
||||
id: string;
|
||||
number: string;
|
||||
type: string;
|
||||
status: string;
|
||||
description: string;
|
||||
assessment_target: { specialization: string; grade: string } | null;
|
||||
rubric_version: number | null;
|
||||
response_target: { business_days: number; kind: string; due_at: string };
|
||||
decision: unknown;
|
||||
};
|
||||
|
||||
type SupportCaseListResponse = {
|
||||
items: Pick<SupportCaseResponse, "id" | "number" | "type">[];
|
||||
};
|
||||
|
||||
type ConsentList = {
|
||||
items: { purpose: string; state: string }[];
|
||||
};
|
||||
|
||||
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
||||
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
|
||||
const testPassword = "correct horse battery staple 2026";
|
||||
|
||||
test.use({ trace: "off", screenshot: "off", video: "off" });
|
||||
|
||||
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 readInbox(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 InboxResponse).messages;
|
||||
}
|
||||
|
||||
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
const message = (await readInbox(email)).at(-1);
|
||||
if (message) return message;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
throw new Error("The local registration mailbox did not receive the verification message.");
|
||||
}
|
||||
|
||||
function tokenFromMessage(message: InboxMessage): string {
|
||||
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 local registration message had no verification link.");
|
||||
return token;
|
||||
}
|
||||
|
||||
async function registerCandidate(page: Page, prefix: string): Promise<string> {
|
||||
const email = `${prefix}-${crypto.randomUUID()}@example.test`;
|
||||
await page.goto("/register");
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(testPassword);
|
||||
await page.getByRole("radio", { name: /Кандидат/ }).check();
|
||||
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
||||
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
||||
|
||||
const message = await waitForVerificationMessage(email);
|
||||
const verificationUrl = new URL("/verify-email", baseURL());
|
||||
verificationUrl.hash = `token=${tokenFromMessage(message)}`;
|
||||
await page.goto(verificationUrl.toString());
|
||||
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
|
||||
expect(await page.evaluate(() => window.location.hash)).toBe("");
|
||||
await page.getByLabel("Пароль, выбранный при регистрации").fill(testPassword);
|
||||
const confirmation = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
||||
expect((await confirmation).status()).toBe(200);
|
||||
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
||||
|
||||
await page.goto("/login");
|
||||
await page.getByLabel("Электронная почта").fill(email);
|
||||
await page.getByLabel("Пароль", { exact: true }).fill(testPassword);
|
||||
const login = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await page.getByRole("button", { name: "Войти" }).click();
|
||||
expect((await login).status()).toBe(201);
|
||||
return email;
|
||||
}
|
||||
|
||||
async function replaySupportCaseCreate(
|
||||
page: Page,
|
||||
originalResponse: Awaited<ReturnType<Page["waitForResponse"]>>,
|
||||
): Promise<SupportCaseResponse> {
|
||||
const originalRequest = originalResponse.request();
|
||||
const body = originalRequest.postData();
|
||||
const idempotencyKey = originalRequest.headers()["idempotency-key"];
|
||||
expect(body).toBeTruthy();
|
||||
expect(idempotencyKey).toBeTruthy();
|
||||
|
||||
const replay = await page.evaluate(
|
||||
async ({ body, idempotencyKey }) => {
|
||||
const sessionResponse = await fetch("/api/v1/identity/sessions/current", {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!sessionResponse.ok) throw new Error("Could not read the current local session.");
|
||||
const session = (await sessionResponse.json()) as { csrf_token?: string };
|
||||
if (!session.csrf_token) throw new Error("The current local session has no CSRF token.");
|
||||
|
||||
const response = await fetch("/api/v1/me/support-cases", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": idempotencyKey,
|
||||
"X-CSRF-Token": session.csrf_token,
|
||||
},
|
||||
body,
|
||||
});
|
||||
return {
|
||||
status: response.status,
|
||||
body: (await response.json()) as SupportCaseResponse,
|
||||
};
|
||||
},
|
||||
{ body: body ?? "", idempotencyKey: idempotencyKey ?? "" },
|
||||
);
|
||||
|
||||
expect(replay.status).toBe(201);
|
||||
return replay.body;
|
||||
}
|
||||
|
||||
async function focusByKeyboard(page: Page, target: Locator): Promise<void> {
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||
await page.keyboard.press("Tab");
|
||||
if (await target.evaluate((element) => element === document.activeElement)) {
|
||||
const hasVisibleFocus = await target.evaluate((element) => {
|
||||
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
|
||||
const style = getComputedStyle(element);
|
||||
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
|
||||
});
|
||||
expect(hasVisibleFocus).toBe(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("Keyboard navigation did not reach the requested control.");
|
||||
}
|
||||
|
||||
async function checkResponsiveForm(
|
||||
page: Page,
|
||||
target: Locator,
|
||||
widths = [360, 768, 1280],
|
||||
): Promise<void> {
|
||||
for (const width of widths) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await focusByKeyboard(page, target);
|
||||
const hasHorizontalOverflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||||
);
|
||||
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("candidate support cases and manual assessment", () => {
|
||||
test.skip(
|
||||
!mailFixtureEnabled || !questionnaireFixtureEnabled,
|
||||
"Requires the isolated local mail and published-bank fixtures.",
|
||||
);
|
||||
|
||||
test("creates and reloads a support case from an unavailable assessment and hides it from another account", async ({
|
||||
page,
|
||||
}) => {
|
||||
await registerCandidate(page, "support-author");
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("link", { name: "Поддержка", exact: true })).toBeVisible();
|
||||
await page.getByRole("link", { name: "Поддержка", exact: true }).click();
|
||||
await expect(page).toHaveURL(/\/candidate\/support\/cases$/);
|
||||
await page.getByRole("link", { name: "Написать в поддержку" }).click();
|
||||
await expect(page).toHaveURL(/\/candidate\/support\/cases\/new$/);
|
||||
|
||||
const description = "Не удается открыть оценку для выбранной категории.";
|
||||
const textarea = page.getByLabel("Что произошло или какая помощь нужна");
|
||||
await textarea.fill(description);
|
||||
await checkResponsiveForm(page, textarea);
|
||||
|
||||
await page.setViewportSize({ width: 360, height: 900 });
|
||||
const submitButton = page.getByRole("button", { name: "Отправить обращение" });
|
||||
await focusByKeyboard(page, submitButton);
|
||||
const createResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await page.keyboard.press("Enter");
|
||||
const createResponse = await createResponsePromise;
|
||||
expect(createResponse.status()).toBe(201);
|
||||
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
|
||||
expect(createBody).toMatchObject({ type: "support", description });
|
||||
expect("assessment_target" in createBody).toBe(false);
|
||||
const created = (await createResponse.json()) as SupportCaseResponse;
|
||||
expect(created.type).toBe("support");
|
||||
expect(created.description).toBe(description);
|
||||
expect(created.response_target.kind).toBe("operational_goal");
|
||||
|
||||
const casePath = `/candidate/support/cases/${created.id}`;
|
||||
await expect(page).toHaveURL(new RegExp(`${created.id}$`));
|
||||
await expect(page.getByText(description, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Операционная цель", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/рабочих дней/)).toBeVisible();
|
||||
|
||||
const detailResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
await page.reload();
|
||||
expect((await detailResponsePromise).status()).toBe(200);
|
||||
await expect(page.getByText(description, { exact: true })).toBeVisible();
|
||||
const replayed = await replaySupportCaseCreate(page, createResponse);
|
||||
expect(replayed.id).toBe(created.id);
|
||||
const supportList = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/v1/me/support-cases?limit=100", {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) throw new Error("Could not read the local support case list.");
|
||||
return (await response.json()) as SupportCaseListResponse;
|
||||
});
|
||||
expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1);
|
||||
await page.getByRole("link", { name: "Мои обращения" }).click();
|
||||
await expect(page.getByRole("link", { name: created.number })).toBeVisible();
|
||||
|
||||
const logoutStatus = await page.evaluate(async () => {
|
||||
const current = await fetch("/api/v1/identity/sessions/current", {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!current.ok) return current.status;
|
||||
const session = (await current.json()) as { csrf_token?: string };
|
||||
if (!session.csrf_token) return 0;
|
||||
const response = await fetch("/api/v1/identity/sessions/current", {
|
||||
method: "DELETE",
|
||||
credentials: "include",
|
||||
headers: { "X-CSRF-Token": session.csrf_token },
|
||||
});
|
||||
return response.status;
|
||||
});
|
||||
expect(logoutStatus).toBe(204);
|
||||
|
||||
await registerCandidate(page, "support-reader");
|
||||
await page.goto(casePath);
|
||||
const foreignDetail = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
await page.reload();
|
||||
expect((await foreignDetail).status()).toBe(404);
|
||||
await expect(page.getByText("Обращение не найдено или недоступно")).toBeVisible();
|
||||
await expect(page.getByText(description, { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("allows a manual request after C3 revocation without an attempt or an automatic grant", async ({
|
||||
page,
|
||||
}) => {
|
||||
await registerCandidate(page, "manual-author");
|
||||
await page.goto("/candidate/privacy");
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Согласия и настройки приватности" }),
|
||||
).toBeVisible();
|
||||
|
||||
const c3Text = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/consent-texts/c3" &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
|
||||
expect((await c3Text).status()).toBe(200);
|
||||
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
|
||||
const grantList = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/consents" &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
const grantResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/consents/c3" &&
|
||||
response.request().method() === "PUT",
|
||||
);
|
||||
await page.getByRole("button", { name: "Дать согласие C3" }).click();
|
||||
expect((await grantResponse).status()).toBe(200);
|
||||
const activeC3List = (await (await grantList).json()) as ConsentList;
|
||||
expect(
|
||||
activeC3List.items.some((record) => record.purpose === "c3" && record.state === "active"),
|
||||
).toBe(true);
|
||||
|
||||
await page.getByRole("button", { name: "Отозвать C3", exact: true }).click();
|
||||
await page.getByLabel("Я понимаю последствия отзыва C3.").check();
|
||||
const revokeList = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/consents" &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
const revokeResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/consents/c3" &&
|
||||
response.request().method() === "DELETE",
|
||||
);
|
||||
await page.getByRole("button", { name: "Подтвердить отзыв" }).click();
|
||||
expect((await revokeResponse).status()).toBe(204);
|
||||
const revokedC3List = (await (await revokeList).json()) as ConsentList;
|
||||
expect(
|
||||
revokedC3List.items.some((record) => record.purpose === "c3" && record.state === "active"),
|
||||
).toBe(false);
|
||||
|
||||
const attemptRequests: string[] = [];
|
||||
page.on("request", (request) => {
|
||||
const url = new URL(request.url());
|
||||
if (url.pathname === "/api/v1/me/assessment-attempts") attemptRequests.push(request.method());
|
||||
});
|
||||
await page.goto("/candidate/support/cases/manual-assessment");
|
||||
const specialization = page.getByLabel("Специальность");
|
||||
await expect(specialization.locator("option[value='frontend']")).toHaveCount(1);
|
||||
await specialization.selectOption("frontend");
|
||||
await expect(page.getByText(/Запрос ручной оценки остается доступен/)).toBeVisible();
|
||||
await page.getByLabel("Желаемый грейд").selectOption("junior");
|
||||
const reason = "Прошу эксперта оценить эту категорию вручную.";
|
||||
const description = page.getByLabel("Почему вы просите ручную оценку");
|
||||
await description.fill(reason);
|
||||
await expect(page.getByText(/не требует C3/)).toBeVisible();
|
||||
await checkResponsiveForm(page, specialization);
|
||||
|
||||
await page.setViewportSize({ width: 360, height: 900 });
|
||||
const submitButton = page.getByRole("button", { name: "Отправить запрос эксперту" });
|
||||
await focusByKeyboard(page, submitButton);
|
||||
const createResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await page.keyboard.press("Enter");
|
||||
const createResponse = await createResponsePromise;
|
||||
expect(createResponse.status()).toBe(201);
|
||||
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
|
||||
expect(createBody).toMatchObject({
|
||||
type: "manual_assessment",
|
||||
description: reason,
|
||||
assessment_target: { specialization: "frontend", grade: "junior" },
|
||||
});
|
||||
expect("object" in createBody).toBe(false);
|
||||
const created = (await createResponse.json()) as SupportCaseResponse;
|
||||
expect(created.type).toBe("manual_assessment");
|
||||
expect(created.status).toBe("waiting_expert");
|
||||
expect(created.assessment_target).toEqual({ specialization: "frontend", grade: "junior" });
|
||||
expect(created.rubric_version).toBeNull();
|
||||
expect(created.decision).toBeNull();
|
||||
expect(attemptRequests).toEqual([]);
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась.",
|
||||
),
|
||||
).toBeVisible();
|
||||
|
||||
const detailResponsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === `/api/v1/me/support-cases/${created.id}` &&
|
||||
response.request().method() === "GET",
|
||||
);
|
||||
await page.reload();
|
||||
expect((await detailResponsePromise).status()).toBe(200);
|
||||
await expect(page.getByText(reason, { exact: true })).toBeVisible();
|
||||
const replayed = await replaySupportCaseCreate(page, createResponse);
|
||||
expect(replayed.id).toBe(created.id);
|
||||
const supportList = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/v1/me/support-cases?limit=100", {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) throw new Error("Could not read the local support case list.");
|
||||
return (await response.json()) as SupportCaseListResponse;
|
||||
});
|
||||
expect(supportList.items.filter((item) => item.id === created.id)).toHaveLength(1);
|
||||
|
||||
const activeC3AfterRequest = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" });
|
||||
if (!response.ok) return null;
|
||||
const body = (await response.json()) as ConsentList;
|
||||
return body.items.some((record) => record.purpose === "c3" && record.state === "active");
|
||||
});
|
||||
expect(activeC3AfterRequest).toBe(false);
|
||||
|
||||
await page.goto("/candidate/support/cases/manual-assessment");
|
||||
await page.getByLabel("Специальность").selectOption("backend");
|
||||
await page.getByLabel("Желаемый грейд").selectOption("junior");
|
||||
const backendReason = "Прошу эксперта оценить Backend на уровне Junior.";
|
||||
await page.getByLabel("Почему вы просите ручную оценку").fill(backendReason);
|
||||
const backendCreatePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
new URL(response.url()).pathname === "/api/v1/me/support-cases" &&
|
||||
response.request().method() === "POST",
|
||||
);
|
||||
await page.getByRole("button", { name: "Отправить запрос эксперту" }).click();
|
||||
const backendCreateResponse = await backendCreatePromise;
|
||||
expect(backendCreateResponse.status()).toBe(201);
|
||||
expect(backendCreateResponse.request().postDataJSON()).toMatchObject({
|
||||
type: "manual_assessment",
|
||||
description: backendReason,
|
||||
assessment_target: { specialization: "backend", grade: "junior" },
|
||||
});
|
||||
const backendCase = (await backendCreateResponse.json()) as SupportCaseResponse;
|
||||
expect(backendCase.type).toBe("manual_assessment");
|
||||
expect(backendCase.status).toBe("waiting_expert");
|
||||
expect(backendCase.assessment_target).toEqual({ specialization: "backend", grade: "junior" });
|
||||
expect(backendCase.rubric_version).toEqual(expect.any(Number));
|
||||
expect(backendCase.rubric_version).toBeGreaterThan(0);
|
||||
expect(backendCase.decision).toBeNull();
|
||||
expect(attemptRequests).toEqual([]);
|
||||
|
||||
const activeC3AfterPublishedManualRequest = await page.evaluate(async () => {
|
||||
const response = await fetch("/api/v1/me/consents?limit=100", { credentials: "include" });
|
||||
if (!response.ok) return null;
|
||||
const body = (await response.json()) as ConsentList;
|
||||
return body.items.some((record) => record.purpose === "c3" && record.state === "active");
|
||||
});
|
||||
expect(activeC3AfterPublishedManualRequest).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,8 @@ export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
outputDir: `${artifactsDir}/results`,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
// The browser container has two CPUs; host-based defaults oversubscribe it.
|
||||
workers: 2,
|
||||
retries: 0,
|
||||
reporter: [["list"], ["html", { outputFolder: `${artifactsDir}/report`, open: "never" }]],
|
||||
use: {
|
||||
|
||||
@@ -2,8 +2,10 @@ import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { assessmentQueryKeys } from "../../entities/assessment";
|
||||
import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent";
|
||||
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../shared/api/schemas";
|
||||
import { createQueryClient } from "../providers/query-client";
|
||||
import { routes } from "./routes";
|
||||
|
||||
@@ -20,7 +22,7 @@ async function render(path: string): Promise<string | Response> {
|
||||
const queryClient = createQueryClient();
|
||||
const scenario = path.startsWith("/employer") ? "employer" : "candidate";
|
||||
if (path.startsWith("/candidate") || path.startsWith("/employer")) {
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
|
||||
const session = {
|
||||
account: {
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
email: "person@example.test",
|
||||
@@ -39,7 +41,17 @@ async function render(path: string): Promise<string | Response> {
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
});
|
||||
} satisfies Session;
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
if (path === "/candidate/assessment") {
|
||||
queryClient.setQueryData(assessmentQueryKeys.availability(session), { specializations: [] });
|
||||
queryClient.setQueryData(assessmentQueryKeys.questionnaire(session), {
|
||||
version: 0,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (path.startsWith("/candidate/privacy")) {
|
||||
const hasMore = path.includes("history=partial");
|
||||
@@ -122,7 +134,23 @@ describe("route groups", () => {
|
||||
["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"],
|
||||
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
|
||||
["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"],
|
||||
["/candidate/assessment", "Проверка знаний", "Разделы кабинета кандидата"],
|
||||
[
|
||||
"/candidate/assessment/01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
|
||||
"Попытка проверки",
|
||||
"Разделы кабинета кандидата",
|
||||
],
|
||||
["/employer/company", "Компания", "Разделы кабинета работодателя"],
|
||||
["/employer/needs", "Потребности", "Разделы кабинета работодателя"],
|
||||
["/candidate/support/cases", "Мои обращения", "Разделы кабинета кандидата"],
|
||||
["/candidate/support/cases/new", "Обратиться в поддержку", "Разделы кабинета кандидата"],
|
||||
[
|
||||
"/candidate/support/cases/manual-assessment",
|
||||
"Запросить ручную оценку",
|
||||
"Разделы кабинета кандидата",
|
||||
],
|
||||
["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"],
|
||||
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
|
||||
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
|
||||
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
|
||||
const html = await renderHtml(path);
|
||||
@@ -183,6 +211,14 @@ describe("route groups", () => {
|
||||
});
|
||||
|
||||
describe("product readiness", () => {
|
||||
it("keeps the training run available when no full-assessment category exists", async () => {
|
||||
const html = await renderHtml("/candidate/assessment");
|
||||
|
||||
expect(html).toContain("Сначала выберите специализацию");
|
||||
expect(html).toContain("Начать демонстрацию");
|
||||
expect(html).not.toContain("Начать полную проверку");
|
||||
});
|
||||
|
||||
it("presents the root page as a scaffold, not as a working product", async () => {
|
||||
const html = await renderHtml("/");
|
||||
|
||||
@@ -226,7 +262,7 @@ describe("product readiness", () => {
|
||||
});
|
||||
|
||||
it("labels the remaining cabinet scaffolds as placeholders", async () => {
|
||||
for (const path of ["/candidate", "/employer/needs"]) {
|
||||
for (const path of ["/candidate", "/employer/candidates"]) {
|
||||
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import { redirect, type RouteObject } from "react-router-dom";
|
||||
import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment";
|
||||
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
|
||||
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
|
||||
import { CompanyPage } from "../../pages/company";
|
||||
import { ConsentsPage } from "../../pages/consents";
|
||||
import { SessionGate } from "../../entities/session";
|
||||
import { NotFoundPage } from "../../pages/not-found";
|
||||
import { NeedEditorPage } from "../../pages/need-editor";
|
||||
import { NeedListPage } from "../../pages/needs";
|
||||
import { PlaceholderPage } from "../../pages/placeholder";
|
||||
import { ProfilePage } from "../../pages/profile";
|
||||
import { QuestionnairePage } from "../../pages/questionnaire";
|
||||
import { StatusPage } from "../../pages/status";
|
||||
import {
|
||||
CreateSupportCasePage,
|
||||
ManualAssessmentPage,
|
||||
SupportCaseDetailPage,
|
||||
SupportCasesPage,
|
||||
} from "../../pages/support-cases";
|
||||
import { WelcomePage } from "../../pages/welcome";
|
||||
import { paths } from "../../shared/config";
|
||||
import { CandidateShell } from "../../widgets/candidate-shell";
|
||||
@@ -17,6 +26,7 @@ import { PublicShell } from "../../widgets/public-shell";
|
||||
import { RootLayout } from "../ui/root-layout";
|
||||
import { RouteErrorPage } from "../ui/route-error-page";
|
||||
import { CandidateHomeRoute } from "./candidate-home-route";
|
||||
import { SupportRoute } from "./support-route";
|
||||
|
||||
/**
|
||||
* Route tree with public pages and role-specific cabinets. Protected shells
|
||||
@@ -34,7 +44,7 @@ export const routes: RouteObject[] = [
|
||||
{ path: paths.login, element: <LoginPage /> },
|
||||
{ path: paths.register, element: <RegisterPage /> },
|
||||
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
|
||||
{ path: paths.support, element: <PlaceholderPage screen="support" /> },
|
||||
{ path: paths.support, element: <SupportRoute /> },
|
||||
{ path: paths.status, element: <StatusPage /> },
|
||||
{ path: "*", element: <NotFoundPage /> },
|
||||
],
|
||||
@@ -58,7 +68,11 @@ export const routes: RouteObject[] = [
|
||||
},
|
||||
{
|
||||
path: paths.candidate.assessment,
|
||||
element: <PlaceholderPage screen="candidateAssessment" />,
|
||||
element: <AssessmentPage />,
|
||||
},
|
||||
{
|
||||
path: `${paths.candidate.assessment}/:attemptId`,
|
||||
element: <AssessmentAttemptPage />,
|
||||
},
|
||||
{
|
||||
path: paths.candidate.results,
|
||||
@@ -72,6 +86,13 @@ export const routes: RouteObject[] = [
|
||||
path: paths.candidate.privacy,
|
||||
element: <ConsentsPage />,
|
||||
},
|
||||
{ path: paths.candidate.supportCases, element: <SupportCasesPage /> },
|
||||
{ path: paths.candidate.supportNew, element: <CreateSupportCasePage /> },
|
||||
{ path: paths.candidate.supportManual, element: <ManualAssessmentPage /> },
|
||||
{
|
||||
path: `${paths.candidate.supportCases}/:caseId`,
|
||||
element: <SupportCaseDetailPage />,
|
||||
},
|
||||
{
|
||||
path: "*",
|
||||
element: (
|
||||
@@ -94,7 +115,15 @@ export const routes: RouteObject[] = [
|
||||
path: paths.employer.company,
|
||||
element: <CompanyPage />,
|
||||
},
|
||||
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
|
||||
{ path: paths.employer.needs, element: <NeedListPage /> },
|
||||
{ path: `${paths.employer.needs}/new`, element: <NeedEditorPage /> },
|
||||
{ path: `${paths.employer.needs}/:needId`, element: <NeedEditorPage /> },
|
||||
{ path: paths.employer.supportCases, element: <SupportCasesPage /> },
|
||||
{ path: paths.employer.supportNew, element: <CreateSupportCasePage /> },
|
||||
{
|
||||
path: `${paths.employer.supportCases}/:caseId`,
|
||||
element: <SupportCaseDetailPage />,
|
||||
},
|
||||
{
|
||||
path: paths.employer.candidates,
|
||||
element: <PlaceholderPage screen="employerCandidates" />,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Navigate, useLocation } from "react-router-dom";
|
||||
import { parseSupportCaseContext } from "../../entities/support-case";
|
||||
import { ApiRequestError } from "../../shared/api";
|
||||
import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity";
|
||||
import { paths } from "../../shared/config";
|
||||
import { ButtonLink, ErrorState, LoadingState, Page, Section } from "../../shared/ui";
|
||||
|
||||
/** Support remains reachable before completing either onboarding flow. */
|
||||
export function SupportRoute() {
|
||||
const session = useGetCurrentSession();
|
||||
const location = useLocation();
|
||||
if (session.isPending) {
|
||||
return (
|
||||
<Page title="Поддержка">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
if (session.isError) {
|
||||
if (session.error instanceof ApiRequestError && session.error.status === 401) {
|
||||
return (
|
||||
<Page title="Поддержка" lead="Войдите, чтобы отправить обращение и следить за ответом.">
|
||||
<Section title="Ваши обращения">
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Войти и открыть поддержку
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Поддержка">
|
||||
<ErrorState
|
||||
title="Не удалось открыть поддержку"
|
||||
error={session.error}
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
const state: unknown = location.state;
|
||||
const context =
|
||||
state && typeof state === "object" && !Array.isArray(state)
|
||||
? parseSupportCaseContext((state as Record<string, unknown>).supportContext)
|
||||
: null;
|
||||
const cabinet = session.data.account.scenario === "candidate" ? paths.candidate : paths.employer;
|
||||
return (
|
||||
<Navigate
|
||||
to={context ? cabinet.supportNew : cabinet.supportCases}
|
||||
state={context ? { supportContext: context } : undefined}
|
||||
replace
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useRouteError } from "react-router-dom";
|
||||
import { ErrorState, Page } from "../../shared/ui";
|
||||
import { paths } from "../../shared/config";
|
||||
import { ErrorState, Page, TextLink } from "../../shared/ui";
|
||||
|
||||
/**
|
||||
* Last-resort boundary for errors thrown while rendering a route. It has no
|
||||
@@ -18,6 +19,7 @@ export function RouteErrorPage() {
|
||||
window.location.reload();
|
||||
}}
|
||||
/>
|
||||
<TextLink to={paths.support}>Обратиться в поддержку</TextLink>
|
||||
</Page>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useQuery, type QueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
getMyAssessmentAvailability,
|
||||
getMyAssessmentAttempt,
|
||||
getMyAssessmentResult,
|
||||
} from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate";
|
||||
import type {
|
||||
AssessmentAttempt,
|
||||
AssessmentAvailability,
|
||||
AssessmentResult,
|
||||
Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
parseAssessmentAvailabilityResponse,
|
||||
parseAssessmentAttemptResponse,
|
||||
parseAssessmentResultResponse,
|
||||
parseCandidateQuestionnaireResponse,
|
||||
} from "../model/contract-validation";
|
||||
import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session";
|
||||
|
||||
type AssessmentQueryOptions = {
|
||||
enabled?: boolean;
|
||||
queryClient: QueryClient;
|
||||
actor: Session | undefined;
|
||||
};
|
||||
|
||||
const privateQueryOptions = {
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always" as const,
|
||||
refetchOnWindowFocus: "always" as const,
|
||||
retry: false,
|
||||
};
|
||||
|
||||
export function useAssessmentAvailability({
|
||||
actor,
|
||||
enabled = true,
|
||||
queryClient,
|
||||
}: AssessmentQueryOptions) {
|
||||
return useQuery<AssessmentAvailability, Error>({
|
||||
queryKey: actor
|
||||
? assessmentQueryKeys.availability(actor)
|
||||
: [...assessmentQueryKeysPrefix, "availability"],
|
||||
enabled: Boolean(actor && enabled),
|
||||
...privateQueryOptions,
|
||||
queryFn: async ({ signal }) => {
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
const availability = await getMyAssessmentAvailability({ signal });
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
return parseAssessmentAvailabilityResponse(availability);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssessmentQuestionnaire({
|
||||
actor,
|
||||
enabled = true,
|
||||
queryClient,
|
||||
}: AssessmentQueryOptions) {
|
||||
return useQuery({
|
||||
queryKey: actor
|
||||
? assessmentQueryKeys.questionnaire(actor)
|
||||
: [...assessmentQueryKeysPrefix, "questionnaire"],
|
||||
enabled: Boolean(actor && enabled),
|
||||
...privateQueryOptions,
|
||||
queryFn: async ({ signal }) => {
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
const questionnaire = await getMyQuestionnaire({ signal });
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
return parseCandidateQuestionnaireResponse(questionnaire);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssessmentAttempt({
|
||||
actor,
|
||||
attemptId,
|
||||
enabled = true,
|
||||
queryClient,
|
||||
}: AssessmentQueryOptions & { attemptId: string }) {
|
||||
return useQuery<AssessmentAttempt, Error>({
|
||||
queryKey: actor
|
||||
? assessmentQueryKeys.attempt(actor, attemptId)
|
||||
: [...assessmentQueryKeysPrefix, "attempt", attemptId],
|
||||
enabled: Boolean(actor && attemptId && enabled),
|
||||
...privateQueryOptions,
|
||||
refetchInterval: (query) => {
|
||||
const attempt = query.state.data;
|
||||
return attempt?.practices.some((practice) => practice.status === "pending") ? 2500 : false;
|
||||
},
|
||||
queryFn: async ({ signal }) => {
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
const response = await getMyAssessmentAttempt(attemptId, { signal });
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
return parseAssessmentAttemptResponse(response);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssessmentResult({
|
||||
actor,
|
||||
attemptId,
|
||||
enabled = true,
|
||||
queryClient,
|
||||
}: AssessmentQueryOptions & { attemptId: string }) {
|
||||
return useQuery<AssessmentResult, Error>({
|
||||
queryKey: actor
|
||||
? assessmentQueryKeys.result(actor, attemptId)
|
||||
: [...assessmentQueryKeysPrefix, "result", attemptId],
|
||||
enabled: Boolean(actor && attemptId && enabled),
|
||||
...privateQueryOptions,
|
||||
queryFn: async ({ signal }) => {
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
const response = await getMyAssessmentResult(attemptId, { signal });
|
||||
assertCurrentAssessmentSession(queryClient, actor);
|
||||
return parseAssessmentResultResponse(response);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const assessmentQueryKeysPrefix = ["candidate-assessment"] as const;
|
||||
@@ -0,0 +1,29 @@
|
||||
export {
|
||||
useAssessmentAttempt,
|
||||
useAssessmentAvailability,
|
||||
useAssessmentQuestionnaire,
|
||||
useAssessmentResult,
|
||||
} from "./api/assessment-queries";
|
||||
export {
|
||||
assessmentQueryKeys,
|
||||
assessmentQueryPrefix,
|
||||
assessmentSessionMatches,
|
||||
assertCurrentAssessmentSession,
|
||||
isCurrentAssessmentSession,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
} from "./model/session";
|
||||
export { isOutcomeAmbiguous } from "./model/idempotency";
|
||||
export {
|
||||
parseAssessmentAttemptResponse,
|
||||
parseAssessmentResultResponse,
|
||||
} from "./model/contract-validation";
|
||||
export { assessmentResultSummary } from "./model/result-summary";
|
||||
export {
|
||||
availabilityLabels,
|
||||
gradeLabels,
|
||||
methodLabel,
|
||||
outcomeLabels,
|
||||
selectedSpecialization,
|
||||
specializationLabels,
|
||||
} from "./model/labels";
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import type { AssessmentAttempt } from "../../../shared/api/schemas";
|
||||
import {
|
||||
parseAssessmentAvailabilityResponse,
|
||||
parseAssessmentAttemptResponse,
|
||||
parseAssessmentResultResponse,
|
||||
parseCandidateQuestionnaireResponse,
|
||||
} from "./contract-validation";
|
||||
|
||||
const validAttempt: AssessmentAttempt = {
|
||||
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01",
|
||||
version: 2,
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "python",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
mode: "demo_basic",
|
||||
state: "in_progress",
|
||||
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
|
||||
started_at: "2026-10-08T10:00:00Z",
|
||||
expires_at: "2026-10-08T11:00:00Z",
|
||||
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
|
||||
finished_at: null,
|
||||
progress: { answered_items: 1, max_items: 2 },
|
||||
current_item: {
|
||||
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
|
||||
sequence: 2,
|
||||
prompt: "Сколько?",
|
||||
content: { format: "number", unit: null },
|
||||
},
|
||||
practices: [],
|
||||
};
|
||||
|
||||
function captureError(operation: () => unknown): unknown {
|
||||
try {
|
||||
operation();
|
||||
} catch (error: unknown) {
|
||||
return error;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
describe("assessment response contract validation", () => {
|
||||
it("accepts an empty availability and an unsaved questionnaire", () => {
|
||||
expect(parseAssessmentAvailabilityResponse({ specializations: [] })).toEqual({
|
||||
specializations: [],
|
||||
});
|
||||
expect(
|
||||
parseCandidateQuestionnaireResponse({
|
||||
version: 0,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
}),
|
||||
).toEqual({
|
||||
version: 0,
|
||||
specializations: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["availability", parseAssessmentAvailabilityResponse],
|
||||
["questionnaire", parseCandidateQuestionnaireResponse],
|
||||
] as const)("rejects an invalid %s response", (_name, parse) => {
|
||||
const error = captureError(() => parse({}));
|
||||
expect(error).toBeInstanceOf(ApiRequestError);
|
||||
expect(error).toMatchObject({ status: 200, code: invalidResponseCode });
|
||||
});
|
||||
|
||||
it("accepts a complete attempt payload", () => {
|
||||
expect(parseAssessmentAttemptResponse(validAttempt)).toEqual(validAttempt);
|
||||
});
|
||||
|
||||
it.each([{}, { id: validAttempt.id, version: validAttempt.version }])(
|
||||
"rejects an incomplete successful attempt payload",
|
||||
(value) => {
|
||||
const error = captureError(() => parseAssessmentAttemptResponse(value, 201));
|
||||
expect(error).toBeInstanceOf(ApiRequestError);
|
||||
expect(error).toMatchObject({ status: 201, code: invalidResponseCode });
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects an incomplete successful result payload", () => {
|
||||
expect(() => parseAssessmentResultResponse({})).toThrowError(
|
||||
expect.objectContaining({ status: 200, code: invalidResponseCode }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import {
|
||||
AssessmentAttempt as assessmentAttemptSchema,
|
||||
AssessmentAvailability as assessmentAvailabilitySchema,
|
||||
AssessmentResult as assessmentResultSchema,
|
||||
CandidateQuestionnaire as candidateQuestionnaireSchema,
|
||||
type AssessmentAttempt,
|
||||
type AssessmentAvailability,
|
||||
type AssessmentResult,
|
||||
type CandidateQuestionnaire,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
function invalidAssessmentResponse(status: number): ApiRequestError {
|
||||
return new ApiRequestError({
|
||||
status,
|
||||
code: invalidResponseCode,
|
||||
title: "The response does not match the API contract.",
|
||||
});
|
||||
}
|
||||
|
||||
export function parseAssessmentAttemptResponse(value: unknown, status = 200): AssessmentAttempt {
|
||||
const parsed = assessmentAttemptSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidAssessmentResponse(status);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export function parseAssessmentAvailabilityResponse(
|
||||
value: unknown,
|
||||
status = 200,
|
||||
): AssessmentAvailability {
|
||||
const parsed = assessmentAvailabilitySchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidAssessmentResponse(status);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export function parseCandidateQuestionnaireResponse(
|
||||
value: unknown,
|
||||
status = 200,
|
||||
): CandidateQuestionnaire {
|
||||
const parsed = candidateQuestionnaireSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidAssessmentResponse(status);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export function parseAssessmentResultResponse(value: unknown, status = 200): AssessmentResult {
|
||||
const parsed = assessmentResultSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidAssessmentResponse(status);
|
||||
return parsed.data;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ApiRequestError,
|
||||
invalidResponseCode,
|
||||
networkErrorCode,
|
||||
type ApiErrorCode,
|
||||
} from "../../../shared/api";
|
||||
import { isOutcomeAmbiguous } from "./idempotency";
|
||||
|
||||
const ambiguousOutcomes: ReadonlyArray<readonly [number, ApiErrorCode]> = [
|
||||
[0, networkErrorCode],
|
||||
[200, invalidResponseCode],
|
||||
[429, "rate_limited"],
|
||||
[500, "internal"],
|
||||
];
|
||||
|
||||
describe("assessment command retry safety", () => {
|
||||
it.each(ambiguousOutcomes)(
|
||||
"keeps the idempotency key when outcome status is %s",
|
||||
(status, code) => {
|
||||
expect(
|
||||
isOutcomeAmbiguous(new ApiRequestError({ status, code, title: "Request failed." })),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([400, 401, 403, 404, 409, 412, 422])(
|
||||
"does not classify deterministic HTTP %s as an ambiguous outcome",
|
||||
(status) => {
|
||||
expect(
|
||||
isOutcomeAmbiguous(
|
||||
new ApiRequestError({ status, code: "validation_failed", title: "Rejected." }),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat local validation errors as a request outcome", () => {
|
||||
expect(isOutcomeAmbiguous(new Error("Invalid form state."))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
|
||||
export function isOutcomeAmbiguous(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 0 ||
|
||||
error.status >= 500 ||
|
||||
error.status === 429 ||
|
||||
error.code === invalidResponseCode)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type {
|
||||
AssessmentAvailability,
|
||||
AssessmentGradeAvailabilityStatus,
|
||||
AssessmentMode,
|
||||
AssessmentOutcome,
|
||||
AssessmentSpecializationAvailability,
|
||||
GradeCode,
|
||||
SpecializationCode,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export const specializationLabels: Readonly<Record<SpecializationCode, string>> = {
|
||||
backend: "Backend",
|
||||
frontend: "Frontend",
|
||||
mobile: "Мобильная разработка",
|
||||
network_engineer: "Сетевые технологии",
|
||||
devops_sre: "DevOps и SRE",
|
||||
data_analyst: "Аналитика данных",
|
||||
ds_ml: "Data Science и ML",
|
||||
information_security: "Информационная безопасность",
|
||||
qa: "Тестирование",
|
||||
};
|
||||
|
||||
export const gradeLabels: Readonly<Record<GradeCode, string>> = {
|
||||
intern: "Стажер",
|
||||
junior: "Junior",
|
||||
middle: "Middle",
|
||||
senior: "Senior",
|
||||
};
|
||||
|
||||
export const availabilityLabels: Readonly<Record<AssessmentGradeAvailabilityStatus, string>> = {
|
||||
available: "Можно начать",
|
||||
active_attempt: "Есть незавершенная попытка",
|
||||
cooldown: "Пока недоступно",
|
||||
insufficient_bank: "Проверка еще не подготовлена",
|
||||
};
|
||||
|
||||
export const outcomeLabels: Readonly<Record<AssessmentOutcome, string>> = {
|
||||
confirmed: "Уровень подтвержден",
|
||||
not_confirmed: "Уровень пока не подтвержден",
|
||||
not_determined: "Результат не определен",
|
||||
};
|
||||
|
||||
export function methodLabel(mode: AssessmentMode): string {
|
||||
switch (mode) {
|
||||
case "adaptive":
|
||||
return "Адаптивная проверка";
|
||||
case "demo_basic":
|
||||
return "Базовая проверка по фиксированному набору заданий";
|
||||
case "demo_express":
|
||||
return "Демонстрационный экспресс-запуск";
|
||||
}
|
||||
}
|
||||
|
||||
export function selectedSpecialization(
|
||||
availability: AssessmentAvailability,
|
||||
code: SpecializationCode | undefined,
|
||||
): AssessmentSpecializationAvailability | undefined {
|
||||
return availability.specializations.find((item) => item.specialization === code);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { QueryClient, QueryKey, QueryState } from "@tanstack/react-query";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
|
||||
type SessionSnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
|
||||
|
||||
export function assessmentSessionMatches(
|
||||
snapshot: SessionSnapshot | undefined,
|
||||
actor: Session | undefined,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
snapshot?.status === "success" &&
|
||||
actor &&
|
||||
snapshot.data?.account.id === actor.account.id &&
|
||||
snapshot.data.csrf_token === actor.csrf_token &&
|
||||
actor.account.scenario === "candidate",
|
||||
);
|
||||
}
|
||||
|
||||
export function isCurrentAssessmentSession(
|
||||
queryClient: QueryClient,
|
||||
actor: Session | undefined,
|
||||
): boolean {
|
||||
return assessmentSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertCurrentAssessmentSession(
|
||||
queryClient: QueryClient,
|
||||
actor: Session | undefined,
|
||||
): asserts actor is Session {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) {
|
||||
throw new Error("The candidate session changed during the assessment request.");
|
||||
}
|
||||
}
|
||||
|
||||
export const assessmentQueryPrefix = ["candidate-assessment"] as const;
|
||||
|
||||
export const assessmentQueryKeys = {
|
||||
availability: (actor: Session) =>
|
||||
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "availability"] as const,
|
||||
questionnaire: (actor: Session) =>
|
||||
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "questionnaire"] as const,
|
||||
attempt: (actor: Session, attemptId: string) =>
|
||||
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "attempt", attemptId] as const,
|
||||
result: (actor: Session, attemptId: string) =>
|
||||
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result", attemptId] as const,
|
||||
};
|
||||
|
||||
export function removeAssessmentQueries(queryClient: QueryClient): void {
|
||||
queryClient.removeQueries({ queryKey: assessmentQueryPrefix });
|
||||
}
|
||||
|
||||
export function removeAssessmentQueriesForSessionChange(
|
||||
queryClient: QueryClient,
|
||||
previousKey?: QueryKey,
|
||||
): void {
|
||||
if (previousKey) {
|
||||
queryClient.removeQueries({ queryKey: previousKey });
|
||||
return;
|
||||
}
|
||||
removeAssessmentQueries(queryClient);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization";
|
||||
import { needQueryKeys } from "../model/query-keys";
|
||||
import {
|
||||
removeAllNeedQueries,
|
||||
removeNeedQueriesForOrganization,
|
||||
removeNeedQueriesForSessionChange,
|
||||
} from "./cache";
|
||||
|
||||
const accountId = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4";
|
||||
const organizationId = "f4866808-70dc-4cbe-b98e-05009c8171d4";
|
||||
const otherOrganizationId = "e0102126-0c16-49f8-8e81-a82949710454";
|
||||
const needId = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91";
|
||||
|
||||
describe("need query cache cleanup", () => {
|
||||
it("removes every list and detail for a denied organization only", () => {
|
||||
const client = new QueryClient();
|
||||
const deniedListKey = needQueryKeys.list(accountId, organizationId);
|
||||
const deniedDetailKey = needQueryKeys.detail(accountId, organizationId, needId);
|
||||
const otherListKey = needQueryKeys.list(accountId, otherOrganizationId);
|
||||
|
||||
client.setQueryData(deniedListKey, { items: [] });
|
||||
client.setQueryData(deniedDetailKey, { id: needId });
|
||||
client.setQueryData(otherListKey, { items: [] });
|
||||
|
||||
removeNeedQueriesForOrganization(client, organizationId);
|
||||
|
||||
expect(client.getQueryData(deniedListKey)).toBeUndefined();
|
||||
expect(client.getQueryData(deniedDetailKey)).toBeUndefined();
|
||||
expect(client.getQueryData(otherListKey)).toEqual({ items: [] });
|
||||
});
|
||||
|
||||
it("clears need and owner-directory caches when the session changes", () => {
|
||||
const client = new QueryClient();
|
||||
const directoryKey = getListMyOrganizationsQueryKey({ limit: 100 });
|
||||
const listKey = needQueryKeys.list(accountId, organizationId);
|
||||
const detailKey = needQueryKeys.detail(accountId, organizationId, needId);
|
||||
|
||||
client.setQueryData(directoryKey, { items: [] });
|
||||
client.setQueryData(listKey, { items: [] });
|
||||
client.setQueryData(detailKey, { id: needId });
|
||||
|
||||
removeNeedQueriesForSessionChange(client);
|
||||
|
||||
expect(client.getQueryData(directoryKey)).toBeUndefined();
|
||||
expect(client.getQueryData(listKey)).toBeUndefined();
|
||||
expect(client.getQueryData(detailKey)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears private need data if the owner directory loses authorization", () => {
|
||||
const client = new QueryClient();
|
||||
const firstNeedKey = needQueryKeys.list(accountId, organizationId);
|
||||
const secondNeedKey = needQueryKeys.detail(accountId, otherOrganizationId, needId);
|
||||
|
||||
client.setQueryData(firstNeedKey, { items: [] });
|
||||
client.setQueryData(secondNeedKey, { id: needId });
|
||||
|
||||
removeAllNeedQueries(client);
|
||||
|
||||
expect(client.getQueryData(firstNeedKey)).toBeUndefined();
|
||||
expect(client.getQueryData(secondNeedKey)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
/** Removes every private need list/detail cache for one organization. */
|
||||
export function removeNeedQueriesForOrganization(
|
||||
queryClient: QueryClient,
|
||||
organizationId: string,
|
||||
): void {
|
||||
const prefix = `/api/v1/organizations/${organizationId}/needs`;
|
||||
void queryClient.removeQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey[0];
|
||||
return typeof key === "string" && (key === prefix || key.startsWith(`${prefix}/`));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Removes every private need query when the owner directory cannot be trusted. */
|
||||
export function removeAllNeedQueries(queryClient: QueryClient): void {
|
||||
void queryClient.removeQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey[0];
|
||||
return (
|
||||
typeof key === "string" &&
|
||||
key.startsWith("/api/v1/organizations/") &&
|
||||
key.includes("/needs")
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Clears need and owner-directory caches when a session identity changes. */
|
||||
export function removeNeedQueriesForSessionChange(queryClient: QueryClient): void {
|
||||
void queryClient.removeQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey[0];
|
||||
return typeof key === "string" && key === "/api/v1/me/organizations";
|
||||
},
|
||||
});
|
||||
removeAllNeedQueries(queryClient);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { listMyOrganizations } from "../../../shared/api/endpoints/organization/organization";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { needDirectoryPageSize, needQueryKeys } from "../model/query-keys";
|
||||
import { isNeedSessionCurrent } from "./session";
|
||||
|
||||
/** Reads the signed-in account's organization directory for need context checks. */
|
||||
export function useNeedOrganizationDirectory(session: Session | undefined, enabled: boolean) {
|
||||
const queryClient = useQueryClient();
|
||||
const accountId = session?.account.id;
|
||||
const scopedAccountId = accountId ?? "no-session";
|
||||
const csrfToken = session?.csrf_token;
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: needQueryKeys.directory(scopedAccountId),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (!isNeedSessionCurrent(queryClient, session))
|
||||
throw new Error("The session changed before the directory request.");
|
||||
const result = await listMyOrganizations(
|
||||
{ limit: needDirectoryPageSize, ...(pageParam ? { cursor: pageParam } : {}) },
|
||||
{ signal },
|
||||
);
|
||||
if (!isNeedSessionCurrent(queryClient, session))
|
||||
throw new Error("The session changed during the directory request.");
|
||||
return result;
|
||||
},
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: enabled && accountId !== undefined && csrfToken !== undefined,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { isNeedSessionCurrent } from "./session";
|
||||
|
||||
const session: Session = {
|
||||
account: {
|
||||
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
|
||||
email: "owner@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-06T09:00:00Z",
|
||||
},
|
||||
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
|
||||
};
|
||||
|
||||
describe("isNeedSessionCurrent", () => {
|
||||
it("matches both the account and current CSRF token", () => {
|
||||
const client = new QueryClient();
|
||||
client.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
|
||||
expect(isNeedSessionCurrent(client, session)).toBe(true);
|
||||
expect(isNeedSessionCurrent(client, { ...session, csrf_token: "another-token" })).toBe(false);
|
||||
expect(
|
||||
isNeedSessionCurrent(client, {
|
||||
...session,
|
||||
account: { ...session.account, id: "36acbba3-d786-4c3a-95b2-4c374ab3206e" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(isNeedSessionCurrent(client, undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
|
||||
/** Checks that a response still belongs to the active account and CSRF session. */
|
||||
export function isNeedSessionCurrent(
|
||||
queryClient: QueryClient,
|
||||
session: Session | undefined,
|
||||
): boolean {
|
||||
if (!session?.csrf_token) return false;
|
||||
const state = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
|
||||
return Boolean(
|
||||
state?.status === "success" &&
|
||||
state.data?.account.id === session.account.id &&
|
||||
state.data.csrf_token === session.csrf_token,
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,13 @@
|
||||
// toUpdateBody with the generated mutations. After a successful update the
|
||||
// returned Need is the new baseline of the draft.
|
||||
|
||||
export { useNeedOrganizationDirectory } from "./api/organization-directory";
|
||||
export {
|
||||
removeAllNeedQueries,
|
||||
removeNeedQueriesForOrganization,
|
||||
removeNeedQueriesForSessionChange,
|
||||
} from "./api/cache";
|
||||
export { isNeedSessionCurrent } from "./api/session";
|
||||
export {
|
||||
addSkill,
|
||||
addTask,
|
||||
@@ -23,6 +30,9 @@ export {
|
||||
setFieldValue,
|
||||
} from "./model/edit";
|
||||
export { fromTransport, NeedTransportError } from "./model/from-transport";
|
||||
export { rebaseNeedDraft } from "./model/rebase";
|
||||
export { activeNeedOrganizations, type NeedOrganization } from "./model/owner-organizations";
|
||||
export { needDirectoryPageSize, needListPageSize, needQueryKeys } from "./model/query-keys";
|
||||
export {
|
||||
changedNeedFields,
|
||||
isNeedFormDirty,
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
setFieldValue,
|
||||
} from "./edit";
|
||||
import { fromTransport, NeedTransportError } from "./from-transport";
|
||||
import { rebaseNeedDraft } from "./rebase";
|
||||
import {
|
||||
changedNeedFields,
|
||||
isNeedFormDirty,
|
||||
@@ -410,6 +411,45 @@ describe("toUpdateBody", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("rebaseNeedDraft", () => {
|
||||
it("keeps local edits and adopts untouched fields from the latest version", () => {
|
||||
const baseline = fromTransport(extractedNeed);
|
||||
let draft = setFieldValue(baseline, "grade", "middle");
|
||||
draft = removeSkill(draft, "requiredSkills", skillIndex(draft, "requiredSkills", "PostgreSQL"));
|
||||
const latest = Need.parse({
|
||||
...extractedNeed,
|
||||
version: 2,
|
||||
title: "Backend for the payments team, updated",
|
||||
requirements: {
|
||||
...extractedNeed.requirements,
|
||||
domain: {
|
||||
status: "confirmed",
|
||||
value: "payments",
|
||||
source: {
|
||||
origin: "manual",
|
||||
quote: null,
|
||||
extracted_in_version: null,
|
||||
extraction_version: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const rebased = rebaseNeedDraft(extractedNeed, draft, latest);
|
||||
const body = toUpdateBody(latest, rebased);
|
||||
|
||||
expect(rebased.title).toBe(latest.title);
|
||||
expect(rebased.domain).toMatchObject({ status: "confirmed", value: "payments" });
|
||||
expect(rebased.grade).toEqual({ status: "confirmed", value: "middle", source: null });
|
||||
expect(rebased.requiredSkills.map((skill) => skill.name)).not.toContain("PostgreSQL");
|
||||
expect(body.expected_version).toBe(2);
|
||||
expect(body.title).toBeUndefined();
|
||||
expect(body.domain).toBeUndefined();
|
||||
expect(body.grade).toEqual({ value: "middle", status: "confirmed" });
|
||||
expect(body.required_skills?.map((skill) => skill.name)).not.toContain("PostgreSQL");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCreateBody", () => {
|
||||
function manualDraft(): NeedFormValues {
|
||||
let form: NeedFormValues = { ...emptyNeedForm(), title: createManual.title };
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { MyOrganizationList } from "../../../shared/api/schemas";
|
||||
import { activeNeedOrganizations } from "./owner-organizations";
|
||||
|
||||
function organization(role: "owner" | "recruiter", state: "active" | "removed", id: string) {
|
||||
return {
|
||||
organization: { id, name: `Company ${id}`, verification_level: "e0" },
|
||||
membership: {
|
||||
organization_id: id,
|
||||
role,
|
||||
state,
|
||||
joined_at: "2026-09-01T00:00:00Z",
|
||||
},
|
||||
} satisfies MyOrganizationList["items"][number];
|
||||
}
|
||||
|
||||
describe("activeNeedOrganizations", () => {
|
||||
it("keeps only active owner memberships across loaded pages", () => {
|
||||
const pages: MyOrganizationList[] = [
|
||||
{
|
||||
items: [
|
||||
organization("owner", "active", "00000000-0000-4000-8000-000000000001"),
|
||||
organization("recruiter", "active", "00000000-0000-4000-8000-000000000002"),
|
||||
],
|
||||
page: { has_more: true, next_cursor: "next" },
|
||||
},
|
||||
{
|
||||
items: [organization("owner", "removed", "00000000-0000-4000-8000-000000000003")],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
},
|
||||
];
|
||||
|
||||
expect(activeNeedOrganizations(pages).map((item) => item.organization.id)).toEqual([
|
||||
"00000000-0000-4000-8000-000000000001",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { MyOrganizationList } from "../../../shared/api/schemas";
|
||||
|
||||
export type NeedOrganization = MyOrganizationList["items"][number];
|
||||
|
||||
/** Returns only active owner contexts; other active roles grant no need access. */
|
||||
export function activeNeedOrganizations(pages: readonly MyOrganizationList[]): NeedOrganization[] {
|
||||
return pages.flatMap((page) =>
|
||||
page.items.filter(
|
||||
(item) => item.membership.role === "owner" && item.membership.state === "active",
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { needQueryKeys } from "./query-keys";
|
||||
|
||||
const firstAccount = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4";
|
||||
const secondAccount = "36acbba3-d786-4c3a-95b2-4c374ab3206e";
|
||||
const firstOrganization = "f4866808-70dc-4cbe-b98e-05009c8171d4";
|
||||
const secondOrganization = "e0102126-0c16-49f8-8e81-a82949710454";
|
||||
const firstNeed = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91";
|
||||
const secondNeed = "ae85244a-a0c9-432d-a863-c99f63bb2677";
|
||||
|
||||
describe("need query keys", () => {
|
||||
it("separates directory and need data by the active account", () => {
|
||||
expect(needQueryKeys.directory(firstAccount)).not.toEqual(
|
||||
needQueryKeys.directory(secondAccount),
|
||||
);
|
||||
expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual(
|
||||
needQueryKeys.list(secondAccount, firstOrganization),
|
||||
);
|
||||
});
|
||||
|
||||
it("separates organization list and need detail contexts", () => {
|
||||
expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual(
|
||||
needQueryKeys.list(firstAccount, secondOrganization),
|
||||
);
|
||||
expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual(
|
||||
needQueryKeys.detail(firstAccount, firstOrganization, secondNeed),
|
||||
);
|
||||
expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual(
|
||||
needQueryKeys.detail(firstAccount, secondOrganization, firstNeed),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
getGetOrganizationNeedQueryKey,
|
||||
getListOrganizationNeedsQueryKey,
|
||||
} from "../../../shared/api/endpoints/need/need";
|
||||
import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization";
|
||||
|
||||
export const needDirectoryPageSize = 100;
|
||||
export const needListPageSize = 20;
|
||||
|
||||
/** Need data stays separate for each signed-in account and organization. */
|
||||
export const needQueryKeys = {
|
||||
directory: (accountId: string) =>
|
||||
[...getListMyOrganizationsQueryKey({ limit: needDirectoryPageSize }), accountId] as const,
|
||||
list: (accountId: string, organizationId: string) =>
|
||||
[
|
||||
...getListOrganizationNeedsQueryKey(organizationId, { limit: needListPageSize }),
|
||||
accountId,
|
||||
organizationId,
|
||||
] as const,
|
||||
detail: (accountId: string, organizationId: string, needId: string) =>
|
||||
[...getGetOrganizationNeedQueryKey(organizationId, needId), accountId, organizationId] as const,
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Need } from "../../../shared/api/schemas";
|
||||
import { changedNeedFields } from "./to-transport";
|
||||
import { fromTransport } from "./from-transport";
|
||||
import type { NeedFormField, NeedFormValues } from "./types";
|
||||
|
||||
function carryDraftField<K extends NeedFormField>(
|
||||
target: NeedFormValues,
|
||||
source: NeedFormValues,
|
||||
field: K,
|
||||
): NeedFormValues {
|
||||
return { ...target, [field]: source[field] };
|
||||
}
|
||||
|
||||
/** Reapplies only locally changed fields over a newly loaded server version. */
|
||||
export function rebaseNeedDraft(
|
||||
original: Need,
|
||||
draft: NeedFormValues,
|
||||
latest: Need,
|
||||
): NeedFormValues {
|
||||
const changedFields = new Set(changedNeedFields(original, draft));
|
||||
return (Object.keys(draft) as NeedFormField[]).reduce((rebased, field) => {
|
||||
if (!changedFields.has(field)) return rebased;
|
||||
return carryDraftField(rebased, draft, field);
|
||||
}, fromTransport(latest));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export { createSupportCaseIdempotencyKey, getSupportCaseIdempotencyKey } from "./model/idempotency";
|
||||
export type { SupportCaseKeyBinding } from "./model/idempotency";
|
||||
export { parseSupportCaseContext, supportCaseContextLabel } from "./model/context";
|
||||
export { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./model/query-keys";
|
||||
export { queryClientHasSupportActor, supportSessionMatches } from "./model/session-guard";
|
||||
export {
|
||||
isSupportSessionAccessError,
|
||||
supportCaseCreateFailureMessage,
|
||||
supportCasePathFor,
|
||||
} from "./model/submission";
|
||||
export {
|
||||
formatSupportDate,
|
||||
supportCaseActorLabels,
|
||||
supportCaseEventKindLabels,
|
||||
supportCaseStatusLabels,
|
||||
supportCaseTypeLabels,
|
||||
supportTargetDescription,
|
||||
} from "./model/presentation";
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseSupportCaseContext, supportCaseContextLabel } from "./context";
|
||||
|
||||
const attempt = { type: "assessment_attempt", id: "4c0ce905-a668-4f5d-961b-dc90fc4b684d" };
|
||||
|
||||
describe("support case context", () => {
|
||||
it("accepts only the allowlisted object kind and UUID from router state", () => {
|
||||
expect(parseSupportCaseContext(attempt)).toEqual(attempt);
|
||||
expect(parseSupportCaseContext({ ...attempt, extra: "ignored" })).toEqual(attempt);
|
||||
expect(parseSupportCaseContext({ type: "profile", id: attempt.id })).toBeNull();
|
||||
expect(parseSupportCaseContext({ ...attempt, id: "not-a-uuid" })).toBeNull();
|
||||
expect(parseSupportCaseContext(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("uses a descriptive label without showing the reference identifier", () => {
|
||||
const context = parseSupportCaseContext(attempt);
|
||||
if (!context) throw new Error("Expected a valid context");
|
||||
expect(supportCaseContextLabel(context)).toBe("попыткой оценки");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { SupportCaseObjectReference } from "../../../shared/api/schemas";
|
||||
|
||||
const allowedObjectTypes = new Set<SupportCaseObjectReference["type"]>([
|
||||
"assessment_attempt",
|
||||
"organization",
|
||||
"invitation",
|
||||
"support_case",
|
||||
]);
|
||||
|
||||
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function parseSupportCaseContext(value: unknown): SupportCaseObjectReference | null {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
if (
|
||||
typeof record.type !== "string" ||
|
||||
!allowedObjectTypes.has(record.type as SupportCaseObjectReference["type"]) ||
|
||||
typeof record.id !== "string" ||
|
||||
!uuidPattern.test(record.id)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { type: record.type as SupportCaseObjectReference["type"], id: record.id };
|
||||
}
|
||||
|
||||
export function supportCaseContextLabel(context: SupportCaseObjectReference): string {
|
||||
switch (context.type) {
|
||||
case "assessment_attempt":
|
||||
return "попыткой оценки";
|
||||
case "organization":
|
||||
return "компанией";
|
||||
case "invitation":
|
||||
return "приглашением";
|
||||
case "support_case":
|
||||
return "другим обращением";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { SupportCaseCreate } from "../../../shared/api/schemas";
|
||||
import { getSupportCaseIdempotencyKey } from "./idempotency";
|
||||
|
||||
const body: SupportCaseCreate = { type: "support", description: "Нужна помощь" };
|
||||
|
||||
describe("support case idempotency key", () => {
|
||||
it("keeps a key for an identical retry", () => {
|
||||
const createKey = vi.fn(() => "case-key-1");
|
||||
const first = getSupportCaseIdempotencyKey(body, null, createKey);
|
||||
const retry = getSupportCaseIdempotencyKey({ ...body }, first, createKey);
|
||||
|
||||
expect(retry).toBe(first);
|
||||
expect(retry.key).toBe("case-key-1");
|
||||
expect(createKey).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rotates the key when the request body changes", () => {
|
||||
const createKey = vi.fn().mockReturnValueOnce("case-key-1").mockReturnValueOnce("case-key-2");
|
||||
const first = getSupportCaseIdempotencyKey(body, null, createKey);
|
||||
const changed = getSupportCaseIdempotencyKey(
|
||||
{ ...body, description: "Нужна другая помощь" },
|
||||
first,
|
||||
createKey,
|
||||
);
|
||||
|
||||
expect(changed.key).toBe("case-key-2");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { SupportCaseCreate } from "../../../shared/api/schemas";
|
||||
|
||||
export type SupportCaseKeyBinding = { body: string; key: string };
|
||||
|
||||
export function getSupportCaseIdempotencyKey(
|
||||
body: SupportCaseCreate,
|
||||
previous: SupportCaseKeyBinding | null,
|
||||
createKey: () => string,
|
||||
): SupportCaseKeyBinding {
|
||||
const serialized = JSON.stringify(body);
|
||||
if (previous?.body === serialized) return previous;
|
||||
return { body: serialized, key: createKey() };
|
||||
}
|
||||
|
||||
export function createSupportCaseIdempotencyKey(): string {
|
||||
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
|
||||
throw new Error("Secure random key generation is unavailable.");
|
||||
}
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { supportCaseStatusLabels, supportTargetDescription } from "./presentation";
|
||||
|
||||
describe("support case presentation", () => {
|
||||
it("describes operational goals without presenting them as legal deadlines", () => {
|
||||
expect(
|
||||
supportTargetDescription({
|
||||
kind: "operational_goal",
|
||||
business_days: 5,
|
||||
due_at: "2026-10-13T09:00:00Z",
|
||||
answered_at: null,
|
||||
late: false,
|
||||
policy_version: 2,
|
||||
}),
|
||||
).toMatch(/операционная цель, не юридический срок/);
|
||||
});
|
||||
|
||||
it("labels manual assessment as waiting for an expert", () => {
|
||||
expect(supportCaseStatusLabels.waiting_expert).toBe("Ожидает эксперта");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type {
|
||||
SupportCaseActorKind,
|
||||
SupportCaseEventKind,
|
||||
SupportCaseStatus,
|
||||
SupportCaseType,
|
||||
SupportResponseTarget,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export const supportCaseTypeLabels: Readonly<Record<SupportCaseType, string>> = {
|
||||
support: "Вопрос в поддержку",
|
||||
complaint: "Жалоба",
|
||||
grade_appeal: "Апелляция по оценке",
|
||||
anticheat_appeal: "Апелляция по проверке безопасности",
|
||||
manual_assessment: "Ручная оценка",
|
||||
};
|
||||
|
||||
export const supportCaseStatusLabels: Readonly<Record<SupportCaseStatus, string>> = {
|
||||
submitted: "Принято",
|
||||
in_review: "Рассматривается",
|
||||
waiting_for_user: "Нужен ваш ответ",
|
||||
waiting_expert: "Ожидает эксперта",
|
||||
resolved: "Решено",
|
||||
closed: "Закрыто",
|
||||
};
|
||||
|
||||
export const supportCaseEventKindLabels: Readonly<Record<SupportCaseEventKind, string>> = {
|
||||
created: "Обращение создано",
|
||||
status_changed: "Статус изменен",
|
||||
reply: "Ответ поддержки",
|
||||
decision: "Решение",
|
||||
};
|
||||
|
||||
export const supportCaseActorLabels: Readonly<Record<SupportCaseActorKind, string>> = {
|
||||
user: "Вы",
|
||||
support: "Поддержка или эксперт",
|
||||
system: "Система",
|
||||
};
|
||||
|
||||
export function formatSupportDate(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.valueOf())) return value;
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
export function supportTargetDescription(target: SupportResponseTarget): string {
|
||||
const targetDate = formatSupportDate(target.due_at);
|
||||
const period = `${target.business_days} ${businessDayLabel(target.business_days)}`;
|
||||
if (target.answered_at) {
|
||||
return `Первый ответ получен ${formatSupportDate(target.answered_at)}. Целевой период был ${period}.`;
|
||||
}
|
||||
if (target.late) {
|
||||
return `Ориентир команды - до ${targetDate}; целевой период ${period} уже прошел.`;
|
||||
}
|
||||
return `Ориентир команды - до ${targetDate}, в течение ${period}. Это операционная цель, не юридический срок.`;
|
||||
}
|
||||
|
||||
function businessDayLabel(value: number): string {
|
||||
const remainder = value % 10;
|
||||
const hundredRemainder = value % 100;
|
||||
if (remainder === 1 && hundredRemainder !== 11) return "рабочий день";
|
||||
if (remainder >= 2 && remainder <= 4 && (hundredRemainder < 12 || hundredRemainder > 14)) {
|
||||
return "рабочих дня";
|
||||
}
|
||||
return "рабочих дней";
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./query-keys";
|
||||
|
||||
describe("support case query keys", () => {
|
||||
it("separates private lists and details by account", () => {
|
||||
expect(supportCaseListQueryKey("account-a")).not.toEqual(supportCaseListQueryKey("account-b"));
|
||||
expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual(
|
||||
supportCaseDetailQueryKey("account-b", "case-1"),
|
||||
);
|
||||
});
|
||||
|
||||
it("separates case details within the same account", () => {
|
||||
expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual(
|
||||
supportCaseDetailQueryKey("account-a", "case-2"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export function supportCaseListQueryKey(accountId: string) {
|
||||
return ["account", accountId, "support-cases", "list"] as const;
|
||||
}
|
||||
|
||||
export function supportCaseDetailQueryKey(accountId: string, caseId: string) {
|
||||
return ["account", accountId, "support-cases", "detail", caseId] as const;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { queryClientHasSupportActor, supportSessionMatches } from "./session-guard";
|
||||
|
||||
const session: Session = {
|
||||
account: {
|
||||
id: "22b209a8-8715-4ad5-a9b0-d93a18fc70a4",
|
||||
email: "candidate@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "a".repeat(32),
|
||||
};
|
||||
|
||||
const otherSession: Session = {
|
||||
...session,
|
||||
account: {
|
||||
...session.account,
|
||||
id: "36acbba3-d786-4c3a-95b2-4c374ab3206e",
|
||||
},
|
||||
csrf_token: "b".repeat(32),
|
||||
};
|
||||
|
||||
describe("support session guard", () => {
|
||||
it("accepts the same account during a background refresh", () => {
|
||||
const state = {
|
||||
data: session,
|
||||
status: "success",
|
||||
fetchStatus: "fetching",
|
||||
isInvalidated: true,
|
||||
} as const;
|
||||
|
||||
expect(supportSessionMatches(state, session)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects cached session data once the session query errors", () => {
|
||||
expect(supportSessionMatches({ data: session, status: "error" }, session)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects another account and a rotated CSRF token", () => {
|
||||
expect(supportSessionMatches({ data: otherSession, status: "success" }, session)).toBe(false);
|
||||
expect(
|
||||
supportSessionMatches(
|
||||
{ data: { ...session, csrf_token: "c".repeat(32) }, status: "success" },
|
||||
session,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reads the live session query state before allowing a callback to write", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const sessionKey = ["/api/v1/identity/sessions/current"];
|
||||
queryClient.setQueryData(sessionKey, session);
|
||||
|
||||
expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(true);
|
||||
|
||||
queryClient.setQueryData(sessionKey, otherSession);
|
||||
expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { QueryClient, QueryState } from "@tanstack/react-query";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
|
||||
type SessionSnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
|
||||
|
||||
export function supportSessionMatches(
|
||||
snapshot: SessionSnapshot | undefined,
|
||||
actor: Session,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
snapshot &&
|
||||
snapshot.status === "success" &&
|
||||
snapshot.data &&
|
||||
snapshot.data.account.id === actor.account.id &&
|
||||
snapshot.data.csrf_token === actor.csrf_token,
|
||||
);
|
||||
}
|
||||
|
||||
export function queryClientHasSupportActor(
|
||||
queryClient: QueryClient,
|
||||
sessionQueryKey: readonly unknown[],
|
||||
actor: Session,
|
||||
): boolean {
|
||||
return supportSessionMatches(queryClient.getQueryState<Session>(sessionQueryKey), actor);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { supportCaseCreateFailureMessage } from "./submission";
|
||||
|
||||
describe("support case submission feedback", () => {
|
||||
it("shows the server retry interval without retrying automatically", () => {
|
||||
const message = supportCaseCreateFailureMessage(
|
||||
new ApiRequestError({
|
||||
status: 429,
|
||||
code: "rate_limited",
|
||||
title: "Rate limited",
|
||||
retryAfterSeconds: 15,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(message).toContain("Повторите вручную через 15 сек.");
|
||||
});
|
||||
|
||||
it("handles missing retry intervals and idempotency conflicts", () => {
|
||||
expect(
|
||||
supportCaseCreateFailureMessage(
|
||||
new ApiRequestError({ status: 429, code: "rate_limited", title: "Rate limited" }),
|
||||
),
|
||||
).toContain("Попробуйте отправить обращение позже.");
|
||||
expect(
|
||||
supportCaseCreateFailureMessage(
|
||||
new ApiRequestError({
|
||||
status: 422,
|
||||
code: "idempotency_key_reused",
|
||||
title: "Key reused",
|
||||
}),
|
||||
),
|
||||
).toContain("Отправьте форму еще раз.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
|
||||
export function isSupportSessionAccessError(error: unknown): boolean {
|
||||
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
|
||||
}
|
||||
|
||||
export function supportCasePathFor(session: Session, caseId: string): string {
|
||||
return session.account.scenario === "candidate"
|
||||
? paths.candidate.supportCase(caseId)
|
||||
: paths.employer.supportCase(caseId);
|
||||
}
|
||||
|
||||
export function supportCaseCreateFailureMessage(error: unknown): string {
|
||||
if (!(error instanceof ApiRequestError)) {
|
||||
return "Не удалось отправить обращение. Проверьте соединение и повторите попытку.";
|
||||
}
|
||||
if (error.status === 429) {
|
||||
const delay = error.retryAfterSeconds;
|
||||
return delay === undefined
|
||||
? "Слишком много запросов. Попробуйте отправить обращение позже."
|
||||
: `Слишком много запросов. Повторите вручную через ${delay} сек.`;
|
||||
}
|
||||
if (error.code === "idempotency_key_reused") {
|
||||
return "Запрос уже связан с другой отправкой. Отправьте форму еще раз.";
|
||||
}
|
||||
if (error.code === "not_found") {
|
||||
return "Не удалось подтвердить связанный объект. Проверьте его доступность и повторите отправку.";
|
||||
}
|
||||
if (error.code === "state_conflict") {
|
||||
return "Действие конфликтует с текущим состоянием объекта. Обновите страницу и проверьте данные.";
|
||||
}
|
||||
if (error.code === "validation_failed") {
|
||||
return "Проверьте текст обращения и выбранный контекст.";
|
||||
}
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return "Сервер не подтвердил право отправить обращение. Обновите вход и повторите попытку.";
|
||||
}
|
||||
return "Не удалось отправить обращение. Попробуйте позже.";
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { AnswerForm } from "./ui/answer-form";
|
||||
export { buildAnswerSubmission, emptyAnswerDraft, newIdempotencyKey } from "./model/answer-draft";
|
||||
export { submitPendingAnswerCommand } from "./model/answer-command";
|
||||
export type { AnswerDraft, AnswerBuildResult } from "./model/answer-draft";
|
||||
export type { AnswerCommandOutcome, PendingAnswerCommand } from "./model/answer-command";
|
||||
@@ -0,0 +1,156 @@
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import { AssessmentAttempt } from "../../../shared/api/schemas";
|
||||
import { submitPendingAnswerCommand, type PendingAnswerCommand } from "./answer-command";
|
||||
|
||||
const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01";
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
const validAttempt: AssessmentAttempt = {
|
||||
id: attemptId,
|
||||
version: 2,
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "python",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
mode: "demo_basic",
|
||||
state: "in_progress",
|
||||
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
|
||||
started_at: "2026-10-08T10:00:00Z",
|
||||
expires_at: "2026-10-08T11:00:00Z",
|
||||
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
|
||||
finished_at: null,
|
||||
progress: { answered_items: 1, max_items: 2 },
|
||||
current_item: {
|
||||
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
|
||||
sequence: 2,
|
||||
prompt: "Сколько?",
|
||||
content: { format: "number", unit: null },
|
||||
},
|
||||
practices: [],
|
||||
};
|
||||
|
||||
describe("assessment answer response validation", () => {
|
||||
it.each([{}, { id: attemptId, version: 2 }])(
|
||||
"keeps the exact command retryable when a successful response is incomplete",
|
||||
async (body) => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
const requests: Array<{ body: string | null; key: string | null; csrf: string | null }> = [];
|
||||
server.use(
|
||||
http.post(
|
||||
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
|
||||
async ({ request }) => {
|
||||
requests.push({
|
||||
body: await request.text(),
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
csrf: request.headers.get("X-CSRF-Token"),
|
||||
});
|
||||
return HttpResponse.json(body, { status: 200 });
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const command: PendingAnswerCommand = {
|
||||
key: "answer-command-key",
|
||||
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
|
||||
itemId: "item-1",
|
||||
};
|
||||
const outcome = await submitPendingAnswerCommand(command, attemptId, "csrf-token");
|
||||
|
||||
expect(outcome.kind).toBe("retry");
|
||||
if (outcome.kind !== "retry") return;
|
||||
expect(outcome.command).toBe(command);
|
||||
expect(outcome.command).toEqual({
|
||||
key: "answer-command-key",
|
||||
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
|
||||
itemId: "item-1",
|
||||
});
|
||||
expect(outcome.error).toMatchObject({
|
||||
status: 200,
|
||||
code: invalidResponseCode,
|
||||
} satisfies Partial<ApiRequestError>);
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
body: command.body,
|
||||
key: command.key,
|
||||
csrf: "csrf-token",
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("accepts a complete server attempt response", async () => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
server.use(
|
||||
http.post(`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, () =>
|
||||
HttpResponse.json(validAttempt, { status: 200 }),
|
||||
),
|
||||
);
|
||||
|
||||
const outcome = await submitPendingAnswerCommand(
|
||||
{
|
||||
key: "answer-command-key",
|
||||
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
|
||||
itemId: "item-1",
|
||||
},
|
||||
attemptId,
|
||||
"csrf-token",
|
||||
);
|
||||
expect(outcome).toEqual({ kind: "accepted", attempt: validAttempt });
|
||||
});
|
||||
|
||||
it("replays the original key and body after a malformed success response", async () => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
const requests: Array<{ body: string; key: string | null }> = [];
|
||||
let responseCount = 0;
|
||||
server.use(
|
||||
http.post(
|
||||
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
|
||||
async ({ request }) => {
|
||||
requests.push({
|
||||
body: await request.text(),
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
});
|
||||
responseCount += 1;
|
||||
return HttpResponse.json(responseCount === 1 ? {} : validAttempt, { status: 200 });
|
||||
},
|
||||
),
|
||||
);
|
||||
const original: PendingAnswerCommand = {
|
||||
key: "same-answer-key",
|
||||
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
|
||||
itemId: "item-1",
|
||||
};
|
||||
|
||||
const first = await submitPendingAnswerCommand(original, attemptId, "csrf-token");
|
||||
expect(first.kind).toBe("retry");
|
||||
if (first.kind !== "retry") return;
|
||||
const second = await submitPendingAnswerCommand(first.command, attemptId, "csrf-token");
|
||||
|
||||
expect(second).toEqual({ kind: "accepted", attempt: validAttempt });
|
||||
expect(requests).toEqual([
|
||||
{ body: original.body, key: original.key },
|
||||
{ body: original.body, key: original.key },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { apiRequest } from "../../../shared/api";
|
||||
import { isOutcomeAmbiguous } from "../../../entities/assessment";
|
||||
import { getSubmitMyAssessmentAnswerUrl } from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import {
|
||||
AssessmentAttempt as assessmentAttemptSchema,
|
||||
type AssessmentAttempt,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export type PendingAnswerCommand = { key: string; body: string; itemId: string };
|
||||
|
||||
export type AnswerCommandOutcome =
|
||||
| { kind: "accepted"; attempt: AssessmentAttempt }
|
||||
| { kind: "retry"; command: PendingAnswerCommand; error: unknown }
|
||||
| { kind: "rejected"; error: unknown };
|
||||
|
||||
export async function submitPendingAnswerCommand(
|
||||
command: PendingAnswerCommand,
|
||||
attemptId: string,
|
||||
csrfToken: string,
|
||||
): Promise<AnswerCommandOutcome> {
|
||||
try {
|
||||
const attempt = await apiRequest<AssessmentAttempt>(
|
||||
getSubmitMyAssessmentAnswerUrl(attemptId),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": command.key,
|
||||
"X-CSRF-Token": csrfToken,
|
||||
},
|
||||
body: command.body,
|
||||
},
|
||||
assessmentAttemptSchema,
|
||||
);
|
||||
return { kind: "accepted", attempt };
|
||||
} catch (error: unknown) {
|
||||
return isOutcomeAmbiguous(error)
|
||||
? { kind: "retry", command, error }
|
||||
: { kind: "rejected", error };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AssessmentAttempt, AssessmentItem } from "../../../shared/api/schemas";
|
||||
import { buildAnswerSubmission, emptyAnswerDraft } from "./answer-draft";
|
||||
|
||||
const attempt = {
|
||||
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01",
|
||||
version: 4,
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
mode: "demo_basic",
|
||||
state: "in_progress",
|
||||
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
|
||||
started_at: "2026-10-07T10:00:00Z",
|
||||
expires_at: "2026-10-07T11:00:00Z",
|
||||
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
|
||||
finished_at: null,
|
||||
progress: { answered_items: 0, max_items: 10 },
|
||||
current_item: null,
|
||||
practices: [],
|
||||
} satisfies AssessmentAttempt;
|
||||
|
||||
const numberItem = {
|
||||
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
|
||||
sequence: 1,
|
||||
prompt: "Сколько?",
|
||||
content: { format: "number", unit: null },
|
||||
} satisfies AssessmentItem;
|
||||
|
||||
describe("assessment answer submission", () => {
|
||||
it("preserves a decimal JSON token without converting it through JavaScript number", () => {
|
||||
const token = "254.00000000000000000000000000000000000001";
|
||||
const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value: token });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.submission).toBeNull();
|
||||
expect(result.body).toContain(`"number":${token}`);
|
||||
expect(JSON.parse(result.body)).toMatchObject({
|
||||
expected_version: attempt.version,
|
||||
item_id: numberItem.id,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([" 2", "2,5", "+2", "01", "Infinity", "2 "])(
|
||||
"rejects a number token that is not valid JSON: %s",
|
||||
(value) => {
|
||||
const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value });
|
||||
|
||||
expect(result).toMatchObject({ ok: false });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the initial order as a draft and requires a complete permutation", () => {
|
||||
const item = {
|
||||
id: numberItem.id,
|
||||
sequence: 1,
|
||||
prompt: "Упорядочите",
|
||||
content: {
|
||||
format: "order",
|
||||
elements: [
|
||||
{ id: "one", text: "Первый" },
|
||||
{ id: "two", text: "Второй" },
|
||||
],
|
||||
},
|
||||
} satisfies AssessmentItem;
|
||||
const draft = emptyAnswerDraft(item);
|
||||
|
||||
expect(draft).toEqual({ format: "order", elementIds: ["one", "two"] });
|
||||
expect(buildAnswerSubmission(attempt, item, draft).ok).toBe(true);
|
||||
expect(
|
||||
buildAnswerSubmission(attempt, item, { format: "order", elementIds: ["one", "one"] }),
|
||||
).toMatchObject({ ok: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { AssessmentAnswerSubmission } from "../../../shared/api/schemas";
|
||||
import type {
|
||||
AssessmentAttempt,
|
||||
AssessmentItem,
|
||||
AssessmentAnswerSubmission as AnswerSubmission,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export type AnswerDraft =
|
||||
| { format: "choice"; optionIds: string[] }
|
||||
| { format: "number"; value: string }
|
||||
| { format: "string"; value: string }
|
||||
| { format: "order"; elementIds: string[] }
|
||||
| { format: "find_error"; lineNumbers: number[] }
|
||||
| { format: "configuration"; value: string }
|
||||
| { format: "practice"; language: "python" | "go" | null; sourceCode: string };
|
||||
|
||||
export type AnswerBuildResult =
|
||||
{ ok: true; body: string; submission: AnswerSubmission | null } | { ok: false; message: string };
|
||||
|
||||
const jsonNumberToken = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
||||
const maxNumberTokenLength = 64;
|
||||
|
||||
export function emptyAnswerDraft(item: AssessmentItem): AnswerDraft {
|
||||
switch (item.content.format) {
|
||||
case "choice":
|
||||
return { format: "choice", optionIds: [] };
|
||||
case "number":
|
||||
return { format: "number", value: "" };
|
||||
case "string":
|
||||
return { format: "string", value: "" };
|
||||
case "order":
|
||||
return { format: "order", elementIds: item.content.elements.map(({ id }) => id) };
|
||||
case "find_error":
|
||||
return { format: "find_error", lineNumbers: [] };
|
||||
case "configuration":
|
||||
return { format: "configuration", value: item.content.initial_config };
|
||||
case "practice":
|
||||
return { format: "practice", language: item.content.languages[0] ?? null, sourceCode: "" };
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAnswerSubmission(
|
||||
attempt: AssessmentAttempt,
|
||||
item: AssessmentItem,
|
||||
draft: AnswerDraft,
|
||||
): AnswerBuildResult {
|
||||
if (draft.format !== item.content.format) {
|
||||
return { ok: false, message: "Формат ответа не совпадает с заданием. Перезагрузите попытку." };
|
||||
}
|
||||
|
||||
if (draft.format === "number" && item.content.format === "number") {
|
||||
const token = draft.value;
|
||||
if (token.length === 0) return { ok: false, message: "Введите числовой ответ." };
|
||||
if (token.length > maxNumberTokenLength || !jsonNumberToken.test(token)) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Введите число без пробелов и разделителей тысяч. Десятичный разделитель - точка.",
|
||||
};
|
||||
}
|
||||
const body = `{"expected_version":${attempt.version},"item_id":${JSON.stringify(item.id)},"answer":{"format":"number","number":${token}}}`;
|
||||
return { ok: true, body, submission: null };
|
||||
}
|
||||
|
||||
let answer: AnswerSubmission["answer"] | null = null;
|
||||
switch (draft.format) {
|
||||
case "choice":
|
||||
if (draft.optionIds.length === 0) {
|
||||
return { ok: false, message: "Выберите ответ." };
|
||||
}
|
||||
if (
|
||||
item.content.format === "choice" &&
|
||||
!item.content.multiple &&
|
||||
draft.optionIds.length !== 1
|
||||
) {
|
||||
return { ok: false, message: "Выберите один вариант." };
|
||||
}
|
||||
answer = { format: "choice", option_ids: [...draft.optionIds] };
|
||||
break;
|
||||
case "string":
|
||||
if (draft.value.length === 0) return { ok: false, message: "Введите ответ." };
|
||||
if (item.content.format !== "string" || draft.value.length > item.content.max_length) {
|
||||
return { ok: false, message: "Проверьте длину ответа." };
|
||||
}
|
||||
answer = { format: "string", text: draft.value };
|
||||
break;
|
||||
case "order":
|
||||
if (
|
||||
item.content.format !== "order" ||
|
||||
draft.elementIds.length !== item.content.elements.length ||
|
||||
new Set(draft.elementIds).size !== item.content.elements.length ||
|
||||
item.content.elements.some(({ id }) => !draft.elementIds.includes(id))
|
||||
) {
|
||||
return { ok: false, message: "Расположите все элементы в нужном порядке." };
|
||||
}
|
||||
answer = { format: "order", element_ids: [...draft.elementIds] };
|
||||
break;
|
||||
case "find_error":
|
||||
if (
|
||||
item.content.format !== "find_error" ||
|
||||
draft.lineNumbers.length === 0 ||
|
||||
draft.lineNumbers.length > item.content.max_selections
|
||||
) {
|
||||
return { ok: false, message: "Выберите строки с ошибкой в пределах лимита." };
|
||||
}
|
||||
answer = { format: "find_error", line_numbers: [...draft.lineNumbers] };
|
||||
break;
|
||||
case "configuration":
|
||||
if (
|
||||
item.content.format !== "configuration" ||
|
||||
draft.value.length === 0 ||
|
||||
draft.value.length > item.content.max_length
|
||||
) {
|
||||
return { ok: false, message: "Введите конфигурацию в пределах указанного лимита." };
|
||||
}
|
||||
answer = { format: "configuration", config: draft.value };
|
||||
break;
|
||||
case "practice":
|
||||
if (
|
||||
item.content.format !== "practice" ||
|
||||
draft.sourceCode.length === 0 ||
|
||||
draft.sourceCode.length > item.content.max_source_length ||
|
||||
(draft.language !== null && !item.content.languages.includes(draft.language))
|
||||
) {
|
||||
return { ok: false, message: "Добавьте решение в разрешенном формате." };
|
||||
}
|
||||
answer = { format: "practice", language: draft.language, source_code: draft.sourceCode };
|
||||
break;
|
||||
}
|
||||
|
||||
if (!answer) return { ok: false, message: "Проверьте ответ и повторите отправку." };
|
||||
|
||||
const parsed = AssessmentAnswerSubmission.safeParse({
|
||||
expected_version: attempt.version,
|
||||
item_id: item.id,
|
||||
answer,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
return { ok: false, message: "Проверьте ответ и повторите отправку." };
|
||||
}
|
||||
return { ok: true, body: JSON.stringify(parsed.data), submission: parsed.data };
|
||||
}
|
||||
|
||||
export function newIdempotencyKey(): string {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fields,
|
||||
.code-lines {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.legend,
|
||||
.code-lines legend {
|
||||
padding: 0 var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.options,
|
||||
.practice {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.option,
|
||||
.code-line {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.option input,
|
||||
.code-line input {
|
||||
flex: 0 0 auto;
|
||||
width: 1.2rem;
|
||||
height: 1.2rem;
|
||||
margin-block-start: 0.15rem;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
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;
|
||||
font-weight: var(--font-weight-regular);
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
font-family: var(--font-mono);
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.field :is(input, select, textarea):focus-visible,
|
||||
.option input:focus-visible,
|
||||
.code-line input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-regular);
|
||||
}
|
||||
|
||||
.order {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.order-item {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.order-actions,
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.code-lines {
|
||||
padding-inline: var(--space-3);
|
||||
}
|
||||
|
||||
.code-line {
|
||||
align-items: baseline;
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.line-number {
|
||||
flex: 0 0 2.5rem;
|
||||
color: var(--color-text-secondary);
|
||||
text-align: end;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.code-line code {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.examples {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-canvas);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.examples h3,
|
||||
.examples p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.examples pre {
|
||||
max-width: 100%;
|
||||
margin: var(--space-1) 0 var(--space-3);
|
||||
padding: var(--space-2);
|
||||
overflow-x: auto;
|
||||
background: var(--color-surface);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.fields {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.order-item {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import type { AssessmentItem } from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import { emptyAnswerDraft, type AnswerDraft } from "../model/answer-draft";
|
||||
import styles from "./answer-form.module.css";
|
||||
|
||||
type AnswerFormProps = {
|
||||
item: AssessmentItem;
|
||||
isSaving: boolean;
|
||||
retryable: boolean;
|
||||
errorMessage: string | null;
|
||||
onSubmit: (draft: AnswerDraft) => void;
|
||||
onRetry: () => void;
|
||||
};
|
||||
|
||||
export function AnswerForm({
|
||||
item,
|
||||
isSaving,
|
||||
retryable,
|
||||
errorMessage,
|
||||
onSubmit,
|
||||
onRetry,
|
||||
}: AnswerFormProps) {
|
||||
const [draft, setDraft] = useState<AnswerDraft>(() => emptyAnswerDraft(item));
|
||||
const frozen = isSaving || retryable;
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (frozen) return;
|
||||
onSubmit(draft);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit}>
|
||||
<fieldset className={styles.fields} disabled={frozen}>
|
||||
<legend className={styles.legend}>Ваш ответ</legend>
|
||||
<AnswerFields item={item} draft={draft} setDraft={setDraft} />
|
||||
</fieldset>
|
||||
{errorMessage ? (
|
||||
<p className={styles.error} role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
{retryable ? (
|
||||
<Button isBusy={isSaving} onClick={onRetry}>
|
||||
Повторить отправку того же ответа
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="submit" isBusy={isSaving}>
|
||||
{isSaving ? "Сохраняем ответ..." : "Отправить ответ"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
type AnswerFieldsProps = {
|
||||
item: AssessmentItem;
|
||||
draft: AnswerDraft;
|
||||
setDraft: (draft: AnswerDraft) => void;
|
||||
};
|
||||
|
||||
function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
|
||||
const content = item.content;
|
||||
|
||||
switch (content.format) {
|
||||
case "choice": {
|
||||
const selected = draft.format === "choice" ? draft.optionIds : [];
|
||||
return (
|
||||
<div className={styles.options}>
|
||||
{content.options.map((option) => {
|
||||
const checked = selected.includes(option.id);
|
||||
return (
|
||||
<label className={styles.option} key={option.id}>
|
||||
<input
|
||||
type={content.multiple ? "checkbox" : "radio"}
|
||||
name={`answer-${item.id}`}
|
||||
value={option.id}
|
||||
checked={checked}
|
||||
onChange={() => {
|
||||
const optionIds = content.multiple
|
||||
? checked
|
||||
? selected.filter((id) => id !== option.id)
|
||||
: [...selected, option.id]
|
||||
: [option.id];
|
||||
setDraft({ format: "choice", optionIds });
|
||||
}}
|
||||
/>
|
||||
<span>{option.text}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case "number":
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>Числовой ответ{content.unit ? `, ${content.unit}` : ""}</span>
|
||||
<input
|
||||
autoComplete="off"
|
||||
inputMode="decimal"
|
||||
maxLength={64}
|
||||
name="number-answer"
|
||||
type="text"
|
||||
value={draft.format === "number" ? draft.value : ""}
|
||||
onChange={(event) => setDraft({ format: "number", value: event.currentTarget.value })}
|
||||
/>
|
||||
<span className={styles.hint}>
|
||||
Десятичный разделитель - точка. Введенное число отправляется без округления.
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
case "string":
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>Краткий ответ</span>
|
||||
<input
|
||||
autoComplete="off"
|
||||
maxLength={content.max_length}
|
||||
name="text-answer"
|
||||
type="text"
|
||||
value={draft.format === "string" ? draft.value : ""}
|
||||
onChange={(event) => setDraft({ format: "string", value: event.currentTarget.value })}
|
||||
/>
|
||||
<span className={styles.hint}>Не более {content.max_length} символов.</span>
|
||||
</label>
|
||||
);
|
||||
case "order": {
|
||||
const ids =
|
||||
draft.format === "order" ? draft.elementIds : content.elements.map(({ id }) => id);
|
||||
const options = new Map(content.elements.map((element) => [element.id, element.text]));
|
||||
function move(index: number, offset: -1 | 1) {
|
||||
const nextIndex = index + offset;
|
||||
if (nextIndex < 0 || nextIndex >= ids.length) return;
|
||||
const next = [...ids];
|
||||
[next[index], next[nextIndex]] = [next[nextIndex] as string, next[index] as string];
|
||||
setDraft({ format: "order", elementIds: next });
|
||||
}
|
||||
return (
|
||||
<ol className={styles.order} aria-label="Порядок элементов">
|
||||
{ids.map((id, index) => (
|
||||
<li className={styles["order-item"]} key={id}>
|
||||
<span>{options.get(id)}</span>
|
||||
<div className={styles["order-actions"]}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={index === 0}
|
||||
aria-label={`Переместить ${options.get(id)} выше`}
|
||||
onClick={() => move(index, -1)}
|
||||
>
|
||||
Выше
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={index === ids.length - 1}
|
||||
aria-label={`Переместить ${options.get(id)} ниже`}
|
||||
onClick={() => move(index, 1)}
|
||||
>
|
||||
Ниже
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
case "find_error": {
|
||||
const selected = draft.format === "find_error" ? draft.lineNumbers : [];
|
||||
return (
|
||||
<fieldset className={styles["code-lines"]}>
|
||||
<legend>Отметьте строки с ошибкой</legend>
|
||||
{content.lines.map((line) => (
|
||||
<label className={styles["code-line"]} key={line.number}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(line.number)}
|
||||
onChange={(event) => {
|
||||
const lineNumbers = event.currentTarget.checked
|
||||
? [...selected, line.number]
|
||||
: selected.filter((number) => number !== line.number);
|
||||
setDraft({ format: "find_error", lineNumbers });
|
||||
}}
|
||||
/>
|
||||
<span className={styles["line-number"]}>{line.number}</span>
|
||||
<code>{line.text}</code>
|
||||
</label>
|
||||
))}
|
||||
<p className={styles.hint}>Можно отметить не более {content.max_selections} строк.</p>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
case "configuration":
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>Конфигурация ({content.syntax})</span>
|
||||
<textarea
|
||||
autoComplete="off"
|
||||
maxLength={content.max_length}
|
||||
name="configuration-answer"
|
||||
rows={12}
|
||||
spellCheck={false}
|
||||
value={draft.format === "configuration" ? draft.value : content.initial_config}
|
||||
onChange={(event) =>
|
||||
setDraft({ format: "configuration", value: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
<span className={styles.hint}>Не более {content.max_length} символов.</span>
|
||||
</label>
|
||||
);
|
||||
case "practice":
|
||||
return (
|
||||
<div className={styles.practice}>
|
||||
{content.languages.length > 1 ? (
|
||||
<label className={styles.field}>
|
||||
<span>Язык решения</span>
|
||||
<select
|
||||
value={draft.format === "practice" ? (draft.language ?? "") : ""}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
format: "practice",
|
||||
language:
|
||||
event.currentTarget.value === ""
|
||||
? null
|
||||
: (event.currentTarget.value as "go" | "python"),
|
||||
sourceCode: draft.format === "practice" ? draft.sourceCode : "",
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Выберите язык</option>
|
||||
{content.languages.map((language) => (
|
||||
<option key={language} value={language}>
|
||||
{language === "go" ? "Go" : "Python"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : content.languages[0] ? (
|
||||
<p className={styles.hint}>
|
||||
Язык решения: {content.languages[0] === "go" ? "Go" : "Python"}.
|
||||
</p>
|
||||
) : null}
|
||||
{content.public_examples.length > 0 ? (
|
||||
<div className={styles.examples}>
|
||||
<h3>Примеры</h3>
|
||||
{content.public_examples.map((example, index) => (
|
||||
<div key={`${index}-${example.input}`}>
|
||||
<p>Входные данные</p>
|
||||
<pre>{example.input}</pre>
|
||||
<p>Ожидаемый вывод</p>
|
||||
<pre>{example.expected_output}</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<label className={styles.field}>
|
||||
<span>Код решения</span>
|
||||
<textarea
|
||||
autoComplete="off"
|
||||
maxLength={content.max_source_length}
|
||||
name="practice-answer"
|
||||
rows={16}
|
||||
spellCheck={false}
|
||||
value={draft.format === "practice" ? draft.sourceCode : ""}
|
||||
onChange={(event) =>
|
||||
setDraft({
|
||||
format: "practice",
|
||||
language:
|
||||
draft.format === "practice" ? draft.language : (content.languages[0] ?? null),
|
||||
sourceCode: event.currentTarget.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className={styles.hint}>Не более {content.max_source_length} символов.</span>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { CreateSupportCase } from "./ui/create-support-case";
|
||||
@@ -0,0 +1,117 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.intro {
|
||||
max-width: 68ch;
|
||||
margin: 0 0 1.25rem;
|
||||
color: var(--color-text-muted);
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.form {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
max-width: 52rem;
|
||||
}
|
||||
|
||||
.context {
|
||||
min-width: 0;
|
||||
padding: 1rem;
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.context legend {
|
||||
padding: 0 0.35rem;
|
||||
color: var(--color-text-strong);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.checkbox {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.7rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.checkbox input {
|
||||
width: 1.1rem;
|
||||
height: 1.1rem;
|
||||
margin: 0.15rem 0 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.field label {
|
||||
color: var(--color-text-strong);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 12rem;
|
||||
padding: 0.85rem;
|
||||
resize: vertical;
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.field textarea:focus-visible,
|
||||
.checkbox input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field textarea[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.92rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: 0.85rem 1rem;
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.error:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > * {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
createSupportCaseIdempotencyKey,
|
||||
getSupportCaseIdempotencyKey,
|
||||
isSupportSessionAccessError,
|
||||
parseSupportCaseContext,
|
||||
queryClientHasSupportActor,
|
||||
supportCaseCreateFailureMessage,
|
||||
supportCaseContextLabel,
|
||||
supportCaseDetailQueryKey,
|
||||
supportCaseListQueryKey,
|
||||
supportCasePathFor,
|
||||
supportSessionMatches,
|
||||
type SupportCaseKeyBinding,
|
||||
} from "../../../entities/support-case";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { createMySupportCase } from "../../../shared/api/endpoints/support/support";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
Session,
|
||||
SupportCase,
|
||||
SupportCaseCreate,
|
||||
SupportCaseObjectReference,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./create-support-case.module.css";
|
||||
|
||||
function locationSupportContext(state: unknown): SupportCaseObjectReference | null {
|
||||
if (typeof state !== "object" || state === null || Array.isArray(state)) return null;
|
||||
return parseSupportCaseContext((state as Record<string, unknown>).supportContext);
|
||||
}
|
||||
|
||||
export function CreateSupportCase() {
|
||||
const queryClient = useQueryClient();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const formId = useId();
|
||||
const errorRef = useRef<HTMLDivElement>(null);
|
||||
const idempotencyBinding = useRef<SupportCaseKeyBinding | null>(null);
|
||||
const [description, setDescription] = useState("");
|
||||
const [context] = useState(() => locationSupportContext(location.state));
|
||||
const [includeContext, setIncludeContext] = useState(Boolean(context));
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: ({ data, key }: { data: SupportCaseCreate; key: string }) => {
|
||||
const csrfToken = actor?.csrf_token;
|
||||
if (!actor || !csrfToken || !session.isSuccess) {
|
||||
throw new Error("An active account session is required.");
|
||||
}
|
||||
return createMySupportCase(
|
||||
data,
|
||||
{ "Idempotency-Key": key },
|
||||
{ headers: { "X-CSRF-Token": csrfToken } },
|
||||
);
|
||||
},
|
||||
gcTime: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (actionError) errorRef.current?.focus();
|
||||
}, [actionError]);
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || !isSupportSessionAccessError(session.error)) return;
|
||||
queryClient.removeQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "account" &&
|
||||
query.queryKey[1] === accountId &&
|
||||
query.queryKey[2] === "support-cases",
|
||||
});
|
||||
}, [actor, knownActor, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) return <LoadingState label="Проверяем вход..." />;
|
||||
if (session.isError && isSupportSessionAccessError(session.error)) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Войдите, чтобы отправить обращение"
|
||||
description="После входа вы вернетесь в раздел поддержки. Чужая история обращений не будет открыта."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Войти и продолжить
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
title="Не удалось проверить вход"
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!actor || (actor.account.scenario !== "candidate" && actor.account.scenario !== "employer")) {
|
||||
return <ForbiddenState title="Поддержка недоступна" />;
|
||||
}
|
||||
|
||||
const contextLabel = context ? supportCaseContextLabel(context) : null;
|
||||
const isSubmitting = create.isPending;
|
||||
const canSubmit = description.trim().length > 0 && !isSubmitting && !session.isError;
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (
|
||||
!canSubmit ||
|
||||
!actor ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setActionError(null);
|
||||
const data: SupportCaseCreate = {
|
||||
type: "support",
|
||||
description,
|
||||
...(includeContext && context ? { object: context } : {}),
|
||||
};
|
||||
const binding = getSupportCaseIdempotencyKey(
|
||||
data,
|
||||
idempotencyBinding.current,
|
||||
createSupportCaseIdempotencyKey,
|
||||
);
|
||||
idempotencyBinding.current = binding;
|
||||
|
||||
let created: SupportCase;
|
||||
try {
|
||||
created = await create.mutateAsync({ data, key: binding.key });
|
||||
} catch (error: unknown) {
|
||||
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
|
||||
if (error instanceof ApiRequestError && error.code === "idempotency_key_reused") {
|
||||
idempotencyBinding.current = null;
|
||||
}
|
||||
setActionError(supportCaseCreateFailureMessage(error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
|
||||
queryClient.setQueryData(supportCaseDetailQueryKey(actor.account.id, created.id), created);
|
||||
void queryClient.invalidateQueries({ queryKey: supportCaseListQueryKey(actor.account.id) });
|
||||
navigate(supportCasePathFor(actor, created.id), { replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section title="Новое обращение">
|
||||
<p className={styles.intro}>
|
||||
Опишите вопрос своими словами. Не добавляйте пароль или контактные данные других людей.
|
||||
Обращение сохранится в вашем кабинете, а ответ появится в его истории.
|
||||
</p>
|
||||
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
|
||||
{context && contextLabel ? (
|
||||
<fieldset className={styles.context} disabled={isSubmitting}>
|
||||
<legend>Контекст страницы</legend>
|
||||
<label className={styles.checkbox}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeContext}
|
||||
onChange={(event) => setIncludeContext(event.currentTarget.checked)}
|
||||
aria-describedby={`${formId}-context-hint`}
|
||||
/>
|
||||
<span>Связать обращение с {contextLabel}</span>
|
||||
</label>
|
||||
<p id={`${formId}-context-hint`} className={styles.hint}>
|
||||
Передается только вид объекта и его идентификатор. Пароли и параметры адресной
|
||||
строки не передаются.
|
||||
</p>
|
||||
</fieldset>
|
||||
) : null}
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${formId}-description`}>Что произошло или какая помощь нужна</label>
|
||||
<textarea
|
||||
id={`${formId}-description`}
|
||||
name="description"
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.currentTarget.value)}
|
||||
rows={7}
|
||||
maxLength={4000}
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={actionError ? true : undefined}
|
||||
aria-describedby={`${formId}-hint${actionError ? ` ${formId}-error` : ""}`}
|
||||
/>
|
||||
<p id={`${formId}-hint`} className={styles.hint}>
|
||||
До 4000 символов. Текст будет показан как обычный текст.
|
||||
</p>
|
||||
</div>
|
||||
{actionError ? (
|
||||
<div
|
||||
className={styles.error}
|
||||
id={`${formId}-error`}
|
||||
role="alert"
|
||||
tabIndex={-1}
|
||||
ref={errorRef}
|
||||
>
|
||||
{actionError}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" isBusy={isSubmitting} aria-disabled={!canSubmit}>
|
||||
{isSubmitting ? "Отправляем..." : "Отправить обращение"}
|
||||
</Button>
|
||||
<TextLink
|
||||
to={
|
||||
actor.account.scenario === "candidate"
|
||||
? paths.candidate.supportCases
|
||||
: paths.employer.supportCases
|
||||
}
|
||||
>
|
||||
Мои обращения
|
||||
</TextLink>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { isCurrentSessionSnapshot } from "./session-refresh";
|
||||
|
||||
const initialSession: Session = {
|
||||
account: {
|
||||
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
|
||||
email: "owner@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-06T09:00:00Z",
|
||||
},
|
||||
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
|
||||
};
|
||||
|
||||
describe("isCurrentSessionSnapshot", () => {
|
||||
it("accepts the same account and CSRF snapshot only while its cache generation is unchanged", () => {
|
||||
expect(isCurrentSessionSnapshot(initialSession, "success", 100, initialSession, 100)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isCurrentSessionSnapshot(initialSession, "success", 101, initialSession, 100)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a changed account or CSRF token before applying a delayed refresh", () => {
|
||||
const rotatedToken = { ...initialSession, csrf_token: "zyxwvutsrqponmlkjihgfedcba654321" };
|
||||
const anotherAccount = {
|
||||
...initialSession,
|
||||
account: { ...initialSession.account, id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e02" },
|
||||
};
|
||||
|
||||
expect(isCurrentSessionSnapshot(rotatedToken, "success", 100, initialSession, 100)).toBe(false);
|
||||
expect(isCurrentSessionSnapshot(anotherAccount, "success", 100, initialSession, 100)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
|
||||
type SessionQueryStatus = "error" | "pending" | "success";
|
||||
|
||||
export function isCurrentSessionSnapshot(
|
||||
current: Session | undefined,
|
||||
status: SessionQueryStatus | undefined,
|
||||
dataUpdatedAt: number | undefined,
|
||||
expected: Session,
|
||||
expectedDataUpdatedAt: number,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
current &&
|
||||
status === "success" &&
|
||||
current.account.id === expected.account.id &&
|
||||
current.csrf_token === expected.csrf_token &&
|
||||
dataUpdatedAt === expectedDataUpdatedAt,
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from "../../../shared/api/endpoints/organization/organization";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
getCurrentSession,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
rebaseCompanyDraft,
|
||||
type CompanyDraft,
|
||||
} from "../../../entities/company";
|
||||
import { isCurrentSessionSnapshot } from "../model/session-refresh";
|
||||
import styles from "./company-editor.module.css";
|
||||
|
||||
type CompanyEditorProps = {
|
||||
@@ -150,23 +152,64 @@ export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEd
|
||||
);
|
||||
}
|
||||
|
||||
function isSubmittingAccountCurrent(expected: Session): boolean {
|
||||
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
return current?.account.id === expected.account.id;
|
||||
}
|
||||
|
||||
async function refreshAfterCsrfFailure(expected: Session): Promise<void> {
|
||||
if (!isSubmittingAccountCurrent(expected)) return;
|
||||
const sessionQueryKey = getGetCurrentSessionQueryKey();
|
||||
const initialQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
|
||||
if (!isSubmittingSessionCurrent(expected) || !initialQueryState) return;
|
||||
const initialDataUpdatedAt = initialQueryState.dataUpdatedAt;
|
||||
setActionError(null);
|
||||
setCsrfRetryMessage("Проверяем текущий вход...");
|
||||
setStatus("failed");
|
||||
const refreshed = await session.refetch();
|
||||
if (refreshed.data?.account.id !== expected.account.id) return;
|
||||
setCsrfRetryMessage(
|
||||
refreshed.isError
|
||||
? "Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова."
|
||||
: "Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
|
||||
);
|
||||
try {
|
||||
const refreshed = await getCurrentSession();
|
||||
const currentQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
|
||||
const current = queryClient.getQueryData<Session>(sessionQueryKey);
|
||||
if (
|
||||
!isCurrentSessionSnapshot(
|
||||
current,
|
||||
currentQueryState?.status,
|
||||
currentQueryState?.dataUpdatedAt,
|
||||
expected,
|
||||
initialDataUpdatedAt,
|
||||
)
|
||||
) {
|
||||
if (
|
||||
current?.account.id === expected.account.id &&
|
||||
currentQueryState?.status === "success" &&
|
||||
currentQueryState.dataUpdatedAt !== initialDataUpdatedAt
|
||||
) {
|
||||
setCsrfRetryMessage("Вход уже обновлен. Данные формы сохранены; повторите сохранение.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
queryClient.setQueryData(sessionQueryKey, refreshed);
|
||||
if (refreshed.account.id !== expected.account.id) return;
|
||||
setCsrfRetryMessage(
|
||||
"Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const currentQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
|
||||
const current = queryClient.getQueryData<Session>(sessionQueryKey);
|
||||
if (
|
||||
!isCurrentSessionSnapshot(
|
||||
current,
|
||||
currentQueryState?.status,
|
||||
currentQueryState?.dataUpdatedAt,
|
||||
expected,
|
||||
initialDataUpdatedAt,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && (error.status === 401 || error.status === 403)) {
|
||||
onAccessLost(error);
|
||||
void queryClient.invalidateQueries({ queryKey: sessionQueryKey });
|
||||
return;
|
||||
}
|
||||
setCsrfRetryMessage(
|
||||
"Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCreate(): Promise<void> {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export { NeedEditor, type NeedEditorProps } from "./ui/need-editor";
|
||||
@@ -0,0 +1,202 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.intro,
|
||||
.hint,
|
||||
.meta,
|
||||
.provenance,
|
||||
.question {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.hint,
|
||||
.provenance,
|
||||
.question,
|
||||
.field-error,
|
||||
.action-error,
|
||||
.meta {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group,
|
||||
.salary,
|
||||
.conflict,
|
||||
.recommendations,
|
||||
.list {
|
||||
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);
|
||||
}
|
||||
|
||||
.group legend,
|
||||
.work-formats legend {
|
||||
padding: 0 var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field label,
|
||||
.add-row label,
|
||||
.skill-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea,
|
||||
.item input,
|
||||
.add-row input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
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;
|
||||
}
|
||||
|
||||
.add-row input {
|
||||
flex: 1 1 14rem;
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field :is(input, select, textarea):focus-visible,
|
||||
.item input:focus-visible,
|
||||
.add-row input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field [aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.provenance {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.provenance p,
|
||||
.provenance blockquote,
|
||||
.item blockquote {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.provenance blockquote,
|
||||
.item blockquote {
|
||||
padding-inline-start: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-divider);
|
||||
color: var(--color-text-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.question {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.field-error,
|
||||
.action-error {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.work-formats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.work-formats label {
|
||||
display: inline-flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.work-formats .provenance,
|
||||
.work-formats .question {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.salary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.actions,
|
||||
.add-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.list ul {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.badge {
|
||||
width: fit-content;
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text-secondary);
|
||||
background: var(--color-canvas);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.conflict {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.meta {
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.salary-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.group,
|
||||
.salary,
|
||||
.conflict,
|
||||
.recommendations,
|
||||
.list {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Need, Session } from "../../../shared/api/schemas";
|
||||
import { Need as NeedSchema } from "../../../shared/api/schemas";
|
||||
import { NeedEditor } from "./need-editor";
|
||||
|
||||
type ExampleMap = Record<string, { value?: unknown } | undefined>;
|
||||
const bundlePath = fileURLToPath(
|
||||
new URL("../../../../../api/core/openapi.bundle.yml", import.meta.url),
|
||||
);
|
||||
const examples = (
|
||||
parseYaml(readFileSync(bundlePath, "utf8")) as { components: { examples: ExampleMap } }
|
||||
).components.examples;
|
||||
|
||||
function contractExample(name: string): unknown {
|
||||
const value = examples[name]?.value;
|
||||
if (value === undefined) throw new Error(`Missing contract example ${name}.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
const need = NeedSchema.parse(contractExample("NeedExtractedWithUnknownSkill")) as Need;
|
||||
const session: Session = {
|
||||
account: {
|
||||
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
|
||||
email: "owner@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-06T09:00:00Z",
|
||||
},
|
||||
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
|
||||
};
|
||||
|
||||
function renderEditor(value: Need): string {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NeedEditor
|
||||
accountId={session.account.id}
|
||||
organizationId={value.organization_id}
|
||||
session={session}
|
||||
need={value}
|
||||
onCreated={() => undefined}
|
||||
onSaved={() => undefined}
|
||||
onAccessLost={() => undefined}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("NeedEditor", () => {
|
||||
it("keeps parser suggestions reviewable and asks about unknown critical fields", () => {
|
||||
const markup = renderEditor(need);
|
||||
|
||||
expect(markup).toContain("Предложено из текста");
|
||||
expect(markup).toContain("Подтвердить предложение");
|
||||
expect(markup).toContain("Какой грейд нужен");
|
||||
expect(markup).toContain("в какой базе");
|
||||
expect(markup).toContain("Вакансия для сохранения потребности не требуется.");
|
||||
expect(markup).toMatch(
|
||||
/<select id="[^"]+-grade" aria-invalid="false"><option value="" selected="">Не указано/,
|
||||
);
|
||||
});
|
||||
|
||||
it("shows pending recommendation status without fabricating categories", () => {
|
||||
const pending: Need = {
|
||||
...need,
|
||||
recommendations: {
|
||||
status: "pending",
|
||||
requirements_version: need.requirements_version,
|
||||
policy_version: null,
|
||||
algorithm_version: null,
|
||||
computed_at: null,
|
||||
categories: [],
|
||||
},
|
||||
};
|
||||
const markup = renderEditor(pending);
|
||||
|
||||
expect(markup).toContain("Рекомендации пока не рассчитаны.");
|
||||
expect(markup).not.toContain("Категории рассчитаны по подтвержденным требованиям.");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
export { RequestManualAssessment } from "./ui/request-manual-assessment";
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { CatalogSpecializationOption } from "../../../entities/specialization";
|
||||
|
||||
export function manualAvailabilityMessage(option: CatalogSpecializationOption | null): string {
|
||||
if (!option) return "Выберите специальность, чтобы увидеть ее доступность.";
|
||||
if (option.test_availability.status === "in_development") {
|
||||
return option.test_availability.note
|
||||
? `${option.test_availability.note} Запрос ручной оценки остается доступен.`
|
||||
: "Автоматическая проверка пока не опубликована. Запрос ручной оценки остается доступен.";
|
||||
}
|
||||
return "Автоматическая проверка опубликована отдельно. Этот запрос направляется эксперту и не запускает тест.";
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.intro,
|
||||
.privacy,
|
||||
.hint {
|
||||
max-width: 72ch;
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.privacy {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
max-width: 52rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field select,
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
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;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
min-height: 10rem;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field select:focus-visible,
|
||||
.field textarea:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.error:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > :first-child {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CatalogSpecializationOption } from "../../../entities/specialization";
|
||||
import { manualAvailabilityMessage } from "../model/availability-message";
|
||||
|
||||
const unavailableOption: CatalogSpecializationOption = {
|
||||
code: "ds_ml",
|
||||
title: "DS/ML",
|
||||
directionCode: "data",
|
||||
directionTitle: "Данные",
|
||||
test_availability: {
|
||||
status: "in_development",
|
||||
grades: [],
|
||||
task_languages: [],
|
||||
note: "Банк заданий готовится.",
|
||||
},
|
||||
};
|
||||
|
||||
describe("manual assessment availability copy", () => {
|
||||
it("keeps the manual request available when the automated bank is unavailable", () => {
|
||||
const copy = manualAvailabilityMessage(unavailableOption);
|
||||
|
||||
expect(copy).toContain("Банк заданий готовится.");
|
||||
expect(copy).toContain("Запрос ручной оценки остается доступен.");
|
||||
});
|
||||
|
||||
it("states that a manual request does not start an available automated test", () => {
|
||||
const copy = manualAvailabilityMessage({
|
||||
...unavailableOption,
|
||||
test_availability: {
|
||||
status: "available",
|
||||
grades: ["junior"],
|
||||
task_languages: ["go"],
|
||||
note: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(copy).toContain("не запускает тест");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
createSupportCaseIdempotencyKey,
|
||||
getSupportCaseIdempotencyKey,
|
||||
isSupportSessionAccessError,
|
||||
queryClientHasSupportActor,
|
||||
supportCaseCreateFailureMessage,
|
||||
supportCaseDetailQueryKey,
|
||||
supportCaseListQueryKey,
|
||||
supportCasePathFor,
|
||||
supportSessionMatches,
|
||||
type SupportCaseKeyBinding,
|
||||
} from "../../../entities/support-case";
|
||||
import { listSpecializationOptions } from "../../../entities/specialization";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { useGetSpecializationCatalog } from "../../../shared/api/endpoints/catalog/catalog";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { createMySupportCase } from "../../../shared/api/endpoints/support/support";
|
||||
import { manualAvailabilityMessage } from "../model/availability-message";
|
||||
import type {
|
||||
CatalogGrade,
|
||||
Session,
|
||||
SpecializationCode,
|
||||
SupportCase,
|
||||
SupportCaseCreate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./request-manual-assessment.module.css";
|
||||
|
||||
export function RequestManualAssessment() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const catalog = useGetSpecializationCatalog({ query: { retry: false, staleTime: 0 } });
|
||||
const formId = useId();
|
||||
const errorRef = useRef<HTMLDivElement>(null);
|
||||
const idempotencyBinding = useRef<SupportCaseKeyBinding | null>(null);
|
||||
const [specializationCode, setSpecializationCode] = useState<SpecializationCode | "">("");
|
||||
const [gradeCode, setGradeCode] = useState<CatalogGrade["code"] | "">("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
const options = useMemo(
|
||||
() => (catalog.data ? listSpecializationOptions(catalog.data) : []),
|
||||
[catalog.data],
|
||||
);
|
||||
const specialization = useMemo(
|
||||
() => options.find((option) => option.code === specializationCode) ?? null,
|
||||
[options, specializationCode],
|
||||
);
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: ({ data, key }: { data: SupportCaseCreate; key: string }) => {
|
||||
const csrfToken = actor?.csrf_token;
|
||||
if (!actor || !csrfToken || !session.isSuccess) {
|
||||
throw new Error("An active account session is required.");
|
||||
}
|
||||
return createMySupportCase(
|
||||
data,
|
||||
{ "Idempotency-Key": key },
|
||||
{ headers: { "X-CSRF-Token": csrfToken } },
|
||||
);
|
||||
},
|
||||
gcTime: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (actionError) errorRef.current?.focus();
|
||||
}, [actionError]);
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || !isSupportSessionAccessError(session.error)) return;
|
||||
queryClient.removeQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "account" &&
|
||||
query.queryKey[1] === accountId &&
|
||||
query.queryKey[2] === "support-cases",
|
||||
});
|
||||
}, [actor, knownActor, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) return <LoadingState label="Проверяем вход..." />;
|
||||
if (session.isError && isSupportSessionAccessError(session.error)) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Войдите, чтобы отправить запрос эксперту"
|
||||
description="После входа вы вернетесь в раздел поддержки. Запрос не включает согласие C3."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Войти и продолжить
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
title="Не удалось проверить вход"
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!actor || actor.account.scenario !== "candidate") {
|
||||
return (
|
||||
<ForbiddenState
|
||||
title="Ручная оценка доступна кандидатам"
|
||||
description="Откройте кабинет кандидата, чтобы выбрать специальность и желаемый грейд."
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (catalog.isPending && !catalog.data)
|
||||
return <LoadingState label="Загружаем каталог специальностей..." />;
|
||||
if (catalog.isError && !catalog.data) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={catalog.error}
|
||||
title="Не удалось загрузить специальности"
|
||||
isRetrying={catalog.isRefetching}
|
||||
onRetry={() => void catalog.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (catalog.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={catalog.error}
|
||||
title="Не удалось подтвердить каталог"
|
||||
isRetrying={catalog.isRefetching}
|
||||
onRetry={() => void catalog.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const isSubmitting = create.isPending;
|
||||
const grades = catalog.data?.grades ?? [];
|
||||
const canSubmit = Boolean(specializationCode && gradeCode && description.trim()) && !isSubmitting;
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (
|
||||
!canSubmit ||
|
||||
!actor ||
|
||||
!specialization ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setActionError(null);
|
||||
const data: SupportCaseCreate = {
|
||||
type: "manual_assessment",
|
||||
description,
|
||||
assessment_target: {
|
||||
specialization: specialization.code,
|
||||
grade: gradeCode as CatalogGrade["code"],
|
||||
},
|
||||
};
|
||||
const binding = getSupportCaseIdempotencyKey(
|
||||
data,
|
||||
idempotencyBinding.current,
|
||||
createSupportCaseIdempotencyKey,
|
||||
);
|
||||
idempotencyBinding.current = binding;
|
||||
|
||||
let created: SupportCase;
|
||||
try {
|
||||
created = await create.mutateAsync({ data, key: binding.key });
|
||||
} catch (error: unknown) {
|
||||
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
|
||||
if (error instanceof ApiRequestError && error.code === "idempotency_key_reused") {
|
||||
idempotencyBinding.current = null;
|
||||
}
|
||||
setActionError(supportCaseCreateFailureMessage(error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
|
||||
queryClient.setQueryData(supportCaseDetailQueryKey(actor.account.id, created.id), created);
|
||||
void queryClient.invalidateQueries({ queryKey: supportCaseListQueryKey(actor.account.id) });
|
||||
navigate(supportCasePathFor(actor, created.id), { replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section title="Запрос ручной оценки">
|
||||
<p className={styles.intro}>
|
||||
Вы выбираете специальность и желаемый грейд. Эксперт рассмотрит запрос по рубрике этой
|
||||
категории, если она опубликована. Запрос доступен до первой попытки и не требует C3.
|
||||
</p>
|
||||
<p className={styles.privacy}>
|
||||
Отправка не включает и не меняет C3, не создает попытку и не меняет подтвержденный грейд.{" "}
|
||||
<TextLink to={paths.candidate.privacy}>Проверить состояние согласия C3</TextLink>.
|
||||
</p>
|
||||
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${formId}-specialization`}>Специальность</label>
|
||||
<select
|
||||
id={`${formId}-specialization`}
|
||||
value={specializationCode}
|
||||
onChange={(event) =>
|
||||
setSpecializationCode(event.currentTarget.value as SpecializationCode | "")
|
||||
}
|
||||
disabled={isSubmitting || catalog.isFetching}
|
||||
aria-describedby={`${formId}-availability`}
|
||||
required
|
||||
>
|
||||
<option value="">Выберите специальность</option>
|
||||
{options.map((option) => (
|
||||
<option key={option.code} value={option.code}>
|
||||
{option.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p id={`${formId}-availability`} className={styles.hint}>
|
||||
{manualAvailabilityMessage(specialization)}
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${formId}-grade`}>Желаемый грейд</label>
|
||||
<select
|
||||
id={`${formId}-grade`}
|
||||
value={gradeCode}
|
||||
onChange={(event) =>
|
||||
setGradeCode(event.currentTarget.value as CatalogGrade["code"] | "")
|
||||
}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
>
|
||||
<option value="">Выберите грейд</option>
|
||||
{grades.map((grade) => (
|
||||
<option key={grade.code} value={grade.code}>
|
||||
{grade.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className={styles.hint}>Это желаемая цель оценки, а не подтвержденный результат.</p>
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={`${formId}-description`}>Почему вы просите ручную оценку</label>
|
||||
<textarea
|
||||
id={`${formId}-description`}
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.currentTarget.value)}
|
||||
rows={6}
|
||||
maxLength={4000}
|
||||
required
|
||||
disabled={isSubmitting}
|
||||
aria-describedby={`${formId}-description-hint${actionError ? ` ${formId}-error` : ""}`}
|
||||
/>
|
||||
<p id={`${formId}-description-hint`} className={styles.hint}>
|
||||
Можно отправить запрос без предыдущей попытки. До 4000 символов.
|
||||
</p>
|
||||
</div>
|
||||
{actionError ? (
|
||||
<div
|
||||
id={`${formId}-error`}
|
||||
className={styles.error}
|
||||
role="alert"
|
||||
tabIndex={-1}
|
||||
ref={errorRef}
|
||||
>
|
||||
{actionError}
|
||||
</div>
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" isBusy={isSubmitting} aria-disabled={!canSubmit}>
|
||||
{isSubmitting ? "Отправляем запрос..." : "Отправить запрос эксперту"}
|
||||
</Button>
|
||||
<TextLink to={paths.candidate.supportCases}>Мои обращения</TextLink>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { getSignInDestination } from "./sign-in-destination";
|
||||
|
||||
describe("getSignInDestination", () => {
|
||||
it.each(["candidate", "employer"] as const)(
|
||||
"returns %s to its own support area before onboarding is complete",
|
||||
(scenario) => {
|
||||
expect(
|
||||
getSignInDestination(
|
||||
{ scenario, onboarding_step: "candidate_consents" },
|
||||
{ returnTo: "support", pathname: "https://example.test/", scenario: "other" },
|
||||
),
|
||||
).toBe(paths[scenario].supportCases);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
null,
|
||||
undefined,
|
||||
"support",
|
||||
[],
|
||||
{ returnTo: "/support" },
|
||||
{ returnTo: "https://example.test/" },
|
||||
{ returnTo: "//example.test/" },
|
||||
{ pathname: "/support" },
|
||||
{ returnTo: { pathname: "/support" } },
|
||||
])("ignores an unrecognized return intent: %j", (state) => {
|
||||
expect(
|
||||
getSignInDestination({ scenario: "candidate", onboarding_step: "candidate_profile" }, state),
|
||||
).toBe(paths.candidate.profile);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { getOnboardingDestination } from "../../../entities/session";
|
||||
import type { Account } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
|
||||
/** Only a fixed support intent can override the saved onboarding step. */
|
||||
export function getSignInDestination(
|
||||
account: Pick<Account, "scenario" | "onboarding_step">,
|
||||
state: unknown,
|
||||
): string {
|
||||
if (
|
||||
typeof state === "object" &&
|
||||
state !== null &&
|
||||
!Array.isArray(state) &&
|
||||
"returnTo" in state &&
|
||||
state.returnTo === "support"
|
||||
) {
|
||||
return account.scenario === "candidate"
|
||||
? paths.candidate.supportCases
|
||||
: paths.employer.supportCases;
|
||||
}
|
||||
return getOnboardingDestination(account);
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { useLogin } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { EmailAddress } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { getOnboardingDestination } from "../../../entities/session";
|
||||
import { Button, TextLink } from "../../../shared/ui";
|
||||
import { establishSession } from "../model/establish-session";
|
||||
import { getSignInDestination } from "../model/sign-in-destination";
|
||||
import styles from "./sign-in-form.module.css";
|
||||
|
||||
type SignInFormProps = {
|
||||
@@ -19,6 +19,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
const id = useId();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const login = useLogin({ mutation: { gcTime: 0 } });
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -46,7 +47,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
establishSession(queryClient, session);
|
||||
setPassword("");
|
||||
onSignedIn();
|
||||
await navigate(getOnboardingDestination(session.account), { replace: true });
|
||||
await navigate(getSignInDestination(session.account, location.state), { replace: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof ApiRequestError && error.code === "email_not_verified") {
|
||||
onUnverified(email);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export { AssessmentAttemptPage } from "./ui/assessment-attempt-page";
|
||||
export { AssessmentPage } from "./ui/assessment-page";
|
||||
@@ -0,0 +1,102 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.resume p,
|
||||
.finalize p,
|
||||
.info p,
|
||||
.result p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.item {
|
||||
gap: var(--space-4);
|
||||
border-color: var(--color-border-strong);
|
||||
}
|
||||
|
||||
.item-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.item-heading h2,
|
||||
.result h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.item-heading span {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.prompt {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.info {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.result {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.demo-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.result-error {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.back-link {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
finalizeMyAssessmentAttempt,
|
||||
startMyAssessmentAttemptSession,
|
||||
} from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
AssessmentAttempt,
|
||||
AssessmentFinalization,
|
||||
Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
assessmentQueryKeys,
|
||||
assessmentResultSummary,
|
||||
assessmentSessionMatches,
|
||||
gradeLabels,
|
||||
isOutcomeAmbiguous,
|
||||
isCurrentAssessmentSession,
|
||||
methodLabel,
|
||||
parseAssessmentAttemptResponse,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
useAssessmentAttempt,
|
||||
useAssessmentResult,
|
||||
} from "../../../entities/assessment";
|
||||
import {
|
||||
AnswerForm,
|
||||
buildAnswerSubmission,
|
||||
newIdempotencyKey,
|
||||
submitPendingAnswerCommand,
|
||||
} from "../../../features/answer-assessment";
|
||||
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
|
||||
import attemptStyles from "./assessment-attempt-page.module.css";
|
||||
|
||||
type PendingFinalize = { key: string; body: AssessmentFinalization };
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
|
||||
}
|
||||
|
||||
function isTerminal(attempt: AssessmentAttempt): boolean {
|
||||
return ["completed", "expired", "insufficient_bank"].includes(attempt.state);
|
||||
}
|
||||
|
||||
function attemptName(attempt: AssessmentAttempt): string {
|
||||
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
|
||||
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
|
||||
}
|
||||
|
||||
function answerErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiRequestError && error.status === 0) {
|
||||
return "Не удалось связаться с сервером. Повторите отправку того же ответа.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status >= 500) {
|
||||
return "Сервер не подтвердил ответ. Повторите отправку того же ответа.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 429) {
|
||||
return error.retryAfterSeconds
|
||||
? `Слишком много запросов. Повторите через ${error.retryAfterSeconds} сек.`
|
||||
: "Слишком много запросов. Повторите позже.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
return "Попытка изменилась в другом окне. Проверьте актуальное задание и отправьте ответ еще раз.";
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 400) {
|
||||
return "Сервер не принял этот формат ответа. Проверьте введенные данные.";
|
||||
}
|
||||
return "Не удалось отправить ответ. Проверьте соединение и повторите попытку.";
|
||||
}
|
||||
|
||||
export function AssessmentAttemptPage() {
|
||||
const { attemptId = "" } = useParams();
|
||||
return <AssessmentAttemptContent key={attemptId} attemptId={attemptId} />;
|
||||
}
|
||||
|
||||
function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.data;
|
||||
const actorReady = Boolean(
|
||||
actor &&
|
||||
actor.account.scenario === "candidate" &&
|
||||
isCurrentAssessmentSession(queryClient, actor),
|
||||
);
|
||||
const attemptQuery = useAssessmentAttempt({ actor, attemptId, enabled: actorReady, queryClient });
|
||||
const attempt = attemptQuery.data;
|
||||
const resultQuery = useAssessmentResult({
|
||||
actor,
|
||||
attemptId,
|
||||
enabled: actorReady && Boolean(attempt && isTerminal(attempt)),
|
||||
queryClient,
|
||||
});
|
||||
const [workReady, setWorkReady] = useState(false);
|
||||
const [resumeBusy, setResumeBusy] = useState(false);
|
||||
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
|
||||
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
|
||||
const [answerBusy, setAnswerBusy] = useState(false);
|
||||
const [answerError, setAnswerError] = useState<string | null>(null);
|
||||
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
|
||||
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
|
||||
const [finalizeBusy, setFinalizeBusy] = useState(false);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const requestInFlight = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
|
||||
const previous = previousActor.current;
|
||||
if (previous && (!next || previous.accountId !== next.accountId)) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setPendingResume(null);
|
||||
setPendingAnswer(null);
|
||||
setPendingFinalize(null);
|
||||
setWorkReady(false);
|
||||
setPageError(null);
|
||||
setAnswerError(null);
|
||||
setAccessDenied(false);
|
||||
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setWorkReady(false);
|
||||
setPageError("Проверка входа обновлена. Продолжите попытку еще раз.");
|
||||
}
|
||||
previousActor.current = next;
|
||||
}, [actor, actorReady, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (attemptQuery.isError && isAccessLoss(attemptQuery.error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
});
|
||||
}
|
||||
if (resultQuery.isError && isAccessLoss(resultQuery.error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
});
|
||||
}
|
||||
}, [
|
||||
actor,
|
||||
attemptQuery.error,
|
||||
attemptQuery.isError,
|
||||
queryClient,
|
||||
resultQuery.error,
|
||||
resultQuery.isError,
|
||||
]);
|
||||
|
||||
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
|
||||
const key = getGetCurrentSessionQueryKey();
|
||||
const captured = queryClient.getQueryData<Session>(key);
|
||||
if (!assessmentSessionMatches(queryClient.getQueryState<Session>(key), currentActor))
|
||||
return false;
|
||||
const refreshed = await session.refetch();
|
||||
const latest = queryClient.getQueryData<Session>(key);
|
||||
const state = queryClient.getQueryState<Session>(key);
|
||||
if (
|
||||
!captured ||
|
||||
refreshed.isError ||
|
||||
!refreshed.data ||
|
||||
state?.status !== "success" ||
|
||||
latest?.account.id !== currentActor.account.id ||
|
||||
latest.csrf_token !== refreshed.data.csrf_token
|
||||
) {
|
||||
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (captured.csrf_token !== currentActor.csrf_token) return false;
|
||||
setAnswerError("Проверка входа обновлена. Черновик сохранен, повторите отправку.");
|
||||
return true;
|
||||
}
|
||||
|
||||
async function resumeWork() {
|
||||
if (
|
||||
!actor ||
|
||||
!attempt ||
|
||||
!isCurrentAssessmentSession(queryClient, actor) ||
|
||||
requestInFlight.current
|
||||
)
|
||||
return;
|
||||
const command = pendingResume ?? { key: newIdempotencyKey(), version: attempt.version };
|
||||
if (!pendingResume) setPendingResume(command);
|
||||
requestInFlight.current = true;
|
||||
setResumeBusy(true);
|
||||
setPageError(null);
|
||||
try {
|
||||
const resumedResponse = await startMyAssessmentAttemptSession(
|
||||
attempt.id,
|
||||
{ expected_version: command.version },
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": actor.csrf_token } },
|
||||
);
|
||||
const resumed = parseAssessmentAttemptResponse(resumedResponse);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), resumed);
|
||||
setPendingResume(null);
|
||||
setWorkReady(true);
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(actor);
|
||||
} else if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
} else if (isOutcomeAmbiguous(error)) {
|
||||
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
|
||||
} else {
|
||||
setPendingResume(null);
|
||||
setPageError("Не удалось продолжить попытку. Обновите состояние и повторите действие.");
|
||||
await attemptQuery.refetch();
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setResumeBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function refetchAttempt(): Promise<AssessmentAttempt | null> {
|
||||
const refreshed = await attemptQuery.refetch();
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || refreshed.isError) return null;
|
||||
return refreshed.data ?? null;
|
||||
}
|
||||
|
||||
async function sendAnswer(draft: AnswerDraft) {
|
||||
if (!actor || !attempt || !attempt.current_item || !workReady || requestInFlight.current)
|
||||
return;
|
||||
const built = buildAnswerSubmission(attempt, attempt.current_item, draft);
|
||||
if (!built.ok) {
|
||||
setAnswerError(built.message);
|
||||
return;
|
||||
}
|
||||
const command: PendingAnswerCommand = {
|
||||
key: newIdempotencyKey(),
|
||||
body: built.body,
|
||||
itemId: attempt.current_item.id,
|
||||
};
|
||||
await sendPendingAnswer(command, actor, attempt.id);
|
||||
}
|
||||
|
||||
async function retryAnswer() {
|
||||
if (!actor || !attempt || !pendingAnswer || requestInFlight.current) return;
|
||||
await sendPendingAnswer(pendingAnswer, actor, attempt.id);
|
||||
}
|
||||
|
||||
async function sendPendingAnswer(
|
||||
command: PendingAnswerCommand,
|
||||
currentActor: Session,
|
||||
currentAttemptId: string,
|
||||
) {
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
setPendingAnswer(command);
|
||||
requestInFlight.current = true;
|
||||
setAnswerBusy(true);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
try {
|
||||
const outcome = await submitPendingAnswerCommand(
|
||||
command,
|
||||
currentAttemptId,
|
||||
currentActor.csrf_token,
|
||||
);
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
if (outcome.kind === "retry") {
|
||||
setPendingAnswer(outcome.command);
|
||||
setAnswerError(answerErrorMessage(outcome.error));
|
||||
return;
|
||||
}
|
||||
if (outcome.kind === "rejected") throw outcome.error;
|
||||
const saved = outcome.attempt;
|
||||
const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId);
|
||||
queryClient.setQueryData<AssessmentAttempt>(key, (current) =>
|
||||
current && current.version > saved.version ? current : saved,
|
||||
);
|
||||
void queryClient.invalidateQueries({ queryKey: key });
|
||||
setPendingAnswer(null);
|
||||
setAnswerError(null);
|
||||
setAnswerNeedsReview(false);
|
||||
setWorkReady(true);
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(currentActor);
|
||||
return;
|
||||
}
|
||||
if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setPendingAnswer(null);
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
return;
|
||||
}
|
||||
if (isOutcomeAmbiguous(error)) {
|
||||
setAnswerError(answerErrorMessage(error));
|
||||
return;
|
||||
}
|
||||
setPendingAnswer(null);
|
||||
setAnswerError(answerErrorMessage(error));
|
||||
if (error instanceof ApiRequestError && error.status === 412) {
|
||||
const latest = await refetchAttempt();
|
||||
setAnswerNeedsReview(Boolean(latest?.current_item?.id === command.itemId));
|
||||
if (latest?.current_item?.id !== command.itemId) {
|
||||
setAnswerError("Попытка изменилась в другом окне. Показано текущее задание с сервера.");
|
||||
}
|
||||
} else if (error instanceof ApiRequestError && error.status === 409) {
|
||||
const latest = await refetchAttempt();
|
||||
if (latest) {
|
||||
queryClient.setQueryData(
|
||||
assessmentQueryKeys.attempt(currentActor, currentAttemptId),
|
||||
latest,
|
||||
);
|
||||
}
|
||||
setWorkReady(false);
|
||||
setPageError(
|
||||
"Сеанс работы завершился или состояние попытки изменилось. Продолжите попытку заново.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setAnswerBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function finalizeAttempt() {
|
||||
if (!actor || !attempt || !workReady || requestInFlight.current) return;
|
||||
const body: AssessmentFinalization = { expected_version: attempt.version };
|
||||
const command = pendingFinalize ?? { key: newIdempotencyKey(), body };
|
||||
if (!pendingFinalize) setPendingFinalize(command);
|
||||
requestInFlight.current = true;
|
||||
setFinalizeBusy(true);
|
||||
setPageError(null);
|
||||
try {
|
||||
const finalizedResponse = await finalizeMyAssessmentAttempt(
|
||||
attempt.id,
|
||||
command.body,
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": actor.csrf_token } },
|
||||
);
|
||||
const finalized = parseAssessmentAttemptResponse(finalizedResponse);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), finalized);
|
||||
setPendingFinalize(null);
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: assessmentQueryKeys.result(actor, attempt.id),
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
await refreshSessionForActor(actor);
|
||||
} else if (isAccessLoss(error)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
setWorkReady(false);
|
||||
} else if (isOutcomeAmbiguous(error)) {
|
||||
setPageError("Сервер не подтвердил завершение. Повторите запрос с тем же ключом.");
|
||||
} else {
|
||||
setPendingFinalize(null);
|
||||
setPageError("Сервер пока не завершил попытку. Обновите состояние и повторите действие.");
|
||||
const latest = await refetchAttempt();
|
||||
if (latest)
|
||||
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), latest);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setFinalizeBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Попытка недоступна"
|
||||
description="Сервер не подтвердил доступ к этой попытке. Проверьте вход в кабинет кандидата."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!attemptId) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ErrorState
|
||||
error={new Error("The attempt identifier is missing.")}
|
||||
title="Не удалось открыть попытку"
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (attemptQuery.isPending && !attempt) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Загружаем сохраненную попытку..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (attemptQuery.isError || !attempt) {
|
||||
if (isAccessLoss(attemptQuery.error)) {
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={attemptQuery.error}
|
||||
title="Попытка недоступна"
|
||||
description="Сервер не подтвердил доступ к этой попытке."
|
||||
action={<ButtonLink to={paths.candidate.assessment}>К списку проверок</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
|
||||
<ErrorState
|
||||
error={attemptQuery.error}
|
||||
isRetrying={attemptQuery.isRefetching}
|
||||
onRetry={() => void attemptQuery.refetch()}
|
||||
title="Не удалось загрузить попытку"
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
const currentItem = attempt.current_item;
|
||||
const practicePending = attempt.practices.some((practice) => practice.status === "pending");
|
||||
const pendingAnswerNeedsReplay = Boolean(
|
||||
pendingAnswer && pendingAnswer.itemId !== currentItem?.id,
|
||||
);
|
||||
const canFinalize =
|
||||
attempt.state === "ready_to_finalize" ||
|
||||
(attempt.state === "additional_practice_pending" &&
|
||||
!currentItem &&
|
||||
attempt.practices.some(
|
||||
(practice) =>
|
||||
practice.kind === "additional" && ["not_started", "failed"].includes(practice.status),
|
||||
));
|
||||
const terminal = isTerminal(attempt);
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead={
|
||||
attempt.kind === "demo_express"
|
||||
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
|
||||
: undefined
|
||||
}
|
||||
width="wide"
|
||||
>
|
||||
<div className={attemptStyles.layout}>
|
||||
<Section
|
||||
title={attemptName(attempt)}
|
||||
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`}
|
||||
>
|
||||
<div className={attemptStyles.meta}>
|
||||
<span>
|
||||
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items}
|
||||
</span>
|
||||
<span>
|
||||
Срок до:{" "}
|
||||
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
|
||||
new Date(attempt.expires_at),
|
||||
)}
|
||||
</span>
|
||||
{attempt.sessions ? (
|
||||
<span>
|
||||
Сеанс {attempt.sessions.used} из {attempt.sessions.max}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{pageError ? (
|
||||
<p className={attemptStyles.error} role="alert">
|
||||
{pageError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!workReady && !terminal ? (
|
||||
<div className={attemptStyles.resume}>
|
||||
<p>
|
||||
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
|
||||
меняются, а ответ не отправляется повторно автоматически.
|
||||
</p>
|
||||
<Button isBusy={resumeBusy} onClick={() => void resumeWork()}>
|
||||
{resumeBusy
|
||||
? "Проверяем попытку..."
|
||||
: pendingResume
|
||||
? "Повторить продолжение"
|
||||
: "Начать или продолжить"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady && pendingAnswerNeedsReplay && !terminal ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
|
||||
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
|
||||
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
currentItem &&
|
||||
!terminal &&
|
||||
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
|
||||
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
|
||||
<div className={attemptStyles["item-heading"]}>
|
||||
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2>
|
||||
<span>
|
||||
{currentItem.sequence} из {attempt.progress.max_items}
|
||||
</span>
|
||||
</div>
|
||||
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
|
||||
<AnswerForm
|
||||
key={currentItem.id}
|
||||
item={currentItem}
|
||||
isSaving={answerBusy}
|
||||
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
|
||||
errorMessage={answerError}
|
||||
onSubmit={(draft) => void sendAnswer(draft)}
|
||||
onRetry={() => void retryAnswer()}
|
||||
/>
|
||||
{answerNeedsReview ? (
|
||||
<p className={attemptStyles.info} role="status">
|
||||
Черновик остался в форме. Проверьте его и отправьте для актуальной версии попытки.
|
||||
</p>
|
||||
) : null}
|
||||
</article>
|
||||
) : null}
|
||||
|
||||
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
|
||||
<p className={attemptStyles.info} role="status">
|
||||
Решение передано на проверку. Результат появится после ответа сервера; страница
|
||||
обновляет статус автоматически.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
!currentItem &&
|
||||
!practicePending &&
|
||||
canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.finalize}>
|
||||
<p>
|
||||
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
|
||||
</p>
|
||||
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
|
||||
{finalizeBusy
|
||||
? "Запрашиваем решение..."
|
||||
: pendingFinalize
|
||||
? "Повторить завершение"
|
||||
: "Завершить проверку"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{workReady &&
|
||||
!currentItem &&
|
||||
!practicePending &&
|
||||
!canFinalize &&
|
||||
!terminal &&
|
||||
!pendingAnswerNeedsReplay ? (
|
||||
<div className={attemptStyles.info} role="status">
|
||||
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={attemptQuery.isRefetching}
|
||||
onClick={() => void attemptQuery.refetch()}
|
||||
>
|
||||
Обновить попытку
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
|
||||
</Section>
|
||||
<div className={attemptStyles["back-link"]}>
|
||||
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
|
||||
К доступным проверкам
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
|
||||
if (resultQuery.isPending && !resultQuery.data) {
|
||||
return <LoadingState label="Загружаем сохраненный результат..." />;
|
||||
}
|
||||
if (resultQuery.isError || !resultQuery.data) {
|
||||
return (
|
||||
<div className={attemptStyles["result-error"]}>
|
||||
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
|
||||
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={resultQuery.error}
|
||||
isRetrying={resultQuery.isRefetching}
|
||||
onRetry={() => void resultQuery.refetch()}
|
||||
title="Не удалось загрузить результат"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={resultQuery.isRefetching}
|
||||
onClick={() => void resultQuery.refetch()}
|
||||
>
|
||||
Обновить результат
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const result = resultQuery.data;
|
||||
const summary = assessmentResultSummary(result);
|
||||
return (
|
||||
<div className={attemptStyles.result} role="status" aria-live="polite">
|
||||
<h2>Результат с сервера</h2>
|
||||
<p>{summary.text}</p>
|
||||
{summary.reason ? <p>{summary.reason}</p> : null}
|
||||
{summary.isDemonstration ? (
|
||||
<p className={attemptStyles["demo-label"]}>
|
||||
Только демонстрация. Подтвержденный грейд не присваивается.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type {
|
||||
AssessmentAttemptCreate,
|
||||
GradeCode,
|
||||
SpecializationCode,
|
||||
TaskLanguage,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment";
|
||||
import { parseAssessmentAttemptResponse } from "../../../entities/assessment";
|
||||
|
||||
export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
|
||||
|
||||
export function buildRootAttemptCreate(
|
||||
specialization: SpecializationCode,
|
||||
grade: GradeCode,
|
||||
savedLanguages: readonly TaskLanguage[],
|
||||
selectedLanguage: TaskLanguage | "",
|
||||
): AssessmentAttemptCreate | null {
|
||||
let taskLanguage: TaskLanguage | null = null;
|
||||
|
||||
if (savedLanguages.length === 1) {
|
||||
taskLanguage = savedLanguages[0] ?? null;
|
||||
} else if (savedLanguages.length > 1) {
|
||||
if (!selectedLanguage || !savedLanguages.includes(selectedLanguage)) return null;
|
||||
taskLanguage = selectedLanguage;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "root",
|
||||
specialization,
|
||||
target_grade: grade,
|
||||
task_language: taskLanguage,
|
||||
};
|
||||
}
|
||||
|
||||
export function preservePendingCreate(
|
||||
pending: PendingCreate | null,
|
||||
body: AssessmentAttemptCreate | null,
|
||||
keyFactory: () => string,
|
||||
): PendingCreate | null {
|
||||
return pending ?? (body ? { key: keyFactory(), body } : null);
|
||||
}
|
||||
|
||||
export function submitPendingAttempt(command: PendingCreate, csrfToken: string) {
|
||||
return createMyAssessmentAttempt(
|
||||
command.body,
|
||||
{ "Idempotency-Key": command.key },
|
||||
{ headers: { "X-CSRF-Token": csrfToken } },
|
||||
).then((response) => parseAssessmentAttemptResponse(response, 201));
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
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 select:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.language-note,
|
||||
.language-availability {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.language-note {
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.language-availability {
|
||||
max-width: 72ch;
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express,
|
||||
.notice {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.availability p,
|
||||
.express p,
|
||||
.notice p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.status-row [data-state="available"] {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.limits {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.limits div {
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
background: var(--color-canvas);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.limits dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.limits dd {
|
||||
margin: var(--space-1) 0 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.notice {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.notice h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-m);
|
||||
}
|
||||
|
||||
.notice p,
|
||||
.express p,
|
||||
.pending {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.pending {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.controls,
|
||||
.limits {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.availability,
|
||||
.express,
|
||||
.notice {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { AssessmentPolicyParameters, TaskLanguageControl } from "./assessment-page";
|
||||
import {
|
||||
buildRootAttemptCreate,
|
||||
preservePendingCreate,
|
||||
submitPendingAttempt,
|
||||
} from "./assessment-page.model";
|
||||
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe("assessment task language selection", () => {
|
||||
it("sends null when the saved questionnaire has no language", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", [], "")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the only saved language without an ambiguous default", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python"], "")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "python",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires an explicit choice when the questionnaire has multiple languages", () => {
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "")).toBeNull();
|
||||
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "go")).toEqual({
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the selected second language and idempotency key on an exact retry", () => {
|
||||
const body = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
|
||||
expect(body).not.toBeNull();
|
||||
const keyFactory = vi.fn(() => "original-key");
|
||||
const pending = preservePendingCreate(null, body, keyFactory);
|
||||
const retryBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "python");
|
||||
const retried = preservePendingCreate(pending, retryBody, () => "new-key");
|
||||
|
||||
expect(pending?.body).toMatchObject({ kind: "root", task_language: "go" });
|
||||
expect(retried).toBe(pending);
|
||||
expect(retried?.key).toBe("original-key");
|
||||
expect(retried?.body).toEqual(body);
|
||||
expect(keyFactory).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("posts the selected second language and replays the same request after an ambiguous response", async () => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
const requests: Array<{ body: unknown; key: string | null; csrf: string | null }> = [];
|
||||
server.use(
|
||||
http.post("http://localhost/api/v1/me/assessment-attempts", async ({ request }) => {
|
||||
requests.push({
|
||||
body: await request.json(),
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
csrf: request.headers.get("X-CSRF-Token"),
|
||||
});
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: "urn:lincodex:problem:internal",
|
||||
title: "Internal error",
|
||||
status: 500,
|
||||
code: "internal",
|
||||
},
|
||||
{ status: 500, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const keyFactory = vi.fn(() => "retry-key");
|
||||
const firstBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
|
||||
const pending = preservePendingCreate(null, firstBody, keyFactory);
|
||||
expect(pending).not.toBeNull();
|
||||
await expect(submitPendingAttempt(pending!, "csrf-token")).rejects.toMatchObject({
|
||||
status: 500,
|
||||
});
|
||||
|
||||
const changedSelection = buildRootAttemptCreate(
|
||||
"backend",
|
||||
"junior",
|
||||
["python", "go"],
|
||||
"python",
|
||||
);
|
||||
const retry = preservePendingCreate(pending, changedSelection, keyFactory);
|
||||
await expect(submitPendingAttempt(retry!, "csrf-token")).rejects.toMatchObject({
|
||||
status: 500,
|
||||
});
|
||||
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
body: {
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
},
|
||||
key: "retry-key",
|
||||
csrf: "csrf-token",
|
||||
},
|
||||
{
|
||||
body: {
|
||||
kind: "root",
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
task_language: "go",
|
||||
},
|
||||
key: "retry-key",
|
||||
csrf: "csrf-token",
|
||||
},
|
||||
]);
|
||||
expect(retry).toBe(pending);
|
||||
expect(keyFactory).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TaskLanguageControl", () => {
|
||||
it("shows the single saved language without requiring another choice", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TaskLanguageControl languages={["go"]} value="" disabled={false} onChange={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Язык задания из анкеты:");
|
||||
expect(html).toContain("Go");
|
||||
expect(html).not.toContain("<select");
|
||||
});
|
||||
|
||||
it("requires a visible choice when both languages are saved", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<TaskLanguageControl
|
||||
languages={["python", "go"]}
|
||||
value="go"
|
||||
disabled={false}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Язык задания");
|
||||
expect(html).toContain('value="python"');
|
||||
expect(html).toContain('value="go" selected');
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssessmentPolicyParameters", () => {
|
||||
const grade = {
|
||||
grade: "junior",
|
||||
status: "active_attempt",
|
||||
mode: "adaptive",
|
||||
available_at: null,
|
||||
time_limit_seconds: 900,
|
||||
max_sessions: 1,
|
||||
max_items: 12,
|
||||
practice_required: true,
|
||||
} as const;
|
||||
|
||||
it("does not present today's policy limits as settings for a pinned attempt", () => {
|
||||
const html = renderToStaticMarkup(<AssessmentPolicyParameters grade={grade} />);
|
||||
|
||||
expect(html).toBe("");
|
||||
});
|
||||
|
||||
it("shows current policy parameters before a new attempt", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<AssessmentPolicyParameters grade={{ ...grade, status: "available" }} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Метод:");
|
||||
expect(html).toContain("Лимит времени");
|
||||
expect(html).toContain("Заданий");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,568 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type {
|
||||
AssessmentAttemptCreate,
|
||||
AssessmentGradeAvailability,
|
||||
GradeCode,
|
||||
Session,
|
||||
SpecializationCode,
|
||||
TaskLanguage,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
assessmentSessionMatches,
|
||||
gradeLabels,
|
||||
isOutcomeAmbiguous,
|
||||
isCurrentAssessmentSession,
|
||||
methodLabel,
|
||||
removeAssessmentQueries,
|
||||
removeAssessmentQueriesForSessionChange,
|
||||
selectedSpecialization,
|
||||
specializationLabels,
|
||||
useAssessmentAvailability,
|
||||
useAssessmentQuestionnaire,
|
||||
} from "../../../entities/assessment";
|
||||
import { newIdempotencyKey } from "../../../features/answer-assessment";
|
||||
import {
|
||||
buildRootAttemptCreate,
|
||||
preservePendingCreate,
|
||||
submitPendingAttempt,
|
||||
type PendingCreate,
|
||||
} from "./assessment-page.model";
|
||||
import styles from "./assessment-page.module.css";
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
|
||||
}
|
||||
|
||||
function requiresC3(error: ApiRequestError): boolean {
|
||||
return (
|
||||
error.code === "state_conflict" &&
|
||||
error.fieldErrors.some((field) => field.code === "consent_required")
|
||||
);
|
||||
}
|
||||
|
||||
function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
|
||||
switch (grade.status) {
|
||||
case "available":
|
||||
return "Уровень открыт для начала. Список доступности не разделяет варианты по языку; сервер проверит задания выбранного языка при создании попытки.";
|
||||
case "active_attempt":
|
||||
return "Продолжите сохраненную попытку по ссылке ниже. Ее язык и параметры закреплены и отображаются внутри попытки.";
|
||||
case "cooldown":
|
||||
return grade.available_at
|
||||
? `Следующая попытка будет доступна ${formatDate(grade.available_at)}.`
|
||||
: "Следующая попытка пока недоступна.";
|
||||
case "insufficient_bank":
|
||||
return "Набор заданий пока не подготовлен. Система не будет повторять уже пройденные задания.";
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function formatTimeLimit(seconds: number | null): string {
|
||||
if (seconds === null) return "не задано";
|
||||
const minutes = Math.ceil(seconds / 60);
|
||||
return `${minutes} мин.`;
|
||||
}
|
||||
|
||||
function taskLanguageLabel(language: TaskLanguage): string {
|
||||
return language === "go" ? "Go" : "Python";
|
||||
}
|
||||
|
||||
export function TaskLanguageControl({
|
||||
languages,
|
||||
value,
|
||||
disabled,
|
||||
onChange,
|
||||
}: {
|
||||
languages: readonly TaskLanguage[];
|
||||
value: TaskLanguage | "";
|
||||
disabled: boolean;
|
||||
onChange: (language: TaskLanguage | "") => void;
|
||||
}) {
|
||||
if (languages.length === 0) {
|
||||
return (
|
||||
<p className={styles["language-note"]}>
|
||||
В сохраненной анкете нет выбранного языка. Попытка отправится без языка, а сервер проверит
|
||||
доступность заданий при создании.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (languages.length === 1) {
|
||||
return (
|
||||
<p className={styles["language-note"]}>
|
||||
Язык задания из анкеты: <strong>{taskLanguageLabel(languages[0]!)}</strong>.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<label className={styles.field}>
|
||||
<span>Язык задания</span>
|
||||
<select
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onChange={(event) => onChange(event.currentTarget.value as TaskLanguage | "")}
|
||||
>
|
||||
<option value="">Выберите язык</option>
|
||||
{languages.map((language) => (
|
||||
<option key={language} value={language}>
|
||||
{taskLanguageLabel(language)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function AssessmentPolicyParameters({ grade }: { grade: AssessmentGradeAvailability }) {
|
||||
if (grade.status === "active_attempt") return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{grade.mode ? <p>Метод: {methodLabel(grade.mode)}.</p> : null}
|
||||
<dl className={styles.limits}>
|
||||
<div>
|
||||
<dt>Лимит времени</dt>
|
||||
<dd>{formatTimeLimit(grade.time_limit_seconds)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Попыток работы</dt>
|
||||
<dd>{grade.max_sessions ?? "не задано"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Заданий</dt>
|
||||
<dd>{grade.max_items ?? "не задано"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Практика кода</dt>
|
||||
<dd>
|
||||
{grade.practice_required === null
|
||||
? "не задано"
|
||||
: grade.practice_required
|
||||
? "включена"
|
||||
: "не требуется"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AssessmentSignalsNotice() {
|
||||
return (
|
||||
<aside className={styles.notice} aria-labelledby="assessment-signals-title">
|
||||
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
|
||||
<p>
|
||||
Сохраняются время ответов и технические события: смена вкладки, выход из полноэкранного
|
||||
режима и размер операций копирования или вставки. Содержимое ответов и буфера не
|
||||
отправляется как сигнал. Камера, микрофон и запись экрана не используются.
|
||||
</p>
|
||||
<p>Сигналы помогают назначить ручную перепроверку и сами по себе не меняют результат.</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function AssessmentPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.data;
|
||||
const actorReady = Boolean(
|
||||
actor &&
|
||||
actor.account.scenario === "candidate" &&
|
||||
isCurrentAssessmentSession(queryClient, actor),
|
||||
);
|
||||
const availability = useAssessmentAvailability({ actor, enabled: actorReady, queryClient });
|
||||
const questionnaire = useAssessmentQuestionnaire({ actor, enabled: actorReady, queryClient });
|
||||
const [selection, setSelection] = useState<{
|
||||
specialization: SpecializationCode | "";
|
||||
grade: GradeCode | "";
|
||||
}>({ specialization: "", grade: "" });
|
||||
const [selectedTaskLanguage, setSelectedTaskLanguage] = useState<TaskLanguage | "">("");
|
||||
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
|
||||
const [createBusy, setCreateBusy] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [c3Required, setC3Required] = useState(false);
|
||||
const [accessDenied, setAccessDenied] = useState(false);
|
||||
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const requestInFlight = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
|
||||
const previous = previousActor.current;
|
||||
if (previous && (!next || previous.accountId !== next.accountId)) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setPendingCreate(null);
|
||||
setSelectedTaskLanguage("");
|
||||
setFormError(null);
|
||||
setC3Required(false);
|
||||
setAccessDenied(false);
|
||||
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
|
||||
removeAssessmentQueriesForSessionChange(queryClient);
|
||||
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
|
||||
}
|
||||
previousActor.current = next;
|
||||
}, [actor, actorReady, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
(availability.isError && isAccessLoss(availability.error)) ||
|
||||
(questionnaire.isError && isAccessLoss(questionnaire.error))
|
||||
) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
queueMicrotask(() => {
|
||||
if (isCurrentAssessmentSession(queryClient, actor)) setAccessDenied(true);
|
||||
});
|
||||
}
|
||||
}, [
|
||||
actor,
|
||||
availability.error,
|
||||
availability.isError,
|
||||
queryClient,
|
||||
questionnaire.error,
|
||||
questionnaire.isError,
|
||||
]);
|
||||
|
||||
const data = availability.data;
|
||||
const firstSpecialization = data?.specializations[0]?.specialization ?? "";
|
||||
const selectedCode = data?.specializations.some(
|
||||
(item) => item.specialization === selection.specialization,
|
||||
)
|
||||
? selection.specialization
|
||||
: firstSpecialization;
|
||||
const specialization = data ? selectedSpecialization(data, selectedCode || undefined) : undefined;
|
||||
const questionnaireSpecialization = questionnaire.data?.specializations.find(
|
||||
(item) => item.specialization === selectedCode,
|
||||
);
|
||||
const selfGrade = questionnaireSpecialization?.self_assessed_grade ?? "";
|
||||
const firstAvailableGrade =
|
||||
specialization?.grades.find((grade) => grade.status === "available")?.grade ?? "";
|
||||
const selectedGradeCode = specialization?.grades.some((grade) => grade.grade === selection.grade)
|
||||
? selection.grade
|
||||
: selfGrade || firstAvailableGrade || specialization?.grades[0]?.grade || "";
|
||||
const grade = specialization?.grades.find((item) => item.grade === selectedGradeCode);
|
||||
const activeAttemptId = specialization?.active_attempt_id;
|
||||
const savedTaskLanguages = questionnaireSpecialization?.task_languages ?? [];
|
||||
const selectedLanguageIsValid = savedTaskLanguages.includes(selectedTaskLanguage as TaskLanguage);
|
||||
const taskLanguageReady = savedTaskLanguages.length < 2 || selectedLanguageIsValid;
|
||||
|
||||
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
|
||||
const captured = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
if (
|
||||
!assessmentSessionMatches(
|
||||
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
|
||||
currentActor,
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const refreshed = await session.refetch();
|
||||
const latest = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const queryState = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
|
||||
if (
|
||||
!captured ||
|
||||
refreshed.isError ||
|
||||
!refreshed.data ||
|
||||
!latest ||
|
||||
latest.account.id !== currentActor.account.id ||
|
||||
latest.csrf_token !== refreshed.data.csrf_token ||
|
||||
queryState?.status !== "success"
|
||||
) {
|
||||
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (captured.csrf_token !== currentActor.csrf_token) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
async function startAttempt(body?: AssessmentAttemptCreate) {
|
||||
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
|
||||
return;
|
||||
const command = preservePendingCreate(pendingCreate, body ?? null, newIdempotencyKey);
|
||||
if (!command) return;
|
||||
if (!pendingCreate) setPendingCreate(command);
|
||||
requestInFlight.current = true;
|
||||
setCreateBusy(true);
|
||||
setFormError(null);
|
||||
setC3Required(false);
|
||||
try {
|
||||
const created = await submitPendingAttempt(command, actor.csrf_token);
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
setPendingCreate(null);
|
||||
navigate(paths.candidate.assessmentAttempt(created.id));
|
||||
} catch (error: unknown) {
|
||||
if (!isCurrentAssessmentSession(queryClient, actor)) return;
|
||||
if (
|
||||
error instanceof ApiRequestError &&
|
||||
error.status === 403 &&
|
||||
error.code === "csrf_check_failed"
|
||||
) {
|
||||
const refreshed = await refreshSessionForActor(actor);
|
||||
if (refreshed) {
|
||||
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) {
|
||||
removeAssessmentQueries(queryClient);
|
||||
setAccessDenied(true);
|
||||
return;
|
||||
}
|
||||
if (error instanceof ApiRequestError && error.status === 409) {
|
||||
setPendingCreate(null);
|
||||
if (requiresC3(error)) {
|
||||
setC3Required(true);
|
||||
setFormError("Для полной проверки нужно активное согласие C3.");
|
||||
return;
|
||||
}
|
||||
setFormError("Доступность изменилась. Обновите состояние перед началом новой попытки.");
|
||||
await availability.refetch();
|
||||
return;
|
||||
}
|
||||
if (isOutcomeAmbiguous(error)) {
|
||||
setFormError(
|
||||
"Не удалось подтвердить создание попытки. Повторная отправка использует тот же ключ.",
|
||||
);
|
||||
} else {
|
||||
setPendingCreate(null);
|
||||
setFormError(
|
||||
"Сервер отклонил создание попытки. Проверьте доступность и повторите действие.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
requestInFlight.current = false;
|
||||
setCreateBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleStartReal = () => {
|
||||
if (!specialization || !grade || !questionnaireSpecialization) return;
|
||||
const body = buildRootAttemptCreate(
|
||||
specialization.specialization,
|
||||
grade.grade,
|
||||
questionnaireSpecialization.task_languages,
|
||||
selectedTaskLanguage,
|
||||
);
|
||||
if (!body) {
|
||||
setFormError("Выберите язык задания перед началом проверки.");
|
||||
return;
|
||||
}
|
||||
void startAttempt(body);
|
||||
};
|
||||
|
||||
const handleStartExpress = () => {
|
||||
void startAttempt({ kind: "demo_express" });
|
||||
};
|
||||
|
||||
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<ForbiddenState
|
||||
error={session.error}
|
||||
title="Проверка недоступна"
|
||||
description="Войдите в кабинет кандидата и повторите проверку доступа."
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isPending || !actor) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actorReady) {
|
||||
return (
|
||||
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
|
||||
<LoadingState label="Подтверждаем текущий вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page
|
||||
title="Проверка знаний"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<Section
|
||||
title="Доступность проверки"
|
||||
description="Состояние и ограничения загружаются с сервера."
|
||||
>
|
||||
{(availability.isPending && !availability.data) ||
|
||||
(questionnaire.isPending && !questionnaire.data) ? (
|
||||
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
|
||||
) : !data || !questionnaire.data ? (
|
||||
<ErrorState
|
||||
error={!data ? availability.error : questionnaire.error}
|
||||
isRetrying={!data ? availability.isRefetching : questionnaire.isRefetching}
|
||||
onRetry={() => void (!data ? availability.refetch() : questionnaire.refetch())}
|
||||
title="Не удалось загрузить состояние проверки"
|
||||
/>
|
||||
) : data.specializations.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Сначала выберите специализацию"
|
||||
description="Сохраните специализацию в анкете кандидата, чтобы увидеть доступные проверки."
|
||||
action={<ButtonLink to={paths.candidate.questionnaire}>Открыть анкету</ButtonLink>}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.controls}>
|
||||
<label className={styles.field}>
|
||||
<span>Специализация</span>
|
||||
<select
|
||||
value={selectedCode}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onChange={(event) => {
|
||||
setSelection({
|
||||
specialization: event.currentTarget.value as SpecializationCode,
|
||||
grade: "",
|
||||
});
|
||||
setSelectedTaskLanguage("");
|
||||
}}
|
||||
>
|
||||
{data.specializations.map((item) => (
|
||||
<option key={item.specialization} value={item.specialization}>
|
||||
{specializationLabels[item.specialization]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span>Целевой уровень</span>
|
||||
<select
|
||||
value={selectedGradeCode}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onChange={(event) =>
|
||||
setSelection({
|
||||
specialization: selectedCode,
|
||||
grade: event.currentTarget.value as GradeCode,
|
||||
})
|
||||
}
|
||||
>
|
||||
{specialization?.grades.map((item) => (
|
||||
<option key={item.grade} value={item.grade}>
|
||||
{gradeLabels[item.grade]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{questionnaireSpecialization && grade?.status !== "active_attempt" ? (
|
||||
<TaskLanguageControl
|
||||
languages={savedTaskLanguages}
|
||||
value={selectedLanguageIsValid ? selectedTaskLanguage : ""}
|
||||
disabled={Boolean(pendingCreate) || createBusy}
|
||||
onChange={setSelectedTaskLanguage}
|
||||
/>
|
||||
) : null}
|
||||
{grade?.status !== "active_attempt" ? (
|
||||
<p className={styles["language-availability"]}>
|
||||
Доступность уровня не зависит от выбранного языка. При создании сервер проверит,
|
||||
опубликованы ли подходящие задания.
|
||||
</p>
|
||||
) : null}
|
||||
{specialization && grade ? (
|
||||
<div className={styles.availability}>
|
||||
<div className={styles["status-row"]}>
|
||||
<strong>{gradeLabels[grade.grade]}</strong>
|
||||
<span data-state={grade.status}>
|
||||
{grade.status === "available"
|
||||
? "Доступна"
|
||||
: grade.status === "active_attempt"
|
||||
? "Есть попытка"
|
||||
: grade.status === "cooldown"
|
||||
? "Пауза"
|
||||
: "Банк не готов"}
|
||||
</span>
|
||||
</div>
|
||||
<p>{gradeStatusDescription(grade)}</p>
|
||||
<AssessmentPolicyParameters grade={grade} />
|
||||
{activeAttemptId && grade.status === "active_attempt" ? (
|
||||
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
|
||||
Продолжить текущую попытку
|
||||
</ButtonLink>
|
||||
) : grade.status === "available" ? (
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={!taskLanguageReady}
|
||||
onClick={() => {
|
||||
if (taskLanguageReady) handleStartReal();
|
||||
}}
|
||||
>
|
||||
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{pendingCreate ? (
|
||||
<p className={styles.pending} role="status">
|
||||
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
|
||||
ее с тем же ключом.
|
||||
</p>
|
||||
) : null}
|
||||
{formError ? (
|
||||
<p className={styles.error} role="alert">
|
||||
{formError}{" "}
|
||||
{c3Required ? (
|
||||
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<AssessmentSignalsNotice />
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Демонстрационный экспресс-запуск"
|
||||
description="Отдельный учебный режим для знакомства с заданиями."
|
||||
>
|
||||
<div className={styles.express}>
|
||||
<p>
|
||||
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
|
||||
и не влияет на доступность полной проверки.
|
||||
</p>
|
||||
<Button
|
||||
isBusy={createBusy}
|
||||
disabled={Boolean(pendingCreate)}
|
||||
onClick={handleStartExpress}
|
||||
>
|
||||
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
|
||||
</Button>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ConsentManagement } from "../../../features/consent-management";
|
||||
import { Page } from "../../../shared/ui";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, Page, Section } from "../../../shared/ui";
|
||||
|
||||
export function ConsentsPage() {
|
||||
return (
|
||||
@@ -10,6 +11,15 @@ export function ConsentsPage() {
|
||||
width="wide"
|
||||
>
|
||||
<ConsentManagement />
|
||||
<Section title="Ручная оценка">
|
||||
<p>
|
||||
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
|
||||
автоматическую оценку. Запрос не включает согласие обратно.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NeedEditorPage } from "./ui/need-editor-page";
|
||||
@@ -0,0 +1,41 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.content [hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
max-width: 38rem;
|
||||
}
|
||||
|
||||
.selector label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.selector select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
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;
|
||||
}
|
||||
|
||||
.selector select:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
getOrganizationNeed,
|
||||
useGetOrganizationNeed,
|
||||
} from "../../../shared/api/endpoints/need/need";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { MyOrganizationList, Need, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
needQueryKeys,
|
||||
removeAllNeedQueries,
|
||||
removeNeedQueriesForOrganization,
|
||||
removeNeedQueriesForSessionChange,
|
||||
useNeedOrganizationDirectory,
|
||||
} from "../../../entities/need";
|
||||
import { NeedEditor } from "../../../features/edit-need";
|
||||
import styles from "./need-editor-page.module.css";
|
||||
|
||||
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function isOwnerContext(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
session: Session | undefined,
|
||||
pages: readonly MyOrganizationList[],
|
||||
organizationId: string,
|
||||
): boolean {
|
||||
if (!isNeedSessionCurrent(queryClient, session)) return false;
|
||||
return activeNeedOrganizations(pages).some((item) => item.organization.id === organizationId);
|
||||
}
|
||||
|
||||
export function NeedEditorPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { needId } = useParams();
|
||||
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
|
||||
const session = sessionQuery.data;
|
||||
const accountId = session?.account.id;
|
||||
const sessionReady =
|
||||
Boolean(session && session.account.scenario === "employer") &&
|
||||
isNeedSessionCurrent(queryClient, session);
|
||||
const directory = useNeedOrganizationDirectory(session, sessionReady);
|
||||
const directoryData = directory.data;
|
||||
const directoryIsError = directory.isError;
|
||||
const directoryIsFetching = directory.isFetching;
|
||||
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
|
||||
const directoryIsLoading = directory.isLoading;
|
||||
const hasMoreOwnerPages = directory.hasNextPage;
|
||||
const fetchNextOwnerPage = directory.fetchNextPage;
|
||||
const refetchDirectory = directory.refetch;
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const organizationId = searchParams.get("organization_id");
|
||||
const [deniedOrganizationId, setDeniedOrganizationId] = useState<string | null>(null);
|
||||
const reportedAccessError = useRef(false);
|
||||
const previousSessionRef = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const pages = directoryData?.pages ?? emptyDirectoryPages;
|
||||
const organizations = useMemo(() => activeNeedOrganizations(pages), [pages]);
|
||||
const owner = organizations.find((item) => item.organization.id === organizationId);
|
||||
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
|
||||
const directoryFresh =
|
||||
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
|
||||
const deniedKey = accountId && organizationId ? `${accountId}:${organizationId}` : null;
|
||||
const denied = deniedOrganizationId !== null && deniedOrganizationId === deniedKey;
|
||||
const membershipDenied =
|
||||
Boolean(organizationId) && !owner && directoryFresh && !hasMoreOwnerPages;
|
||||
const canReadNeed =
|
||||
needId !== undefined &&
|
||||
organizationId !== null &&
|
||||
directoryFresh &&
|
||||
owner !== undefined &&
|
||||
!denied;
|
||||
const needQuery = useGetOrganizationNeed(organizationId ?? "", needId ?? "", {
|
||||
query: {
|
||||
queryKey: needQueryKeys.detail(
|
||||
accountId ?? "no-session",
|
||||
organizationId ?? "no-organization",
|
||||
needId ?? "new",
|
||||
),
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed before the need request.");
|
||||
}
|
||||
const result = await getOrganizationNeed(organizationId ?? "", needId ?? "", { signal });
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed during the need request.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
enabled: canReadNeed,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
session && sessionReady
|
||||
? { accountId: session.account.id, csrfToken: session.csrf_token }
|
||||
: null;
|
||||
const previous = previousSessionRef.current;
|
||||
if (
|
||||
previous &&
|
||||
(!next || previous.accountId !== next.accountId || previous.csrfToken !== next.csrfToken)
|
||||
) {
|
||||
removeNeedQueriesForSessionChange(queryClient);
|
||||
}
|
||||
previousSessionRef.current = next;
|
||||
}, [queryClient, session, sessionReady]);
|
||||
|
||||
useEffect(() => {
|
||||
if (directoryIsError && isAccessLoss(directory.error)) {
|
||||
removeAllNeedQueries(queryClient);
|
||||
}
|
||||
}, [directory.error, directoryIsError, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
|
||||
if (organizationId) {
|
||||
if (!owner && hasMoreOwnerPages) void fetchNextOwnerPage();
|
||||
return;
|
||||
}
|
||||
if (organizations[0]) {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("organization_id", organizations[0].organization.id);
|
||||
setSearchParams(next, { replace: true });
|
||||
} else if (hasMoreOwnerPages) {
|
||||
void fetchNextOwnerPage();
|
||||
}
|
||||
}, [
|
||||
directoryData,
|
||||
directoryIsError,
|
||||
directoryIsFetchingNextPage,
|
||||
fetchNextOwnerPage,
|
||||
hasMoreOwnerPages,
|
||||
organizations,
|
||||
organizationId,
|
||||
owner,
|
||||
searchParams,
|
||||
sessionReady,
|
||||
setSearchParams,
|
||||
]);
|
||||
|
||||
const markAccessLost = useCallback(
|
||||
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
|
||||
if (
|
||||
!isAccessLoss(error) ||
|
||||
!deniedOrganizationId ||
|
||||
!isNeedSessionCurrent(queryClient, session) ||
|
||||
!accountId
|
||||
)
|
||||
return;
|
||||
setDeniedOrganizationId(`${accountId}:${deniedOrganizationId}`);
|
||||
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
|
||||
await refetchDirectory();
|
||||
},
|
||||
[accountId, queryClient, refetchDirectory, session, setDeniedOrganizationId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needQuery.isError || !isAccessLoss(needQuery.error)) {
|
||||
if (!needQuery.isError) reportedAccessError.current = false;
|
||||
return;
|
||||
}
|
||||
if (reportedAccessError.current) return;
|
||||
reportedAccessError.current = true;
|
||||
void markAccessLost(needQuery.error, organizationId);
|
||||
}, [markAccessLost, needQuery.error, needQuery.isError, organizationId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!membershipDenied || !organizationId) return;
|
||||
removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
}, [membershipDenied, organizationId, queryClient]);
|
||||
|
||||
const isCurrentActor = useCallback(
|
||||
() => isNeedSessionCurrent(queryClient, session),
|
||||
[queryClient, session],
|
||||
);
|
||||
|
||||
const persistCreated = useCallback(
|
||||
async (saved: Need) => {
|
||||
const refreshed = await refetchDirectory();
|
||||
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
|
||||
const refreshedPages = refreshed.data?.pages ?? [];
|
||||
if (!isCurrentActor()) return;
|
||||
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
|
||||
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
|
||||
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
throw new Error("Owner access changed while saving the need.");
|
||||
}
|
||||
const key = needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id);
|
||||
queryClient.setQueryData(key, saved);
|
||||
navigate(paths.employer.need(saved.id, organizationId ?? ""), { replace: true });
|
||||
},
|
||||
[
|
||||
accountId,
|
||||
isCurrentActor,
|
||||
navigate,
|
||||
organizationId,
|
||||
queryClient,
|
||||
refetchDirectory,
|
||||
session,
|
||||
setDeniedOrganizationId,
|
||||
],
|
||||
);
|
||||
|
||||
const persistSaved = useCallback(
|
||||
async (saved: Need) => {
|
||||
const refreshed = await refetchDirectory();
|
||||
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
|
||||
const refreshedPages = refreshed.data?.pages ?? [];
|
||||
if (!isCurrentActor()) return;
|
||||
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
|
||||
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
|
||||
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
|
||||
throw new Error("Owner access changed while saving the need.");
|
||||
}
|
||||
queryClient.setQueryData(
|
||||
needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id),
|
||||
saved,
|
||||
);
|
||||
},
|
||||
[
|
||||
accountId,
|
||||
isCurrentActor,
|
||||
organizationId,
|
||||
queryClient,
|
||||
refetchDirectory,
|
||||
session,
|
||||
setDeniedOrganizationId,
|
||||
],
|
||||
);
|
||||
|
||||
const selectedOrganizationDenied = denied || membershipDenied;
|
||||
const sessionFailure = sessionQuery.isError;
|
||||
const directoryAccessFailure = directory.isError && isAccessLoss(directory.error);
|
||||
const loading =
|
||||
!sessionFailure &&
|
||||
(!sessionReady ||
|
||||
directoryIsLoading ||
|
||||
directoryRefreshing ||
|
||||
!directoryData ||
|
||||
(!owner && hasMoreOwnerPages));
|
||||
const title = needId ? "Потребность" : "Новая потребность";
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={title}
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead={
|
||||
needId
|
||||
? "Подтверждайте требования и следите за полнотой данных."
|
||||
: "Опишите потребность команды без создания вакансии."
|
||||
}
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.content}>
|
||||
{sessionFailure ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directory.isError ? (
|
||||
directoryAccessFailure ? (
|
||||
<ForbiddenState error={directory.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directory.error}
|
||||
isRetrying={directory.isFetching}
|
||||
onRetry={() => void directory.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? <LoadingState label="Проверяем компанию и загружаем потребность..." /> : null}
|
||||
{!sessionFailure && !directory.isError && directory.data ? (
|
||||
<>
|
||||
{directoryRefreshing ? (
|
||||
<LoadingState label="Повторно проверяем права владельца..." />
|
||||
) : null}
|
||||
{organizations.length > 1 ? (
|
||||
<div className={styles.selector} hidden={!directoryFresh}>
|
||||
<label htmlFor="need-editor-organization">Компания</label>
|
||||
<select
|
||||
id="need-editor-organization"
|
||||
value={owner?.organization.id ?? ""}
|
||||
onChange={(event) => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("organization_id", event.currentTarget.value);
|
||||
reportedAccessError.current = false;
|
||||
setDeniedOrganizationId(null);
|
||||
setSearchParams(next);
|
||||
}}
|
||||
>
|
||||
{!owner ? <option value="">Выберите компанию</option> : null}
|
||||
{organizations.map((item) => (
|
||||
<option key={item.organization.id} value={item.organization.id}>
|
||||
{item.organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
{selectedOrganizationDenied ? (
|
||||
<ForbiddenState
|
||||
title="Потребность недоступна"
|
||||
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
|
||||
action={
|
||||
<div className={styles.actions}>
|
||||
{needId ? (
|
||||
<ButtonLink to={paths.employer.needs}>К списку потребностей</ButtonLink>
|
||||
) : null}
|
||||
<Button variant="secondary" onClick={() => void directory.refetch()}>
|
||||
Проверить доступ снова
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{!organizationId && organizations.length === 0 && !directory.hasNextPage ? (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Потребностями в этой версии может управлять только владелец компании."
|
||||
action={
|
||||
<ButtonLink to={paths.employer.company}>Открыть профиль компании</ButtonLink>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{owner && !selectedOrganizationDenied ? (
|
||||
<Section title={needId ? "Редактирование" : "Создание потребности"}>
|
||||
{needId && needQuery.isError && isAccessLoss(needQuery.error) ? (
|
||||
<ForbiddenState
|
||||
title="Потребность недоступна"
|
||||
description="Проверьте права владельца и выбранную компанию."
|
||||
/>
|
||||
) : null}
|
||||
{needId && needQuery.isError && !isAccessLoss(needQuery.error) ? (
|
||||
<ErrorState
|
||||
error={needQuery.error}
|
||||
isRetrying={needQuery.isFetching}
|
||||
onRetry={() => void needQuery.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{needId && needQuery.isLoading ? (
|
||||
<LoadingState label="Загружаем данные потребности..." />
|
||||
) : null}
|
||||
{needId && needQuery.data && needQuery.isFetching ? (
|
||||
<LoadingState label="Проверяем, что доступ владельца действует..." />
|
||||
) : null}
|
||||
<div hidden={!directoryFresh || needQuery.isFetching || needQuery.isError}>
|
||||
{(!needId || needQuery.data) && !needQuery.isError ? (
|
||||
<NeedEditor
|
||||
key={`${accountId ?? "no-session"}:${organizationId}:${needId ?? "new"}`}
|
||||
accountId={accountId ?? "no-session"}
|
||||
organizationId={organizationId ?? ""}
|
||||
session={session!}
|
||||
need={needQuery.data}
|
||||
onCreated={persistCreated}
|
||||
onSaved={persistSaved}
|
||||
onAccessLost={(error) => void markAccessLost(error, organizationId)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NeedListPage } from "./ui/need-list-page";
|
||||
@@ -0,0 +1,139 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: end;
|
||||
justify-content: space-between;
|
||||
margin-block-end: var(--space-5);
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: min(100%, 20rem);
|
||||
}
|
||||
|
||||
.selector label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.selector select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
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;
|
||||
}
|
||||
|
||||
.selector select:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.card-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.card-heading h3 {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.complete,
|
||||
.incomplete {
|
||||
max-width: 100%;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.complete {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.incomplete {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(8rem, max-content) minmax(0, 1fr);
|
||||
gap: var(--space-2) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.missing {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
padding-inline-start: var(--space-5);
|
||||
}
|
||||
|
||||
.load-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-block-start: var(--space-4);
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.toolbar > a {
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.facts dd + dt {
|
||||
padding-block-start: var(--space-2);
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { listOrganizationNeeds } from "../../../shared/api/endpoints/need/need";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { MyOrganizationList, NeedList } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
needListPageSize,
|
||||
needQueryKeys,
|
||||
removeAllNeedQueries,
|
||||
removeNeedQueriesForOrganization,
|
||||
removeNeedQueriesForSessionChange,
|
||||
useNeedOrganizationDirectory,
|
||||
} from "../../../entities/need";
|
||||
import styles from "./need-list-page.module.css";
|
||||
|
||||
type NeedSummary = NeedList["items"][number];
|
||||
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
|
||||
|
||||
const specializationLabels: Readonly<Record<string, string>> = {
|
||||
backend: "Backend",
|
||||
frontend: "Frontend",
|
||||
mobile: "Мобильная разработка",
|
||||
network_engineer: "Сетевые технологии",
|
||||
devops_sre: "DevOps/SRE",
|
||||
data_analyst: "Аналитика данных",
|
||||
ds_ml: "DS/ML",
|
||||
information_security: "Информационная безопасность",
|
||||
qa: "QA",
|
||||
};
|
||||
|
||||
const gradeLabels: Readonly<Record<string, string>> = {
|
||||
intern: "Стажер",
|
||||
junior: "Junior",
|
||||
middle: "Middle",
|
||||
senior: "Senior",
|
||||
};
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function displayDecision<T extends string>(
|
||||
state: { status: "confirmed" | "extracted" | "unknown"; value: T | null },
|
||||
labels: Readonly<Record<string, string>>,
|
||||
): string {
|
||||
if (state.status === "unknown" || state.value === null) return "Не указано";
|
||||
const label = labels[state.value] ?? state.value;
|
||||
return state.status === "extracted" ? `Предложено: ${label}` : label;
|
||||
}
|
||||
|
||||
function NeedCard({ item, organizationId }: { item: NeedSummary; organizationId: string }) {
|
||||
const missingCount = item.readiness.missing_fields.length;
|
||||
return (
|
||||
<article className={styles.card}>
|
||||
<div className={styles["card-heading"]}>
|
||||
<h3>{item.title}</h3>
|
||||
<span
|
||||
className={item.readiness.status === "complete" ? styles.complete : styles.incomplete}
|
||||
>
|
||||
{item.readiness.status === "complete"
|
||||
? "Данные заполнены"
|
||||
: `Не хватает данных: ${missingCount}`}
|
||||
</span>
|
||||
</div>
|
||||
<dl className={styles.facts}>
|
||||
<dt>Специализация</dt>
|
||||
<dd>{displayDecision(item.specialization, specializationLabels)}</dd>
|
||||
<dt>Грейд</dt>
|
||||
<dd>{displayDecision(item.grade, gradeLabels)}</dd>
|
||||
<dt>Версия</dt>
|
||||
<dd>{item.version}</dd>
|
||||
</dl>
|
||||
{missingCount > 0 ? (
|
||||
<ul className={styles.missing}>
|
||||
{item.readiness.missing_fields.map((field) => (
|
||||
<li key={field.field}>{field.question}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
|
||||
Открыть потребность
|
||||
</ButtonLink>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function NeedListPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
|
||||
const session = sessionQuery.data;
|
||||
const accountId = session?.account.id;
|
||||
const sessionReady =
|
||||
Boolean(session && session.account.scenario === "employer") &&
|
||||
isNeedSessionCurrent(queryClient, session);
|
||||
const directory = useNeedOrganizationDirectory(session, sessionReady);
|
||||
const directoryData = directory.data;
|
||||
const directoryIsError = directory.isError;
|
||||
const directoryError = directory.error;
|
||||
const directoryIsFetching = directory.isFetching;
|
||||
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
|
||||
const directoryIsLoading = directory.isLoading;
|
||||
const hasMoreOrganizations = directory.hasNextPage;
|
||||
const fetchNextOrganizationPage = directory.fetchNextPage;
|
||||
const refetchDirectory = directory.refetch;
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const selectedOrganizationId = searchParams.get("organization_id");
|
||||
const [deniedContext, setDeniedContext] = useState<string | null>(null);
|
||||
const reportedAccessError = useRef(false);
|
||||
const previousSessionRef = useRef<{ accountId: string; csrfToken: string } | null>(null);
|
||||
const pages = directoryData?.pages ?? emptyDirectoryPages;
|
||||
const organizations = useMemo(() => activeNeedOrganizations(pages), [pages]);
|
||||
const selectedOrganization = organizations.find(
|
||||
(item) => item.organization.id === selectedOrganizationId,
|
||||
);
|
||||
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
|
||||
const directoryFresh =
|
||||
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
|
||||
const deniedKey =
|
||||
accountId && selectedOrganizationId ? `${accountId}:${selectedOrganizationId}` : null;
|
||||
const denied = deniedContext !== null && deniedContext === deniedKey;
|
||||
const membershipDenied =
|
||||
Boolean(selectedOrganizationId) &&
|
||||
!selectedOrganization &&
|
||||
directoryFresh &&
|
||||
!hasMoreOrganizations;
|
||||
|
||||
useEffect(() => {
|
||||
const next =
|
||||
session && sessionReady
|
||||
? { accountId: session.account.id, csrfToken: session.csrf_token }
|
||||
: null;
|
||||
const previous = previousSessionRef.current;
|
||||
if (
|
||||
previous &&
|
||||
(!next || previous.accountId !== next.accountId || previous.csrfToken !== next.csrfToken)
|
||||
) {
|
||||
removeNeedQueriesForSessionChange(queryClient);
|
||||
}
|
||||
previousSessionRef.current = next;
|
||||
}, [queryClient, session, sessionReady]);
|
||||
|
||||
useEffect(() => {
|
||||
if (directoryIsError && isAccessLoss(directoryError)) {
|
||||
removeAllNeedQueries(queryClient);
|
||||
}
|
||||
}, [directoryError, directoryIsError, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
|
||||
if (selectedOrganizationId) {
|
||||
if (!selectedOrganization && hasMoreOrganizations) void fetchNextOrganizationPage();
|
||||
return;
|
||||
}
|
||||
if (organizations[0]) {
|
||||
setSearchParams({ organization_id: organizations[0].organization.id }, { replace: true });
|
||||
} else if (hasMoreOrganizations) {
|
||||
void fetchNextOrganizationPage();
|
||||
}
|
||||
}, [
|
||||
directoryData,
|
||||
directoryIsError,
|
||||
directoryIsFetchingNextPage,
|
||||
fetchNextOrganizationPage,
|
||||
hasMoreOrganizations,
|
||||
organizations,
|
||||
selectedOrganization,
|
||||
selectedOrganizationId,
|
||||
sessionReady,
|
||||
setSearchParams,
|
||||
]);
|
||||
|
||||
const needs = useInfiniteQuery({
|
||||
queryKey: needQueryKeys.list(
|
||||
accountId ?? "no-session",
|
||||
selectedOrganizationId ?? "no-organization",
|
||||
),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (!isNeedSessionCurrent(queryClient, session))
|
||||
throw new Error("The session changed before the need-list request.");
|
||||
const result = await listOrganizationNeeds(
|
||||
selectedOrganizationId ?? "",
|
||||
{ limit: needListPageSize, ...(pageParam ? { cursor: pageParam } : {}) },
|
||||
{ signal },
|
||||
);
|
||||
if (!isNeedSessionCurrent(queryClient, session))
|
||||
throw new Error("The session changed during the need-list request.");
|
||||
return result;
|
||||
},
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: directoryFresh && selectedOrganization !== undefined && !denied && !membershipDenied,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const handleAccessLoss = useCallback(
|
||||
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
|
||||
if (
|
||||
!isAccessLoss(error) ||
|
||||
!deniedOrganizationId ||
|
||||
!isNeedSessionCurrent(queryClient, session)
|
||||
)
|
||||
return;
|
||||
if (!accountId) return;
|
||||
setDeniedContext(`${accountId}:${deniedOrganizationId}`);
|
||||
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
|
||||
await refetchDirectory();
|
||||
},
|
||||
[accountId, queryClient, refetchDirectory, session, setDeniedContext],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needs.isError || !isAccessLoss(needs.error)) {
|
||||
if (!needs.isError) reportedAccessError.current = false;
|
||||
return;
|
||||
}
|
||||
if (reportedAccessError.current) return;
|
||||
reportedAccessError.current = true;
|
||||
void handleAccessLoss(needs.error, selectedOrganizationId);
|
||||
}, [handleAccessLoss, needs.error, needs.isError, selectedOrganizationId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!membershipDenied || !selectedOrganizationId) return;
|
||||
removeNeedQueriesForOrganization(queryClient, selectedOrganizationId);
|
||||
}, [membershipDenied, queryClient, selectedOrganizationId]);
|
||||
|
||||
const listItems = needs.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
const hasAccessError = sessionQuery.isError || directoryIsError;
|
||||
const loading =
|
||||
!sessionQuery.isError &&
|
||||
(!sessionReady ||
|
||||
directoryIsLoading ||
|
||||
directoryRefreshing ||
|
||||
!directoryData ||
|
||||
(!selectedOrganization && hasMoreOrganizations));
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Потребности"
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead="Описывайте потребности команды, подтверждайте предложения из текста и проверяйте готовность данных."
|
||||
width="wide"
|
||||
>
|
||||
{sessionQuery.isError ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directoryIsError ? (
|
||||
isAccessLoss(directoryError) ? (
|
||||
<ForbiddenState error={directoryError} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directoryError}
|
||||
isRetrying={directoryIsFetching}
|
||||
onRetry={() => void refetchDirectory()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? <LoadingState label="Проверяем компанию и загружаем потребности..." /> : null}
|
||||
{!hasAccessError && directoryData && directoryFresh ? (
|
||||
<div className={styles.content}>
|
||||
{organizations.length > 0 ? (
|
||||
<Section title="Список потребностей">
|
||||
<div className={styles.toolbar}>
|
||||
<div className={styles.selector}>
|
||||
<label htmlFor="need-organization">Компания</label>
|
||||
<select
|
||||
id="need-organization"
|
||||
value={selectedOrganization?.organization.id ?? ""}
|
||||
onChange={(event) => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("organization_id", event.currentTarget.value);
|
||||
setDeniedContext(null);
|
||||
reportedAccessError.current = false;
|
||||
setSearchParams(next);
|
||||
}}
|
||||
>
|
||||
{!selectedOrganization ? <option value="">Выберите компанию</option> : null}
|
||||
{organizations.map((item) => (
|
||||
<option key={item.organization.id} value={item.organization.id}>
|
||||
{item.organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{selectedOrganization ? (
|
||||
<ButtonLink to={paths.employer.needNew(selectedOrganization.organization.id)}>
|
||||
Создать потребность
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
</div>
|
||||
{denied || membershipDenied ? (
|
||||
<ForbiddenState
|
||||
title="Потребности компании недоступны"
|
||||
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setDeniedContext(null);
|
||||
reportedAccessError.current = false;
|
||||
void refetchDirectory();
|
||||
}}
|
||||
>
|
||||
Проверить доступ снова
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{needs.isError && !isAccessLoss(needs.error) ? (
|
||||
<ErrorState
|
||||
error={needs.error}
|
||||
isRetrying={needs.isFetching}
|
||||
onRetry={() => void needs.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{needs.isLoading ? <LoadingState label="Загружаем потребности..." /> : null}
|
||||
{needs.data && !needs.isError && !denied && !membershipDenied ? (
|
||||
listItems.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Потребностей пока нет"
|
||||
description="Создайте первую потребность. Связанная вакансия для этого не нужна."
|
||||
action={
|
||||
selectedOrganization ? (
|
||||
<ButtonLink
|
||||
to={paths.employer.needNew(selectedOrganization.organization.id)}
|
||||
>
|
||||
Создать потребность
|
||||
</ButtonLink>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.list}>
|
||||
{listItems.map((item) => (
|
||||
<NeedCard
|
||||
key={item.id}
|
||||
item={item}
|
||||
organizationId={selectedOrganizationId ?? ""}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
{needs.hasNextPage && !denied && !membershipDenied ? (
|
||||
<div className={styles["load-more"]}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={needs.isFetchingNextPage}
|
||||
onClick={() => void needs.fetchNextPage()}
|
||||
>
|
||||
{needs.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
) : (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Потребностями в этой версии может управлять только владелец."
|
||||
/>
|
||||
)}
|
||||
{hasMoreOrganizations ? (
|
||||
<div className={styles["load-more"]}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={directoryIsFetchingNextPage}
|
||||
onClick={() => void fetchNextOrganizationPage()}
|
||||
>
|
||||
{directoryIsFetchingNextPage ? "Загружаем компании..." : "Показать еще компании"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export {
|
||||
CreateSupportCasePage,
|
||||
ManualAssessmentPage,
|
||||
SupportCaseDetailPage,
|
||||
SupportCasesPage,
|
||||
} from "./ui/support-cases-pages";
|
||||
@@ -0,0 +1,119 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.case-list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.case-card,
|
||||
.event,
|
||||
.decision {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.card-heading,
|
||||
.event-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
}
|
||||
|
||||
.card-heading h3,
|
||||
.event-heading h3,
|
||||
.decision h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.card-heading > span {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-pill);
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.case-card p,
|
||||
.event p,
|
||||
.decision p {
|
||||
margin: var(--space-3) 0 0;
|
||||
line-height: var(--line-height-body);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.target,
|
||||
.date,
|
||||
.event-heading time {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.more {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 0.45fr) minmax(0, 1fr);
|
||||
gap: var(--space-2) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.description,
|
||||
.message {
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.history {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.event-heading time {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
@media (width <= 40rem) {
|
||||
.actions > * {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.facts dd + dt {
|
||||
margin-top: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
import { useEffect } from "react";
|
||||
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useParams } from "react-router-dom";
|
||||
import {
|
||||
formatSupportDate,
|
||||
isSupportSessionAccessError,
|
||||
supportCaseActorLabels,
|
||||
supportCaseDetailQueryKey,
|
||||
supportCaseEventKindLabels,
|
||||
supportCaseListQueryKey,
|
||||
supportCasePathFor,
|
||||
supportCaseStatusLabels,
|
||||
supportCaseTypeLabels,
|
||||
supportSessionMatches,
|
||||
supportTargetDescription,
|
||||
} from "../../../entities/support-case";
|
||||
import { CreateSupportCase } from "../../../features/create-support-case";
|
||||
import { RequestManualAssessment } from "../../../features/request-manual-assessment";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import {
|
||||
getMySupportCase,
|
||||
listMySupportCases,
|
||||
} from "../../../shared/api/endpoints/support/support";
|
||||
import type { Session, SupportCase } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
TextLink,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./support-cases-pages.module.css";
|
||||
|
||||
const supportCasePageSize = 20;
|
||||
const caseIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
function isCaseAccessError(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function sessionErrorState(error: unknown, onRetry: () => void, isRetrying: boolean) {
|
||||
if (isSupportSessionAccessError(error)) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={error}
|
||||
title="Войдите, чтобы открыть обращения"
|
||||
description="После входа поддержка откроется для вашего аккаунта."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Войти в поддержку
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ErrorState
|
||||
error={error}
|
||||
title="Не удалось проверить вход"
|
||||
isRetrying={isRetrying}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function removeSupportAccountCache(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
accountId: string,
|
||||
) {
|
||||
queryClient.removeQueries({
|
||||
predicate: (query) =>
|
||||
query.queryKey[0] === "account" &&
|
||||
query.queryKey[1] === accountId &&
|
||||
query.queryKey[2] === "support-cases",
|
||||
});
|
||||
}
|
||||
|
||||
function supportLandingPath(session: Session): string {
|
||||
return session.account.scenario === "candidate"
|
||||
? paths.candidate.supportCases
|
||||
: paths.employer.supportCases;
|
||||
}
|
||||
|
||||
export function SupportCasesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const list = useInfiniteQuery({
|
||||
queryKey: actor
|
||||
? supportCaseListQueryKey(actor.account.id)
|
||||
: ["account", "anonymous", "support-cases", "list"],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (
|
||||
!actor ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed before support history was loaded.");
|
||||
}
|
||||
const result = await listMySupportCases(
|
||||
pageParam
|
||||
? { limit: supportCasePageSize, cursor: pageParam }
|
||||
: { limit: supportCasePageSize },
|
||||
{ signal },
|
||||
);
|
||||
if (
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed while support history was loading.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: Boolean(actor),
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
});
|
||||
const listAccessError = list.isError && isCaseAccessError(list.error) ? list.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || (!isSupportSessionAccessError(session.error) && !listAccessError)) {
|
||||
return;
|
||||
}
|
||||
removeSupportAccountCache(queryClient, accountId);
|
||||
}, [actor, knownActor, listAccessError, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actor || (actor.account.scenario !== "candidate" && actor.account.scenario !== "employer")) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ForbiddenState title="Поддержка недоступна" />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (listAccessError) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ForbiddenState
|
||||
error={listAccessError}
|
||||
title="Обращения недоступны"
|
||||
description="Сервер не подтвердил доступ к истории этого аккаунта."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Обновить вход
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (list.isPending && !list.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<LoadingState label="Загружаем историю обращений..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (list.isError && !list.data) {
|
||||
return (
|
||||
<Page title="Мои обращения">
|
||||
<ErrorState
|
||||
error={list.error}
|
||||
title="Не удалось загрузить обращения"
|
||||
isRetrying={list.isRefetching}
|
||||
onRetry={() => void list.refetch()}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
const cases = list.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
return (
|
||||
<Page
|
||||
title="Мои обращения"
|
||||
eyebrow={
|
||||
actor.account.scenario === "candidate" ? "Кабинет кандидата" : "Кабинет работодателя"
|
||||
}
|
||||
lead="Здесь хранятся обращения этого аккаунта и ответы поддержки."
|
||||
width="wide"
|
||||
>
|
||||
<div className={styles.root}>
|
||||
<Section title="Новый запрос">
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink
|
||||
to={
|
||||
actor.account.scenario === "candidate"
|
||||
? paths.candidate.supportNew
|
||||
: paths.employer.supportNew
|
||||
}
|
||||
>
|
||||
Написать в поддержку
|
||||
</ButtonLink>
|
||||
{actor.account.scenario === "candidate" ? (
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="История">
|
||||
{list.isError ? (
|
||||
<ErrorState
|
||||
error={list.error}
|
||||
title="Не удалось обновить историю"
|
||||
isRetrying={list.isRefetching}
|
||||
onRetry={() => void list.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
{cases.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Обращений пока нет"
|
||||
description="После отправки новое дело появится здесь и останется доступным после повторного входа."
|
||||
action={
|
||||
<ButtonLink
|
||||
to={
|
||||
actor.account.scenario === "candidate"
|
||||
? paths.candidate.supportNew
|
||||
: paths.employer.supportNew
|
||||
}
|
||||
>
|
||||
Создать обращение
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles["case-list"]}>
|
||||
{cases.map((supportCase) => (
|
||||
<SupportCaseSummaryCard
|
||||
key={supportCase.id}
|
||||
supportCase={supportCase}
|
||||
href={supportCasePathFor(actor, supportCase.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{list.hasNextPage ? (
|
||||
<div className={styles.more}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={list.isFetchingNextPage}
|
||||
onClick={() => void list.fetchNextPage()}
|
||||
>
|
||||
{list.isFetchingNextPage ? "Загружаем..." : "Показать более ранние обращения"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportCaseSummaryCard({
|
||||
supportCase,
|
||||
href,
|
||||
}: {
|
||||
supportCase: {
|
||||
id: string;
|
||||
number: string;
|
||||
type: SupportCase["type"];
|
||||
status: SupportCase["status"];
|
||||
response_target: SupportCase["response_target"];
|
||||
created_at: string;
|
||||
};
|
||||
href: string;
|
||||
}) {
|
||||
return (
|
||||
<article className={styles["case-card"]}>
|
||||
<div className={styles["card-heading"]}>
|
||||
<h3>
|
||||
<TextLink to={href}>{supportCase.number}</TextLink>
|
||||
</h3>
|
||||
<span>{supportCaseStatusLabels[supportCase.status]}</span>
|
||||
</div>
|
||||
<p>{supportCaseTypeLabels[supportCase.type]}</p>
|
||||
<p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p>
|
||||
<p className={styles.date}>Создано {formatSupportDate(supportCase.created_at)}</p>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function CreateSupportCasePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Обратиться в поддержку"
|
||||
eyebrow="Мои обращения"
|
||||
lead="Отправьте вопрос или сообщите о проблеме."
|
||||
width="wide"
|
||||
>
|
||||
<CreateSupportCase />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
export function ManualAssessmentPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Запросить ручную оценку"
|
||||
eyebrow="Поддержка"
|
||||
lead="Выберите категорию и расскажите, что важно учесть эксперту."
|
||||
width="wide"
|
||||
>
|
||||
<RequestManualAssessment />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
export function SupportCaseDetailPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { caseId = "" } = useParams();
|
||||
const session = useGetCurrentSession({ query: { retry: false } });
|
||||
const actor = session.isSuccess ? session.data : null;
|
||||
const knownActor =
|
||||
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
|
||||
const validId = caseIdPattern.test(caseId);
|
||||
const details = useQuery({
|
||||
queryKey:
|
||||
actor && validId
|
||||
? supportCaseDetailQueryKey(actor.account.id, caseId)
|
||||
: ["account", "anonymous", "support-cases", "detail", caseId],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (
|
||||
!actor ||
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed before the support request was loaded.");
|
||||
}
|
||||
const result = await getMySupportCase(caseId, { signal });
|
||||
if (
|
||||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
|
||||
) {
|
||||
throw new Error("The active account changed while the support request was loading.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
enabled: Boolean(actor && validId),
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: "always",
|
||||
retry: false,
|
||||
});
|
||||
const detailsAccessError =
|
||||
details.isError && isCaseAccessError(details.error) ? details.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
const accountId = actor?.account.id ?? knownActor?.account.id;
|
||||
if (!accountId || (!isSupportSessionAccessError(session.error) && !detailsAccessError)) {
|
||||
return;
|
||||
}
|
||||
removeSupportAccountCache(queryClient, accountId);
|
||||
}, [actor, detailsAccessError, knownActor, queryClient, session.error]);
|
||||
|
||||
if (session.isPending && !session.data) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Проверяем вход..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isError) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!actor)
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<ForbiddenState title="Войдите, чтобы открыть обращение" />
|
||||
</Page>
|
||||
);
|
||||
if (!validId) {
|
||||
return (
|
||||
<Page title="Обращение не найдено">
|
||||
<EmptyState
|
||||
title="Обращение не найдено или недоступно"
|
||||
description="Проверьте ссылку или вернитесь к истории своего аккаунта."
|
||||
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (detailsAccessError) {
|
||||
if (detailsAccessError.status === 404) {
|
||||
return (
|
||||
<Page title="Обращение не найдено">
|
||||
<EmptyState
|
||||
title="Обращение не найдено или недоступно"
|
||||
description="Ссылка не дает доступ к истории другого аккаунта."
|
||||
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Page title="Обращение недоступно">
|
||||
<ForbiddenState
|
||||
error={detailsAccessError}
|
||||
title="Обращение недоступно"
|
||||
description="Сервер не подтвердил доступ к этой истории."
|
||||
action={
|
||||
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
|
||||
Обновить вход
|
||||
</ButtonLink>
|
||||
}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (details.isPending && !details.data) {
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Загружаем обращение..." />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (details.isError && !details.data) {
|
||||
return (
|
||||
<Page title="Не удалось открыть обращение">
|
||||
<ErrorState
|
||||
error={details.error}
|
||||
title="Не удалось загрузить обращение"
|
||||
isRetrying={details.isRefetching}
|
||||
onRetry={() => void details.refetch()}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!details.data)
|
||||
return (
|
||||
<Page title="Обращение">
|
||||
<LoadingState label="Загружаем обращение..." />
|
||||
</Page>
|
||||
);
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={details.data.number}
|
||||
eyebrow="Мои обращения"
|
||||
lead={supportCaseTypeLabels[details.data.type]}
|
||||
width="wide"
|
||||
>
|
||||
<SupportCaseDetails supportCase={details.data} session={actor} />
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportCaseDetails({
|
||||
supportCase,
|
||||
session,
|
||||
}: {
|
||||
supportCase: SupportCase;
|
||||
session: Session;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<Section title="Состояние">
|
||||
<dl className={styles.facts}>
|
||||
<dt>Номер</dt>
|
||||
<dd>{supportCase.number}</dd>
|
||||
<dt>Статус</dt>
|
||||
<dd>{supportCaseStatusLabels[supportCase.status]}</dd>
|
||||
<dt>Создано</dt>
|
||||
<dd>{formatSupportDate(supportCase.created_at)}</dd>
|
||||
<dt>Операционная цель</dt>
|
||||
<dd>{supportTargetDescription(supportCase.response_target)}</dd>
|
||||
{supportCase.assessment_target ? (
|
||||
<>
|
||||
<dt>Специальность</dt>
|
||||
<dd>{supportCase.assessment_target.specialization}</dd>
|
||||
<dt>Желаемый грейд</dt>
|
||||
<dd>{supportCase.assessment_target.grade}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{supportCase.type === "manual_assessment" ? (
|
||||
<>
|
||||
<dt>Рубрика</dt>
|
||||
<dd>
|
||||
{supportCase.rubric_version === null
|
||||
? "Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась."
|
||||
: `Зафиксирована версия ${supportCase.rubric_version}. Запрос ожидает эксперта.`}
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
</dl>
|
||||
<p className={styles.description}>{supportCase.description}</p>
|
||||
{supportCase.decision ? (
|
||||
<div className={styles.decision}>
|
||||
<h3>Решение</h3>
|
||||
<p>{supportCase.decision.reason}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
<Section title="История">
|
||||
<ol className={styles.history}>
|
||||
{supportCase.history.map((event) => (
|
||||
<li key={event.sequence} className={styles.event}>
|
||||
<div className={styles["event-heading"]}>
|
||||
<h3>{supportCaseEventKindLabels[event.kind]}</h3>
|
||||
<time dateTime={event.occurred_at}>{formatSupportDate(event.occurred_at)}</time>
|
||||
</div>
|
||||
<p>{supportCaseActorLabels[event.actor]}</p>
|
||||
{event.status ? <p>Статус: {supportCaseStatusLabels[event.status]}</p> : null}
|
||||
{event.message ? <p className={styles.message}>{event.message}</p> : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Section>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink to={supportLandingPath(session)} variant="secondary">
|
||||
Мои обращения
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -138,6 +138,50 @@ describe("apiRequest", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("retains a valid Retry-After integer without retaining response headers", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ code: "rate_limited" }), {
|
||||
status: 429,
|
||||
headers: {
|
||||
"content-type": "application/problem+json",
|
||||
"retry-after": "17",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const caught: unknown = await apiRequest("/healthz").catch((error: unknown) => error);
|
||||
|
||||
expect(caught).toBeInstanceOf(ApiRequestError);
|
||||
expect(caught).toMatchObject({ status: 429, retryAfterSeconds: 17 });
|
||||
expect(caught).not.toHaveProperty("headers");
|
||||
});
|
||||
|
||||
it.each([undefined, "", "1.5", "-1", "Wed, 21 Oct 2015 07:28:00 GMT", "9007199254740992"])(
|
||||
"omits invalid or missing Retry-After value %s",
|
||||
async (retryAfter) => {
|
||||
const headers: Record<string, string> = { "content-type": "application/problem+json" };
|
||||
if (retryAfter !== undefined) {
|
||||
headers["retry-after"] = retryAfter;
|
||||
}
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ code: "rate_limited" }), { status: 429, headers }),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(apiRequest("/healthz")).rejects.toMatchObject({
|
||||
status: 429,
|
||||
retryAfterSeconds: undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "a JSON body that is not a problem",
|
||||
|
||||
@@ -27,6 +27,7 @@ type ApiRequestErrorInit = {
|
||||
detail?: string | undefined;
|
||||
traceId?: string | undefined;
|
||||
fieldErrors?: readonly ProblemFieldError[] | undefined;
|
||||
retryAfterSeconds?: number | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -40,6 +41,7 @@ export class ApiRequestError extends Error {
|
||||
readonly detail: string | undefined;
|
||||
readonly traceId: string | undefined;
|
||||
readonly fieldErrors: readonly ProblemFieldError[];
|
||||
readonly retryAfterSeconds: number | undefined;
|
||||
|
||||
constructor(init: ApiRequestErrorInit) {
|
||||
super(init.detail ?? init.title);
|
||||
@@ -50,6 +52,7 @@ export class ApiRequestError extends Error {
|
||||
this.detail = init.detail;
|
||||
this.traceId = init.traceId;
|
||||
this.fieldErrors = init.fieldErrors ?? [];
|
||||
this.retryAfterSeconds = init.retryAfterSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +97,18 @@ function isProblemResponse(response: Response): boolean {
|
||||
return mediaType === problemMediaType;
|
||||
}
|
||||
|
||||
function retryAfterSeconds(response: Response): number | undefined {
|
||||
const value = response.headers.get("retry-after");
|
||||
if (value === null || !/^\d+$/.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const seconds = Number(value);
|
||||
return Number.isSafeInteger(seconds) ? seconds : undefined;
|
||||
}
|
||||
|
||||
async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
const headerTraceId = response.headers.get(requestIdHeader) ?? undefined;
|
||||
const retryAfter = retryAfterSeconds(response);
|
||||
|
||||
if (isProblemResponse(response)) {
|
||||
const body: unknown = await response.json().catch(() => undefined);
|
||||
@@ -109,6 +122,7 @@ async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
detail: problem.detail,
|
||||
traceId: problem.trace_id ?? headerTraceId,
|
||||
fieldErrors: problem.errors,
|
||||
retryAfterSeconds: retryAfter,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -118,6 +132,7 @@ async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
code: unknownErrorCode,
|
||||
title: `Request failed with status ${response.status}.`,
|
||||
traceId: headerTraceId,
|
||||
retryAfterSeconds: retryAfter,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
AssessmentQualifiedResult,
|
||||
AssessmentResult,
|
||||
AssessmentSessions,
|
||||
AssessmentSignalReceipt,
|
||||
AssessmentUncertainty,
|
||||
BasicScore,
|
||||
ChoiceItemContent,
|
||||
@@ -131,6 +132,8 @@ export const getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptM
|
||||
|
||||
export const getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock()},]))
|
||||
|
||||
export const getRecordMyAssessmentAttemptSignalsResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalReceipt, object>> = {}): AssessmentSignalReceipt => ({status: faker.helpers.arrayElement(['accepted','saturated'] as const), accepted_events: faker.number.int({min: 0, max: 50}), received_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse});
|
||||
|
||||
export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
|
||||
@@ -248,6 +251,18 @@ export const getStartMyAssessmentAttemptSessionMockHandler = (overrideResponse?:
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getRecordMyAssessmentAttemptSignalsMockHandler = (overrideResponse?: AssessmentSignalReceipt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentSignalReceipt> | AssessmentSignalReceipt), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/me/assessment-attempts/:attemptId/signals', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getRecordMyAssessmentAttemptSignalsResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
|
||||
return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
|
||||
|
||||
@@ -288,6 +303,7 @@ export const getAssessmentMock = () => [
|
||||
getCreateMyAssessmentAttemptMockHandler(),
|
||||
getGetMyAssessmentAttemptMockHandler(),
|
||||
getStartMyAssessmentAttemptSessionMockHandler(),
|
||||
getRecordMyAssessmentAttemptSignalsMockHandler(),
|
||||
getSubmitMyAssessmentAnswerMockHandler(),
|
||||
getFinalizeMyAssessmentAttemptMockHandler(),
|
||||
getGetMyAssessmentResultMockHandler()
|
||||
|
||||
@@ -30,10 +30,14 @@ import type {
|
||||
AssessmentAttemptSessionStart,
|
||||
AssessmentAvailability,
|
||||
AssessmentFinalization,
|
||||
AssessmentFinalizeConflictProblem,
|
||||
AssessmentResult,
|
||||
AssessmentSignalBatch,
|
||||
AssessmentSignalReceipt,
|
||||
CreateMyAssessmentAttemptHeaders,
|
||||
FinalizeMyAssessmentAttemptHeaders,
|
||||
Problem,
|
||||
RecordMyAssessmentAttemptSignalsHeaders,
|
||||
StartMyAssessmentAttemptSessionHeaders,
|
||||
SubmitMyAssessmentAnswerHeaders
|
||||
} from '../../schemas';
|
||||
@@ -464,6 +468,100 @@ export const useStartMyAssessmentAttemptSession = <TError = ErrorType<Problem>,
|
||||
> => {
|
||||
return useMutation(getStartMyAssessmentAttemptSessionMutationOptions(options), queryClient);
|
||||
}
|
||||
export const getRecordMyAssessmentAttemptSignalsUrl = (attemptId: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/me/assessment-attempts/${attemptId}/signals`
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect.
|
||||
*
|
||||
* The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
*
|
||||
* A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422.
|
||||
* @summary Store a bounded batch of client-reported assessment signals.
|
||||
*/
|
||||
export const recordMyAssessmentAttemptSignals = async (attemptId: string,
|
||||
assessmentSignalBatch: AssessmentSignalBatch,
|
||||
headers: RecordMyAssessmentAttemptSignalsHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentSignalReceipt> => {
|
||||
|
||||
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
|
||||
if (!h) return {};
|
||||
if (h instanceof Headers) return Object.fromEntries(h.entries());
|
||||
if (Symbol.iterator in h) {
|
||||
return Object.fromEntries(
|
||||
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
|
||||
);
|
||||
}
|
||||
const headers: Record<string, string | readonly string[]> = {};
|
||||
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
|
||||
if (value !== undefined) headers[name] = value;
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
return apiRequest<AssessmentSignalReceipt>(getRecordMyAssessmentAttemptSignalsUrl(attemptId),
|
||||
{
|
||||
...options,
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
|
||||
body: JSON.stringify(assessmentSignalBatch)
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getRecordMyAssessmentAttemptSignalsMutationKey = () => ['recordMyAssessmentAttemptSignals'] as const;
|
||||
|
||||
export const getRecordMyAssessmentAttemptSignalsMutationOptions = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext> => {
|
||||
|
||||
const mutationKey = getRecordMyAssessmentAttemptSignalsMutationKey();
|
||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
||||
options
|
||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
||||
: {mutation: { mutationKey, }, request: undefined};
|
||||
|
||||
|
||||
|
||||
|
||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, RecordMyAssessmentAttemptSignalsMutationVariables> = (props) => {
|
||||
const {attemptId,data,headers} = props ?? {};
|
||||
|
||||
return recordMyAssessmentAttemptSignals(attemptId,data,headers,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type RecordMyAssessmentAttemptSignalsMutationResult = NonNullable<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>>
|
||||
export type RecordMyAssessmentAttemptSignalsMutationBody = AssessmentSignalBatch
|
||||
export type RecordMyAssessmentAttemptSignalsMutationError = ErrorType<Problem>
|
||||
export type RecordMyAssessmentAttemptSignalsMutationVariables = {attemptId: string;data: AssessmentSignalBatch;headers: RecordMyAssessmentAttemptSignalsHeaders}
|
||||
|
||||
/**
|
||||
* @summary Store a bounded batch of client-reported assessment signals.
|
||||
*/
|
||||
export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>,
|
||||
TError,
|
||||
RecordMyAssessmentAttemptSignalsMutationVariables,
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getRecordMyAssessmentAttemptSignalsMutationOptions(options), queryClient);
|
||||
}
|
||||
export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => {
|
||||
|
||||
|
||||
@@ -590,7 +688,7 @@ export const useSubmitMyAssessmentAnswer = <TError = ErrorType<Problem>,
|
||||
*
|
||||
* A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
*
|
||||
* An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
* An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
*
|
||||
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not.
|
||||
* @summary Ask for the grade decision of an assessment attempt.
|
||||
@@ -628,7 +726,7 @@ return apiRequest<AssessmentAttempt>(getFinalizeMyAssessmentAttemptUrl(attemptId
|
||||
|
||||
export const getFinalizeMyAssessmentAttemptMutationKey = () => ['finalizeMyAssessmentAttempt'] as const;
|
||||
|
||||
export const getFinalizeMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem>,
|
||||
export const getFinalizeMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem | AssessmentFinalizeConflictProblem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext> => {
|
||||
|
||||
@@ -657,13 +755,13 @@ const {mutation: mutationOptions, request: requestOptions} = options ?
|
||||
|
||||
export type FinalizeMyAssessmentAttemptMutationResult = NonNullable<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>>
|
||||
export type FinalizeMyAssessmentAttemptMutationBody = AssessmentFinalization
|
||||
export type FinalizeMyAssessmentAttemptMutationError = ErrorType<Problem>
|
||||
export type FinalizeMyAssessmentAttemptMutationError = ErrorType<Problem | AssessmentFinalizeConflictProblem>
|
||||
export type FinalizeMyAssessmentAttemptMutationVariables = {attemptId: string;data: AssessmentFinalization;headers: FinalizeMyAssessmentAttemptHeaders}
|
||||
|
||||
/**
|
||||
* @summary Ask for the grade decision of an assessment attempt.
|
||||
*/
|
||||
export const useFinalizeMyAssessmentAttempt = <TError = ErrorType<Problem>,
|
||||
export const useFinalizeMyAssessmentAttempt = <TError = ErrorType<Problem | AssessmentFinalizeConflictProblem>,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>,
|
||||
|
||||
@@ -37,7 +37,7 @@ import type {
|
||||
|
||||
export const getListOrganizationInvitationsResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitationList, object>> = {}): OrganizationInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getListOrganizationInvitationsResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitationList, object>> = {}): OrganizationInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getListOrganizationInvitationsResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
export const getCreateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -45,7 +45,7 @@ export const getCreateOrganizationInvitationResponseInvitationPackageItemProvide
|
||||
|
||||
export const getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getGetOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -53,7 +53,7 @@ export const getGetOrganizationInvitationResponseInvitationPackageItemProvidedMo
|
||||
|
||||
export const getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -61,7 +61,7 @@ export const getUpdateOrganizationInvitationResponseInvitationPackageItemProvide
|
||||
|
||||
export const getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getSendOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -69,7 +69,7 @@ export const getSendOrganizationInvitationResponseInvitationPackageItemProvidedM
|
||||
|
||||
export const getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -77,7 +77,7 @@ export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemPr
|
||||
|
||||
export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
|
||||
|
||||
@@ -85,7 +85,7 @@ export const getWithdrawOrganizationInvitationResponseInvitationPackageItemProvi
|
||||
|
||||
export const getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
|
||||
|
||||
export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
|
||||
|
||||
export const getGetOrganizationInvitationContactsResponseMock = (overrideResponse: Partial<Extract<ContactDisclosure, object>> = {}): ContactDisclosure => ({invitation_id: faker.string.uuid(), grant_id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', full_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), ...overrideResponse})
|
||||
|
||||
|
||||
@@ -34,13 +34,15 @@ import type {
|
||||
} from '../../schemas';
|
||||
|
||||
|
||||
export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial<Extract<PrivacySettings, object>> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse})
|
||||
export const getGetOrganizationCandidateCardResponseMock = (overrideResponse: Partial<Extract<AnonymousCardContent, object>> = {}): AnonymousCardContent => ({pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,]), ...overrideResponse})
|
||||
|
||||
export const getSetMyPublicationResponseMock = (overrideResponse: Partial<Extract<Publication, object>> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
|
||||
export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial<Extract<PrivacySettings, object>> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse})
|
||||
|
||||
export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial<AnonymousCardContent> = {}): AnonymousCardContent => ({...{categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)})), null]), stack: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), experience_months: faker.helpers.arrayElement([faker.number.int({min: 0, max: 1200}), null]), soft_skills: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), null]), relocation: faker.helpers.arrayElement([faker.datatype.boolean(), null])}, ...overrideResponse});
|
||||
export const getSetMyPublicationResponseMock = (overrideResponse: Partial<Extract<Publication, object>> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
|
||||
|
||||
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial<AnonymousCardContent> = {}): AnonymousCardContent => ({...{pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, ...overrideResponse});
|
||||
|
||||
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
|
||||
|
||||
export const getSetMySearchStatusResponseMock = (overrideResponse: Partial<Extract<SearchStatus, object>> = {}): SearchStatus => ({value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
|
||||
|
||||
@@ -50,13 +52,25 @@ export const getHideOrganizationResponseMock = (overrideResponse: Partial<Extrac
|
||||
|
||||
export const getListMyPrivacyHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial<PrivacyOrganization> = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse});
|
||||
|
||||
export const getListMyPrivacyHistoryResponseMock = (overrideResponse: Partial<Extract<PrivacyEventList, object>> = {}): PrivacyEventList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['publication_opened','publication_changed','publication_closed','search_status_confirmed','search_status_cleared','organization_hidden','organization_unhidden'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const),null,]), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), organization: faker.helpers.arrayElement([{...getListMyPrivacyHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
export const getListMyPrivacyHistoryResponseMock = (overrideResponse: Partial<Extract<PrivacyEventList, object>> = {}): PrivacyEventList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['publication_opened','publication_changed','publication_closed','search_status_confirmed','search_status_cleared','organization_hidden','organization_unhidden'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const),null,]), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), organization: faker.helpers.arrayElement([{...getListMyPrivacyHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
export const getListMyCardAccessHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial<PrivacyOrganization> = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse});
|
||||
|
||||
export const getListMyCardAccessHistoryResponseMock = (overrideResponse: Partial<Extract<CardAccessList, object>> = {}): CardAccessList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['card_viewed','contact_read'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', organization: faker.helpers.arrayElement([{...getListMyCardAccessHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateCardMockHandler = (overrideResponse?: AnonymousCardContent | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AnonymousCardContent> | AnonymousCardContent), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/organizations/:orgId/candidate-cards/:candidateHandle', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getGetOrganizationCandidateCardResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
|
||||
export const getGetMyPrivacySettingsMockHandler = (overrideResponse?: PrivacySettings | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<PrivacySettings> | PrivacySettings), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/me/privacy', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
@@ -163,6 +177,7 @@ export const getListMyCardAccessHistoryMockHandler = (overrideResponse?: CardAcc
|
||||
}, options)
|
||||
}
|
||||
export const getPrivacyMock = () => [
|
||||
getGetOrganizationCandidateCardMockHandler(),
|
||||
getGetMyPrivacySettingsMockHandler(),
|
||||
getSetMyPublicationMockHandler(),
|
||||
getGetMyCardPreviewMockHandler(),
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type {
|
||||
AnonymousCardContent,
|
||||
CardAccessList,
|
||||
CardPreview,
|
||||
HiddenOrganization,
|
||||
@@ -63,6 +64,123 @@ const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKe
|
||||
return result;
|
||||
};
|
||||
|
||||
export const getGetOrganizationCandidateCardUrl = (orgId: string,
|
||||
candidateHandle: string,) => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
*
|
||||
* `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
*
|
||||
* The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
*
|
||||
* Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
* @summary Read one currently visible anonymous candidate card.
|
||||
*/
|
||||
export const getOrganizationCandidateCard = async (orgId: string,
|
||||
candidateHandle: string, options?: Parameters<typeof apiRequest>[1]): Promise<AnonymousCardContent> => {
|
||||
|
||||
return apiRequest<AnonymousCardContent>(getGetOrganizationCandidateCardUrl(orgId,candidateHandle),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateCardQueryKey = (orgId: string,
|
||||
candidateHandle: string,) => {
|
||||
return [
|
||||
`/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}`
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getGetOrganizationCandidateCardQueryOptions = <TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetOrganizationCandidateCardQueryKey(orgId,candidateHandle);
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getOrganizationCandidateCard>>> = ({ signal }) => getOrganizationCandidateCard(orgId,candidateHandle, { signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined && candidateHandle !== null && candidateHandle !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type GetOrganizationCandidateCardQueryResult = NonNullable<Awaited<ReturnType<typeof getOrganizationCandidateCard>>>
|
||||
export type GetOrganizationCandidateCardQueryError = ErrorType<Problem>
|
||||
|
||||
|
||||
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateCard>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateCard>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateCard>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getOrganizationCandidateCard>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary Read one currently visible anonymous candidate card.
|
||||
*/
|
||||
|
||||
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
|
||||
orgId: string,
|
||||
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getGetOrganizationCandidateCardQueryOptions(orgId,candidateHandle,options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetMyPrivacySettingsUrl = () => {
|
||||
|
||||
|
||||
@@ -273,9 +391,11 @@ export const useSetMyPublication = <TError = ErrorType<Problem>,
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
* Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`.
|
||||
*
|
||||
* The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results.
|
||||
* The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it.
|
||||
*
|
||||
* `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
* @summary Preview the anonymous card that organizations would read.
|
||||
@@ -590,7 +710,7 @@ export const getHideOrganizationUrl = (orgId: string,) => {
|
||||
*
|
||||
* The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization.
|
||||
*
|
||||
* Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
* Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
*
|
||||
* A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit.
|
||||
*
|
||||
@@ -869,9 +989,9 @@ export const getListMyCardAccessHistoryUrl = (params?: ListMyCardAccessHistoryPa
|
||||
/**
|
||||
* Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
*
|
||||
* An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
|
||||
* An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history.
|
||||
*
|
||||
* The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
* Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access.
|
||||
*
|
||||
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
* @summary List the accesses of organizations to the card of the current candidate.
|
||||
|
||||
@@ -62,7 +62,7 @@ const terms = {
|
||||
} as const;
|
||||
|
||||
const draft = {
|
||||
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
|
||||
candidate_handle: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
need: { need_id: "01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12", requirements_version: 3 },
|
||||
response_period_days: 7,
|
||||
terms,
|
||||
@@ -294,7 +294,7 @@ it("parses an accepted invitation of the organization without contact values", (
|
||||
const parsed = OrganizationInvitation.parse({
|
||||
id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f",
|
||||
organization_id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
|
||||
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
|
||||
candidate_handle: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
need: null,
|
||||
state: "accepted",
|
||||
expiry_reason: null,
|
||||
|
||||
@@ -135,7 +135,15 @@ describe("generated PublicationUpdate", () => {
|
||||
expected_version: number;
|
||||
state: "closed" | "published";
|
||||
fields: Array<
|
||||
"categories" | "stack" | "experience" | "soft_skills" | "location" | "relocation"
|
||||
| "categories"
|
||||
| "stack"
|
||||
| "experience"
|
||||
| "soft_skills"
|
||||
| "location"
|
||||
| "relocation"
|
||||
| "self_assessment"
|
||||
| "work_formats"
|
||||
| "salary_compatibility"
|
||||
>;
|
||||
}>();
|
||||
});
|
||||
@@ -205,23 +213,31 @@ describe("generated HiddenOrganization", () => {
|
||||
|
||||
describe("generated AnonymousCardContent", () => {
|
||||
const card = {
|
||||
categories: [{ specialization: "backend", grade: "middle" }],
|
||||
stack: ["PostgreSQL", "Kafka"],
|
||||
experience_months: null,
|
||||
soft_skills: null,
|
||||
location: null,
|
||||
relocation: null,
|
||||
pseudonym: `cv1_${"a".repeat(43)}`,
|
||||
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
|
||||
stack: ["postgresql", "kafka"],
|
||||
self_assessment: [
|
||||
{
|
||||
specialization: "network_engineer",
|
||||
confirmation_status: "unconfirmed",
|
||||
declared_grade: "junior",
|
||||
},
|
||||
],
|
||||
experience_band: "1_3",
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
};
|
||||
|
||||
it("holds only the closed set of card properties and reads an unpublished one as null", () => {
|
||||
expect(AnonymousCardContent.parse(card)).toEqual(card);
|
||||
expect(Object.keys(AnonymousCardContent.shape).sort()).toEqual([
|
||||
"categories",
|
||||
"experience_months",
|
||||
"location",
|
||||
"relocation",
|
||||
"soft_skills",
|
||||
"experience_band",
|
||||
"pseudonym",
|
||||
"salary_compatibility",
|
||||
"self_assessment",
|
||||
"stack",
|
||||
"work_formats",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -251,7 +267,7 @@ describe("generated AnonymousCardContent", () => {
|
||||
expect(
|
||||
CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card }),
|
||||
).toMatchObject({
|
||||
card: { stack: ["PostgreSQL", "Kafka"] },
|
||||
card: { stack: ["postgresql", "kafka"] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const assessmentClipboardSignalSizeBytesMin = 0;
|
||||
export const assessmentClipboardSignalSizeBytesMax = 2147483647;
|
||||
|
||||
|
||||
export const AssessmentClipboardSignal = zod.object({
|
||||
"kind": zod.enum(['copy', 'paste', 'cut']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
|
||||
"size_bytes": zod.int().min(assessmentClipboardSignalSizeBytesMin).max(assessmentClipboardSignalSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
|
||||
})
|
||||
|
||||
export type AssessmentClipboardSignal = zod.input<typeof AssessmentClipboardSignal>;
|
||||
export type AssessmentClipboardSignalOutput = zod.output<typeof AssessmentClipboardSignal>;
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const assessmentFinalizeConflictProblemTypeMax = 256;
|
||||
|
||||
export const assessmentFinalizeConflictProblemTitleMax = 200;
|
||||
|
||||
export const assessmentFinalizeConflictProblemDetailMax = 1000;
|
||||
|
||||
export const assessmentFinalizeConflictProblemInstanceMax = 2048;
|
||||
|
||||
export const assessmentFinalizeConflictProblemTraceIdMax = 128;
|
||||
|
||||
|
||||
export const assessmentFinalizeConflictProblemTraceIdRegExp = new RegExp('^[A-Za-z0-9._-]+$');
|
||||
export const assessmentFinalizeConflictProblemErrorsItemPointerMax = 1024;
|
||||
|
||||
|
||||
export const assessmentFinalizeConflictProblemErrorsItemPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
|
||||
export const assessmentFinalizeConflictProblemErrorsItemCodeMax = 64;
|
||||
|
||||
|
||||
export const assessmentFinalizeConflictProblemErrorsItemCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
|
||||
export const assessmentFinalizeConflictProblemErrorsItemMessageMax = 500;
|
||||
|
||||
export const assessmentFinalizeConflictProblemErrorsMax = 100;
|
||||
|
||||
export const assessmentFinalizeConflictProblemPendingItemIdsMax = 220;
|
||||
|
||||
|
||||
export const AssessmentFinalizeConflictProblem = zod.object({
|
||||
"type": zod.string().max(assessmentFinalizeConflictProblemTypeMax),
|
||||
"title": zod.string().min(1).max(assessmentFinalizeConflictProblemTitleMax),
|
||||
"status": zod.literal(409),
|
||||
"code": zod.enum(['state_conflict', 'idempotency_in_progress']),
|
||||
"detail": zod.string().max(assessmentFinalizeConflictProblemDetailMax).exactOptional(),
|
||||
"instance": zod.string().max(assessmentFinalizeConflictProblemInstanceMax).exactOptional(),
|
||||
"trace_id": zod.string().min(1).max(assessmentFinalizeConflictProblemTraceIdMax).regex(assessmentFinalizeConflictProblemTraceIdRegExp).exactOptional(),
|
||||
"errors": zod.array(zod.object({
|
||||
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
|
||||
"pointer": zod.string().max(assessmentFinalizeConflictProblemErrorsItemPointerMax).regex(assessmentFinalizeConflictProblemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
|
||||
"code": zod.string().min(1).max(assessmentFinalizeConflictProblemErrorsItemCodeMax).regex(assessmentFinalizeConflictProblemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values.'),
|
||||
"message": zod.string().min(1).max(assessmentFinalizeConflictProblemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.')
|
||||
}).describe('One reason why a request field or parameter is invalid.')).max(assessmentFinalizeConflictProblemErrorsMax).exactOptional(),
|
||||
"pending_item_ids": zod.array(zod.uuid()).max(assessmentFinalizeConflictProblemPendingItemIdsMax).exactOptional().describe('Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items.')
|
||||
}).describe('A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts.')
|
||||
|
||||
export type AssessmentFinalizeConflictProblem = zod.input<typeof AssessmentFinalizeConflictProblem>;
|
||||
export type AssessmentFinalizeConflictProblemOutput = zod.output<typeof AssessmentFinalizeConflictProblem>;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const assessmentFocusLossSignalDurationMsMax = 259200000;
|
||||
|
||||
|
||||
export const AssessmentFocusLossSignal = zod.object({
|
||||
"kind": zod.enum(['focus_loss']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
|
||||
"duration_ms": zod.int().min(1).max(assessmentFocusLossSignalDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
|
||||
})
|
||||
|
||||
export type AssessmentFocusLossSignal = zod.input<typeof AssessmentFocusLossSignal>;
|
||||
export type AssessmentFocusLossSignalOutput = zod.output<typeof AssessmentFocusLossSignal>;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const AssessmentFullscreenExitSignal = zod.object({
|
||||
"kind": zod.enum(['fullscreen_exit']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
})
|
||||
|
||||
export type AssessmentFullscreenExitSignal = zod.input<typeof AssessmentFullscreenExitSignal>;
|
||||
export type AssessmentFullscreenExitSignalOutput = zod.output<typeof AssessmentFullscreenExitSignal>;
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const assessmentSignalBatchEventsItemOneDurationMsMax = 259200000;
|
||||
|
||||
export const assessmentSignalBatchEventsItemTwoSizeBytesMin = 0;
|
||||
export const assessmentSignalBatchEventsItemTwoSizeBytesMax = 2147483647;
|
||||
|
||||
export const assessmentSignalBatchEventsMax = 50;
|
||||
|
||||
|
||||
export const AssessmentSignalBatch = zod.object({
|
||||
"events": zod.array(zod.union([zod.object({
|
||||
"kind": zod.enum(['focus_loss']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
|
||||
"duration_ms": zod.int().min(1).max(assessmentSignalBatchEventsItemOneDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
|
||||
}),zod.object({
|
||||
"kind": zod.enum(['copy', 'paste', 'cut']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
|
||||
"size_bytes": zod.int().min(assessmentSignalBatchEventsItemTwoSizeBytesMin).max(assessmentSignalBatchEventsItemTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
|
||||
}),zod.object({
|
||||
"kind": zod.enum(['fullscreen_exit']),
|
||||
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
|
||||
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
|
||||
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
|
||||
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
|
||||
|
||||
export type AssessmentSignalBatch = zod.input<typeof AssessmentSignalBatch>;
|
||||
export type AssessmentSignalBatchOutput = zod.output<typeof AssessmentSignalBatch>;
|
||||
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user