From 4761508f134ba8eee50e4a8046043560581e247b Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 01:24:45 +0300 Subject: [PATCH] feat(candidate): add the candidate home, results and result history screens --- docs/en/TESTING.md | 2 + docs/ru/TESTING.md | 2 + frontend/README.en.md | 38 +- frontend/README.md | 30 +- frontend/e2e/assessment.spec.ts | 219 ++++++- frontend/e2e/candidate-home.spec.ts | 577 ++++++++++++++++++ .../app/router/candidate-home-route.test.tsx | 44 ++ .../src/app/router/candidate-home-route.tsx | 16 +- frontend/src/app/router/routes.test.tsx | 2 +- frontend/src/app/router/routes.tsx | 7 +- .../assessment/api/assessment-queries.test.ts | 128 ++++ .../assessment/api/assessment-queries.ts | 69 ++- frontend/src/entities/assessment/index.ts | 22 + .../assessment/model/actor-transition.test.ts | 102 ++++ .../assessment/model/actor-transition.ts | 36 ++ .../assessment/model/contract-validation.ts | 11 + .../model/result-presentation.test.ts | 305 +++++++++ .../assessment/model/result-presentation.ts | 368 +++++++++++ .../assessment/model/result-summary.test.ts | 46 +- .../assessment/model/result-summary.ts | 20 +- .../assessment/model/result.fixtures.ts | 150 +++++ .../src/entities/assessment/model/session.ts | 2 + .../assessment/model/use-assessment-actor.ts | 54 ++ .../assessment/ui/assessment-actor-gate.tsx | 50 ++ .../ui/assessment-result-view.module.css | 124 ++++ .../ui/assessment-result-view.test.tsx | 113 ++++ .../assessment/ui/assessment-result-view.tsx | 215 +++++++ .../candidate/api/home-queries.test.ts | 104 ++++ .../entities/candidate/api/home-queries.ts | 202 ++++++ frontend/src/entities/candidate/index.ts | 18 + .../src/entities/candidate/model/home.test.ts | 277 +++++++++ frontend/src/entities/candidate/model/home.ts | 170 ++++++ frontend/src/pages/assessment-result/index.ts | 2 + .../ui/assessment-result-page.module.css | 20 + .../ui/assessment-result-page.tsx | 142 +++++ .../ui/assessment-result-pages.test.tsx | 246 ++++++++ .../ui/assessment-results-page.tsx | 18 + .../ui/assessment-attempt-page.module.css | 24 +- .../assessment/ui/assessment-attempt-page.tsx | 63 +- frontend/src/pages/candidate-home/index.ts | 1 + .../ui/candidate-home-page.module.css | 53 ++ .../ui/candidate-home-page.test.tsx | 256 ++++++++ .../candidate-home/ui/candidate-home-page.tsx | 147 +++++ frontend/src/shared/config/paths.ts | 1 + .../src/widgets/assessment-history/index.ts | 2 + .../ui/assessment-history-list.tsx | 45 ++ .../ui/assessment-history.module.css | 87 +++ .../ui/assessment-history.test.tsx | 217 +++++++ .../ui/assessment-history.tsx | 141 +++++ .../src/widgets/candidate-next-step/index.ts | 1 + .../ui/candidate-next-step.module.css | 126 ++++ .../ui/candidate-next-step.tsx | 300 +++++++++ 52 files changed, 5334 insertions(+), 81 deletions(-) create mode 100644 frontend/e2e/candidate-home.spec.ts create mode 100644 frontend/src/app/router/candidate-home-route.test.tsx create mode 100644 frontend/src/entities/assessment/api/assessment-queries.test.ts create mode 100644 frontend/src/entities/assessment/model/actor-transition.test.ts create mode 100644 frontend/src/entities/assessment/model/actor-transition.ts create mode 100644 frontend/src/entities/assessment/model/result-presentation.test.ts create mode 100644 frontend/src/entities/assessment/model/result-presentation.ts create mode 100644 frontend/src/entities/assessment/model/result.fixtures.ts create mode 100644 frontend/src/entities/assessment/model/use-assessment-actor.ts create mode 100644 frontend/src/entities/assessment/ui/assessment-actor-gate.tsx create mode 100644 frontend/src/entities/assessment/ui/assessment-result-view.module.css create mode 100644 frontend/src/entities/assessment/ui/assessment-result-view.test.tsx create mode 100644 frontend/src/entities/assessment/ui/assessment-result-view.tsx create mode 100644 frontend/src/entities/candidate/api/home-queries.test.ts create mode 100644 frontend/src/entities/candidate/api/home-queries.ts create mode 100644 frontend/src/entities/candidate/model/home.test.ts create mode 100644 frontend/src/entities/candidate/model/home.ts create mode 100644 frontend/src/pages/assessment-result/index.ts create mode 100644 frontend/src/pages/assessment-result/ui/assessment-result-page.module.css create mode 100644 frontend/src/pages/assessment-result/ui/assessment-result-page.tsx create mode 100644 frontend/src/pages/assessment-result/ui/assessment-result-pages.test.tsx create mode 100644 frontend/src/pages/assessment-result/ui/assessment-results-page.tsx create mode 100644 frontend/src/pages/candidate-home/index.ts create mode 100644 frontend/src/pages/candidate-home/ui/candidate-home-page.module.css create mode 100644 frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx create mode 100644 frontend/src/pages/candidate-home/ui/candidate-home-page.tsx create mode 100644 frontend/src/widgets/assessment-history/index.ts create mode 100644 frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx create mode 100644 frontend/src/widgets/assessment-history/ui/assessment-history.module.css create mode 100644 frontend/src/widgets/assessment-history/ui/assessment-history.test.tsx create mode 100644 frontend/src/widgets/assessment-history/ui/assessment-history.tsx create mode 100644 frontend/src/widgets/candidate-next-step/index.ts create mode 100644 frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css create mode 100644 frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 578e397..cd12c8b 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -77,6 +77,8 @@ In the same mode, the runner invokes `/consent-fixture` from the test backend im `frontend/e2e/profile-edit.spec.ts` fills the manual profile at 360px after real registration, acknowledges overlapping employment periods, saves, and reloads the data. A second context changes the version through the API; the first window keeps its draft on 412 and replaces it only through an explicit action. The test checks frozen fields during PUT, focus, no overflow at 360/768/1280px, and rejection of a late response after an account switch. Saving a profile does not count as completion of the consent step. +`frontend/e2e/candidate-home.spec.ts` has two parts. In the mail-fixture mode a candidate goes through registration, a profile with only a name (no FSP ID linking), the questionnaire, and signing in again: the home leads to the profile, then the questionnaire, then the test, shows the declared level apart from the empty confirmed category, and matches the `GET /me/assessment-availability` answer after a page refresh. The saved step stays "Consents" throughout, because the server advances it only from the matching step. The second part also runs in the ordinary `test-e2e`: it replaces API answers (`page.route`) and checks only how the home renders each state - a category with the result and privacy links, an open card and search status, no category with an empty history, a failed attempt, a failed read with retry, a denied read, a failed privacy read, and an expired session. It does not prove backend behavior and does not replace a check of category assignment on a real stack, which this spec does not perform. Review screenshots (360 and 1280 px) contain only synthetic data. + `frontend/e2e/company-management.spec.ts` creates a company, retries a lost response with the same key and body, edits the profile, and compares its preview with the API. Controlled responses check CSRF recovery, version conflict, and a delayed response. A separate `company-fixture` performs real revocation: Go build tag `e2e`, an explicit enable flag, a random bearer token per run, no published port, and only the internal network. It validates two synthetic verified employer accounts, adds a successor owner, and revokes the original owner in one transaction while preserving the mandatory-owner constraint. The browser with its original cookie checks real API denial and removal from its directory. The control endpoint is absent from the ordinary backend and release image; its URL and token reach only the test process through `E2E_COMPANY_FIXTURE_URL` and `E2E_COMPANY_FIXTURE_TOKEN`. ## Release manifest tests diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 9d97d98..9ecd7d5 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -77,6 +77,8 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f `frontend/e2e/profile-edit.spec.ts` заполняет ручной профиль на 360 px после реальной регистрации, подтверждает пересечение периодов, сохраняет и перечитывает данные. Второй контекст меняет версию через API; первое окно сохраняет черновик при 412 и заменяет его только явным действием. Проверяются заморозка полей во время PUT, фокус, отсутствие переполнения на 360/768/1280 px и отбрасывание позднего ответа после смены аккаунта. Шаг согласий не считается завершенным сохранением профиля. +`frontend/e2e/candidate-home.spec.ts` состоит из двух частей. В режиме с почтовой фикстурой кандидат проходит регистрацию, профиль только с именем (без привязки ФСП ID), анкету и повторный вход: главная ведет к профилю, затем к анкете, затем к тесту, показывает заявленный уровень отдельно от пустой подтвержденной категории и совпадает с ответом `GET /me/assessment-availability` после обновления страницы. Сохраненный шаг при этом остается "Согласия": сервер переводит его дальше только из соответствующего шага. Вторая часть работает и в обычном `test-e2e`: она подменяет ответы API (`page.route`) и проверяет только отображение состояний главной - категория и ссылки на результат и приватность, открытая карточка и статус поиска, отсутствие категории и пустая история, неудачная попытка, ошибка чтения с повтором, отказ в доступе, сбой чтения приватности, истекшая сессия. Она не доказывает поведение backend и не заменяет проверку присвоения категории на реальном стенде, которую эта спецификация не выполняет. Скриншоты для просмотра (360 и 1280 px) содержат только синтетические данные. + `frontend/e2e/company-management.spec.ts` создает компанию, повторяет запрос после потери ответа с тем же ключом и телом, изменяет профиль и сравнивает предпросмотр с API. Управляемые ответы проверяют восстановление после CSRF-ошибки, конфликт версии и задержанный ответ. Реальный отзыв выполняет отдельный `company-fixture`: Go build tag `e2e`, явный флаг, случайный bearer token на каждый прогон, без опубликованного порта и только во внутренней сети. Утилита проверяет два синтетических подтвержденных employer-аккаунта, добавляет владельца-преемника и отзывает исходного владельца в одной транзакции, сохраняя ограничение обязательного владельца. Браузер с прежней cookie проверяет отказ реального API и исчезновение компании из своей директории. Контрольный endpoint отсутствует в обычном backend и release-образе; его URL и токен передаются только тестовому процессу через `E2E_COMPANY_FIXTURE_URL` и `E2E_COMPANY_FIXTURE_TOKEN`. ## Тесты манифеста выпуска diff --git a/frontend/README.en.md b/frontend/README.en.md index c45bdc9..dee2c93 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -2,11 +2,11 @@ [Русский](README.md) | English -A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The standalone results page, candidate directory, and employer invitations remain placeholders. +A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API; the 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, 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/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, support cases, technical status, and remaining placeholders. +- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, the result history widget `assessment-history`, and the technical `system-status` widget. - `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)) and `company`; `src/features/` holds user actions and forms. - `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. - `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)). @@ -17,11 +17,11 @@ From the repository root, `make -C frontend dev` starts development and `make -C ## Routes -| Group | Paths | Shell | -| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | -| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `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` | +| Group | Paths | Shell | +| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | +| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. `/support` sends a signed-in user to the support area for their account or to sign-in. Need pages pass `organization_id` in the query string, but the client checks the current owner directory and the server authorizes every request. @@ -49,9 +49,17 @@ 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 home + +`/candidate` opens at every saved onboarding step and does not redirect: the `pages/candidate-home` page shows the saved account step (`onboarding_step` of the current session) and leads to the next action. The "Next step" block (`widgets/candidate-next-step`) and its selection logic (`entities/candidate`, `buildCandidateJourney`) use only server answers: the profile version (`GET /me/profile`; version 0 means the profile was never saved), the questionnaire (`GET /me/questionnaire`), and the assessment availability with the confirmed grade (`GET /me/assessment-availability`). The rules apply in order: a confirmed category leads to the result and visibility settings; an empty profile leads to the profile form; an empty questionnaire leads to the questionnaire; an active attempt leads to resuming it; otherwise the test is next. The saved step is shown only: the server advances it when the profile or the questionnaire is saved from the matching step, so a saved profile can sit behind the earlier "Consents" step, and the presence of saved data decides between the profile, the questionnaire, and the test. Linking an FSP ID and ML extraction are not needed on this path and are never shown as an error or a missing condition. + +The declared level and the confirmed category are always shown apart, per specialization: the declared one comes from the questionnaire `self_assessed_grade` and is labeled as self-assessment, the confirmed one only from the availability `confirmed_grade`. The client does not derive a category from scores, thresholds, or the target grade. The page also shows the latest result (`GET /me/assessment-results?limit=1`, restated by `assessmentResultSummary`, with links to the breakdown and the history) and the profile visibility (`GET /me/privacy`: card open or closed with the reason, whether the category is shown, search status) with a link to `/candidate/privacy`. + +Every block has loading, error with retry, forbidden (401 and 403 without retry), and empty states. The three reads that the next step depends on form one state: if any of them fails, an error with retry appears instead of a step guessed from partial data. The result and the visibility are independent, so their failure does not hide the next step. Query keys contain the account id, data does not outlive the screen (`gcTime: 0`) and is read again on every open and on returning to the tab, so a page refresh shows the current API state. Signing in again still opens the saved-step page (`getOnboardingDestination`), not the home. + ## 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. +`/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 with the same component as the result page and links to it (see [Candidate results](#candidate-results)). Only the server assigns a category; the client calculates neither scores nor grades. Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate. @@ -59,6 +67,18 @@ During a real attempt, `features/assessment-signals` collects the disclosed sign Clipboard contents and typed text are never read into a signal or sent. The paste size comes from the `paste` event: file sizes (`File.size`) plus the UTF-8 length of the plain-text item of `clipboardData`; the string lives in one local variable during the count and is not kept. The Clipboard API (`navigator.clipboard`) is not used. The copy and cut size is the selection length in UTF-16 code units taken from the field offsets without reading its value; when the active field has no numeric offsets the size is zero and the page selection is not read. It is an approximate size, not an exact byte count. The answer time per item is measured by the server and not sent by the client. Event timestamps are moved to server time: the client remembers the difference between the device clock and the `Date` header of API responses, because the server rejects a whole batch when a timestamp is more than five minutes from its own clock. Durations use the device clock and do not depend on that difference. Browser signals are easy to forge and false positives are possible, so they are only a hint for a review. +## Candidate results + +`/candidate/results` lists the completed real assessments of the current candidate (`GET /me/assessment-results`, 20 records per page; the cursor comes only from the server response and is never built on the client). `/candidate/results/:attemptId` opens one record by a direct URL. Both screens read data only for a confirmed candidate session: query keys include the account identifier and the session token, data does not outlive the screen (`gcTime: 0`) and is removed when the session changes or ends. A 401, 403, or 404 response shows an "unavailable" screen without data and does not reveal whether another candidate's result exists; the assessment cache is cleared only on 401, while a network or 5xx failure offers a retry and is not treated as lost access. A failed background refresh keeps the data that was already loaded and says so. Dates are shown in the browser time zone with its name. "Show more" moves the focus to the first new row and announces how many were loaded. Loading, empty history, and error states with retry exist. A failed attempt after a successful one, adaptive estimate values, retry dates, and missing-field cases are covered by unit contract fixtures because the stand cannot produce them; the e2e test checks the shape of the flow (a real result, the express run, ownership, sign-out; the interface has no sign-out control yet, so the session ends through the API). By contract, demonstration runs are not part of the history; their result opens from the attempt screen or by a direct URL and is always marked as a demonstration. + +On the attempt screen only the phrase "Result received" is a live message; the record is ordinary content, and the focus moves to its heading. The shared `AssessmentResultView` component (`entities/assessment`) only restates the fields of the server response: + +- the category comes from `category_decision`, not from the target grade; the decision date, the method and its limitation, the "provisional" status for `uncalibrated`, the basic score, the method limitations, the practice, and the time (which does not affect the decision) are shown; +- an adaptive result shows θ, SE, the 95% interval, P_G, and the strength with the values the server returned (decimal comma, two to three digits, no recalculation); when `uncertainty`, `strength`, or the score is `null`, the rows are omitted and no zeros are substituted, and an adaptive attempt without an estimate gets a note; for `demo_basic` the screen says that no percentile, ability estimate, or P_G is calculated; +- a failed attempt shows the attempt result separately from the previous category, which stays in force; next steps come from `next_steps` in the server order under an "as of the decision" heading: the date comes from `available_at` ("Available from ..."), `null` means the step was available immediately at the decision, and the checks page shows the current availability; +- an offer to accept a lower grade (`accept_lower_grade`) is plain text only: the category does not change without a separate candidate command, and the interface has no such command yet; +- an express result is marked as a demonstration without a real grade, shows no category or estimate, and leads to the full assessment; a prepared full attempt appears as a separate history record, and the decision source is shown when the server reports one. + ## 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. diff --git a/frontend/README.md b/frontend/README.md index 8f79e1d..caed469 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -2,11 +2,11 @@ Русский | [English](README.en.md) -SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. Отдельная страница результатов, каталог кандидатов и приглашения остаются заготовками. +SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API; каталог кандидатов и приглашения остаются заготовками. - `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. -- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, компания и потребности работодателя, обращения в поддержку, технический статус и оставшиеся заготовки экранов. -- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`. +- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, обращения в поддержку, технический статус и оставшиеся заготовки экранов. +- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, виджет истории результатов `assessment-history` и технический виджет `system-status`. - `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)) и `company`; `src/features/` - действия пользователя и формы. - `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. - `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)). @@ -20,7 +20,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS | Группа | Пути | Оболочка | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | | Публичная | `/`, `/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` | +| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | | Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере. @@ -49,9 +49,17 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Конфликт 412 сохраняет черновик и предлагает явное перечитывание или замену по последней прочитанной версии. Ошибки сессии скрывают приватные ответы; ответ прежнего аккаунта не заполняет кеш заново. Переходы onboarding следуют шагу, возвращенному сервером. Сохраненный шаг анкеты открывает `/candidate/questionnaire`. +## Главная кандидата + +`/candidate` открывается на любом сохраненном шаге онбординга и не перенаправляет: страница `pages/candidate-home` показывает сохраненный шаг аккаунта (`onboarding_step` из текущей сессии) и ведет к следующему действию. Блок "Следующий шаг" (`widgets/candidate-next-step`) и логика выбора (`entities/candidate`, `buildCandidateJourney`) используют только ответы сервера: версию профиля (`GET /me/profile`, версия 0 означает, что профиль не сохранен), анкету (`GET /me/questionnaire`) и доступность проверки с подтвержденным грейдом (`GET /me/assessment-availability`). Правила по порядку: подтвержденная категория ведет к результату и настройкам видимости; пустой профиль - к форме профиля; пустая анкета - к анкете; активная попытка - к ее продолжению; иначе - к тесту. Сохраненный шаг только показывается: сервер переводит его дальше лишь при сохранении профиля или анкеты с соответствующего шага, поэтому сохраненный профиль может лежать за более ранним шагом "Согласия", и выбор между профилем, анкетой и тестом делает наличие сохраненных данных. Привязка ФСП ID и ML-разбор не нужны для этого пути и нигде не показываются как ошибка или недостающее условие. + +Заявленный уровень и подтвержденная категория всегда показаны раздельно, по специализациям: заявленный берется из `self_assessed_grade` анкеты и помечен как самооценка, подтвержденный - только из `confirmed_grade` доступности проверки. Клиент не выводит категорию из баллов, порогов или целевого грейда. Страница также показывает последний результат (`GET /me/assessment-results?limit=1`, пересказ через `assessmentResultSummary`, ссылки на разбор и историю) и видимость профиля (`GET /me/privacy`: карточка открыта или закрыта с причиной, показывается ли категория, статус поиска) со ссылкой на `/candidate/privacy`. + +Состояния загрузки, ошибки с повтором, "нет доступа" (401 и 403 без повтора) и пусто есть у каждого блока. Три чтения, от которых зависит следующий шаг, образуют одно состояние: если любое из них не удалось, показывается ошибка с повтором, а не шаг, угаданный по неполным данным. Результат и видимость независимы, поэтому их сбой не скрывает следующий шаг. Ключи запросов содержат идентификатор аккаунта, данные не живут после ухода с экрана (`gcTime: 0`) и читаются заново при каждом открытии и возврате на вкладку, так что обновление страницы показывает актуальное состояние API. Вход после выхода по-прежнему ведет на страницу сохраненного шага (`getOnboardingDestination`), а не на главную. + ## Проверка кандидата -`/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. `demo_express` помечен как демонстрационный и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки, но отдельный маршрут `/candidate/results` пока остается заглушкой; история результатов и присвоение подтвержденных категорий не реализованы. Клиент не вычисляет баллы. +`/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. `demo_express` помечен как демонстрационный и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки тем же компонентом, что и страница результатов, со ссылкой на нее (см. [результаты кандидата](#результаты-кандидата)). Категорию присваивает только сервер; клиент не вычисляет баллы и грейды. Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным. @@ -59,6 +67,18 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Содержимое буфера и вводимый текст не читаются в сигнал и не отправляются. Размер вставки берется из события `paste`: размер файлов (`File.size`) и длина обычного текста в байтах UTF-8 из `clipboardData`; строка живет в одной локальной переменной на время подсчета и не сохраняется. Clipboard API (`navigator.clipboard`) не используется. Размер копирования и вырезания - длина выделения в единицах UTF-16 по смещениям поля, без чтения его значения; если у активного поля нет числовых смещений, размер равен нулю, а выделение страницы не читается. Это приблизительный размер, а не точный счет байтов. Время ответа по заданию измеряет сервер, клиент его не присылает. Время событий приводится к серверному: клиент запоминает разницу между часами устройства и заголовком `Date` ответов API, потому что сервер отклоняет весь пакет, если метка времени выходит за пять минут от его часов. Длительности считаются по часам устройства и от этой разницы не зависят. Браузерные сигналы легко подделать, а ложные срабатывания возможны, поэтому они только подсказка для перепроверки. +## Результаты кандидата + +`/candidate/results` показывает историю завершенных реальных проверок текущего кандидата (`GET /me/assessment-results`, по 20 записей, курсор берется только из ответа сервера и не строится на клиенте). `/candidate/results/:attemptId` открывает одну запись по прямому URL. Оба экрана читают данные только при подтвержденной сессии кандидата: ключи запросов содержат идентификатор аккаунта и токен сессии, данные не живут после ухода с экрана (`gcTime: 0`) и удаляются при смене или потере сессии. Ответ 401, 403 или 404 дает экран "недоступно" без данных и не раскрывает, существует ли чужой результат; кеш ассессмента очищается только при 401, а сбой сети или 5xx предлагает повтор и не считается потерей доступа. Неудачное фоновое обновление оставляет уже загруженные данные и сообщает об этом. Даты показываются в часовом поясе браузера с его названием. "Показать еще" переносит фокус на первую новую запись и сообщает о числе загруженных. Есть состояния загрузки, пустой истории и ошибки с повтором. Неудачная попытка после успешной, значения адаптивной оценки, даты пересдачи и случаи без полей покрыты модульными фикстурами контракта: на стенде их получить нельзя, e2e проверяет форму потока (реальный результат, экспресс, владение, выход из аккаунта; в интерфейсе пока нет кнопки выхода, сессия завершается через API). Демонстрационные запуски по контракту в историю не входят; их результат открывается по ссылке из экрана попытки или по прямому URL и всегда помечен как демонстрация. + +На экране попытки живым сообщением остается только фраза "Результат получен", запись результата - обычное содержимое, а фокус переходит на ее заголовок. Общий компонент `AssessmentResultView` (`entities/assessment`) только пересказывает поля серверного ответа: + +- категория берется из `category_decision`, а не из целевого грейда; видны дата решения, метод и его ограничение, статус "предварительный" при `uncalibrated`, баллы базовой проверки, ограничения метода, практика и время (время не влияет на решение); +- для адаптивного результата показаны θ, SE, 95% интервал, P_G и сила подтверждения с теми значениями, что вернул сервер (запятая, два-три знака, без пересчета); если `uncertainty`, `strength` или баллы равны `null`, строки не выводятся и нули не подставляются, а для адаптивной попытки без оценки показана пометка; для `demo_basic` прямо сказано, что перцентиль, оценка способности и P_G не рассчитываются; +- неудачная попытка показывает отдельный результат попытки и прежнюю категорию, которая сохраняется; следующие шаги выводятся из `next_steps` в порядке сервера под заголовком "на момент решения": дата берется из `available_at` ("Доступно с ..."), `null` значит, что шаг был доступен сразу при решении, а актуальную доступность показывает страница проверок; +- предложение принять меньший грейд (`accept_lower_grade`) выводится только текстом: категория не меняется без отдельной команды кандидата, такой команды в интерфейсе пока нет; +- экспресс-результат помечен как демонстрация без реального грейда, не показывает категорию и оценку и ведет к полной проверке; подготовленная полная попытка показывается отдельной записью истории, а источник решения выводится, если его вернул сервер. + ## Настройки приватности `/candidate/privacy` сейчас показывает управление согласиями и переход к запросу ручной оценки. Публикация карточки, статус поиска, список скрытых организаций, предпросмотр и история доступны через backend API, но отдельный интерфейс для этих настроек еще не реализован. Каталог кандидатов работодателя также остается заглушкой; наличие серверного API чтения анонимной карточки не означает наличия такого экрана. diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index c8a62e7..8029d02 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -1,4 +1,12 @@ -import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test"; +import { + expect, + test, + type Locator, + type Page, + type Request, + type Response, + type Route, +} from "@playwright/test"; type InboxMessage = { text?: string; @@ -57,7 +65,7 @@ function verificationToken(message: InboxMessage): string { return token; } -async function registerVerifiedCandidate(page: Page): Promise { +async function registerVerifiedCandidate(page: Page): Promise { const email = `assessment-${crypto.randomUUID()}@example.test`; await page.goto("/register"); await expect( @@ -98,6 +106,7 @@ async function registerVerifiedCandidate(page: Page): Promise { ); await page.getByRole("button", { name: "Войти" }).click(); expect((await loginResponse).status()).toBe(201); + return email; } async function grantC3(page: Page): Promise { @@ -846,3 +855,209 @@ test("a failed signal batch is retried with the same key while the answer is sav await page.waitForTimeout(3_000); expect(signalRequests.filter((item) => item.key === first?.key)).toHaveLength(2); }); + +const resultHeading = "Результат с сервера"; +const expressBanner = + "Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд."; + +function isFinalizeResponse(response: Response, attemptId: string): boolean { + return ( + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/finalize` + ); +} + +/** Creates an attempt from the assessment page, resumes it, and answers every item. */ +async function runAttemptToResult( + page: Page, + start: { name: string; confirmNotice: boolean }, +): Promise { + const createResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await page.getByRole("button", { name: start.name }).click(); + if (start.confirmNotice) await page.getByRole("button", { name: confirmNoticeName }).click(); + const attempt = (await (await createResponse).json()) as AttemptSnapshot; + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); + + const resumeResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const resumed = (await (await resumeResponse).json()) as AttemptSnapshot; + await answerRequiredNumericItems(page, attempt.id, resumed.progress.max_items); + + const finalizeResponse = page.waitForResponse((response) => + isFinalizeResponse(response, attempt.id), + ); + await page.getByRole("button", { name: "Завершить проверку" }).click(); + expect((await finalizeResponse).status()).toBe(200); + await expect(page.getByRole("heading", { name: resultHeading })).toBeVisible(); + return attempt.id; +} + +async function signOut(page: Page): Promise { + const status = await page.evaluate(async () => { + const current = await fetch("/api/v1/identity/sessions/current", { + credentials: "same-origin", + }); + const session = (await current.json()) as { csrf_token: string }; + const response = await fetch("/api/v1/identity/sessions/current", { + method: "DELETE", + credentials: "same-origin", + headers: { "X-CSRF-Token": session.csrf_token }, + }); + return response.status; + }); + expect(status).toBe(204); +} + +async function signIn(page: Page, email: string): Promise { + 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); +} + +// Browser coverage here is the shape of the flow (a real result, the express +// run, ownership, and sign-out). The stand cannot produce a failed attempt +// after a successful one or an adaptive estimate, so those values, the retry +// dates, and the missing-field cases are covered by the unit fixtures. +test("results keep the express run apart and stay private to the signed-in candidate", async ({ + page, + browser, +}) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(240_000); + + const email = await registerVerifiedCandidate(page); + await grantC3(page); + await saveAssessmentQuestionnaire(page); + await page.goto("/candidate/assessment"); + await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); + await page.getByLabel("Язык задания").selectOption("python"); + + // The full result: method, date, category state, and the provisional status. + const realResult = page.waitForResponse( + (response) => + response.request().method() === "GET" && + response.status() === 200 && + /^\/api\/v1\/me\/assessment-attempts\/[^/]+\/result$/.test(new URL(response.url()).pathname), + ); + const realId = await runAttemptToResult(page, { + name: "Начать полную проверку", + confirmNotice: true, + }); + const stored = (await (await realResult).json()) as { mode: "demo_basic" | "adaptive" }; + // Only a short phrase is a live message; the record is ordinary content and + // the focus moved to its heading. + await expect(page.getByRole("heading", { name: resultHeading })).toBeFocused(); + await expect(page.getByRole("status").filter({ hasText: "Результат получен" })).toHaveCount(1); + await expect(page.getByRole("status").getByRole("article")).toHaveCount(0); + const inline = page.getByRole("article"); + await expect(inline.getByText("Метод и ограничения")).toBeVisible(); + await expect(inline.getByText("Категория после этого результата", { exact: true })).toBeVisible(); + await expect(inline.getByText("Дата решения", { exact: true })).toBeVisible(); + await expect(inline.getByText("Предварительный результат")).toBeVisible(); + if (stored.mode === "demo_basic") { + await expect(inline.getByText(/Перцентиль, оценка способности, интервал/)).toBeVisible(); + await expect(inline.getByText("Стандартная ошибка (SE)")).toHaveCount(0); + } + await expect(page.getByRole("link", { name: "Открыть на странице результатов" })).toHaveAttribute( + "href", + `/candidate/results/${realId}`, + ); + await expectNoHorizontalOverflow(page, 360); + await expectNoHorizontalOverflow(page, 1280); + + // The express run is a demonstration: no category, and it offers the full test. + await page.goto("/candidate/assessment"); + await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible(); + const expressId = await runAttemptToResult(page, { + name: "Начать демонстрацию", + confirmNotice: false, + }); + await expect(page.getByText(expressBanner)).toBeVisible(); + await expect(page.getByText("не присваивается", { exact: true })).toBeVisible(); + await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0); + await page.getByRole("link", { name: "Перейти к полной проверке" }).click(); + await expect(page).toHaveURL(/\/candidate\/assessment$/); + await expect(page.getByRole("heading", { name: "Проверка знаний", level: 1 })).toBeVisible(); + + // History: only the real result; the express run does not replace or join it. + await page.goto("/candidate/results"); + await expect(page.getByRole("heading", { name: "Результаты проверок", level: 1 })).toBeVisible(); + const history = page.getByRole("list", { name: "История результатов" }); + await expect(history.getByRole("listitem")).toHaveCount(1); + await expect(history.getByRole("link")).toHaveAttribute("href", `/candidate/results/${realId}`); + await expect(page.locator(`a[href$="${expressId}"]`)).toHaveCount(0); + await expect(page.getByText(/Демонстрационные запуски сюда не попадают/)).toBeVisible(); + await expectNoHorizontalOverflow(page, 360); + await page.screenshot({ + path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/assessment-history-360.png`, + animations: "disabled", + }); + await expectNoHorizontalOverflow(page, 1280); + + // The stored real result opens by its URL and is not a demonstration. + await history.getByRole("link").click(); + await expect(page).toHaveURL(new RegExp(`/candidate/results/${realId}$`)); + await expect(page.getByRole("heading", { name: "Результат проверки", level: 1 })).toBeVisible(); + await expect(page.getByText("Основная проверка", { exact: true })).toBeVisible(); + await expect(page.getByText(expressBanner)).toHaveCount(0); + + // The express result opens by its own URL, still without a category. + await page.goto(`/candidate/results/${expressId}`); + await expect(page.getByText(expressBanner)).toBeVisible(); + await expect(page.getByRole("link", { name: "Перейти к полной проверке" })).toBeVisible(); + + // Another candidate cannot read the history or the result by a direct URL. + const otherContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + try { + const other = await otherContext.newPage(); + await registerVerifiedCandidate(other); + await other.goto("/candidate/results"); + await expect(other.getByText("Результатов пока нет")).toBeVisible(); + await expect(other.locator(`a[href$="${realId}"]`)).toHaveCount(0); + await other.goto(`/candidate/results/${realId}`); + await expect(other.getByText("Результат недоступен")).toBeVisible(); + await expect(other.getByText("Метод и ограничения")).toHaveCount(0); + } finally { + await otherContext.close(); + } + + // After sign-out the SPA keeps its in-memory state. The app has no sign-out + // control yet, so the session ends through the API; moving inside the app + // must then show no stored data, and a fresh load must ask for sign-in. + await navigateInApp(page, "/candidate/results"); + await expect(history.getByRole("listitem")).toHaveCount(1); + await signOut(page); + expect((await page.request.get("/api/v1/me/assessment-results")).status()).toBe(401); + await navigateInApp(page, `/candidate/results/${realId}`); + await expect(page.getByText(/недоступ/).first()).toBeVisible(); + await expect(page.getByText("Метод и ограничения")).toHaveCount(0); + await navigateInApp(page, "/candidate/results"); + await expect(page.getByText(/недоступ/).first()).toBeVisible(); + await expect(history.getByRole("listitem")).toHaveCount(0); + await page.goto(`/candidate/results/${realId}`); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await expect(page.getByText("Метод и ограничения")).toHaveCount(0); + + // Signing in again restores the permitted screen. + await signIn(page, email); + await navigateInApp(page, "/candidate/results"); + await expect(history.getByRole("listitem")).toHaveCount(1); +}); diff --git a/frontend/e2e/candidate-home.spec.ts b/frontend/e2e/candidate-home.spec.ts new file mode 100644 index 0000000..852e232 --- /dev/null +++ b/frontend/e2e/candidate-home.spec.ts @@ -0,0 +1,577 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +type InboxMessage = { + id?: string; + text?: string; + html?: string; +}; + +type InboxResponse = { + messages: InboxMessage[]; +}; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const password = "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 expectNoHorizontalOverflow(page: Page): Promise { + for (const width of [360, 768, 1280]) { + await page.setViewportSize({ width, height: 900 }); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(overflow, `no horizontal overflow at ${width}px`).toBe(false); + } +} + +// Review screenshots contain only synthetic data from the stubbed answers. +async function captureReviewScreenshots(page: Page, name: string): Promise { + const directory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"; + for (const width of [360, 1280]) { + await page.setViewportSize({ width, height: 1400 }); + await page.screenshot({ + path: `${directory}/${name}-${width}.png`, + animations: "disabled", + fullPage: true, + }); + } +} + +async function expectKeyboardReachesLink(page: Page, name: string): Promise { + const link = page.getByRole("link", { name, exact: true }).first(); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + for (let attempt = 0; attempt < 60; attempt += 1) { + await page.keyboard.press("Tab"); + if (await link.evaluate((element) => element === document.activeElement)) { + const hasRing = await link.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(hasRing, `visible keyboard focus on "${name}"`).toBe(true); + return; + } + } + throw new Error(`Keyboard navigation did not reach the link "${name}".`); +} + +// The first group runs against the real backend and needs the mail fixture to +// confirm the address. The second group answers every API call itself, so it +// checks how the screen renders each state, not how the backend behaves. +test.describe("candidate home with the real backend", () => { + test.skip(!mailFixtureEnabled, "Requires the local mail fixture target."); + + async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) { + throw new Error("The local registration mailbox 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 waitForVerification(email: string): Promise { + 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 register(page: Page): Promise { + const email = `home-${crypto.randomUUID()}@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 verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${verificationToken(await waitForVerification(email))}`; + await page.goto(verificationUrl.toString()); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + return email; + } + + async function signIn(page: Page, email: string): Promise { + await page.goto("/candidate"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await loginResponse).status()).toBe(201); + } + + function isApiPath(pathname: string) { + return (response: { url(): string; request(): { method(): string } }) => + response.request().method() === "GET" && new URL(response.url()).pathname === pathname; + } + + test("a new candidate moves from the empty profile to the test without linking any account", async ({ + page, + }) => { + test.setTimeout(120_000); + const email = await register(page); + await signIn(page, email); + await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible(); + + // Empty profile: the home leads to the form and asks for nothing else. + await page.getByRole("link", { name: "Главная", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Главная", level: 1 })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Заполните профиль" })).toBeVisible(); + await expect(page.getByText(/Сохраненный шаг аккаунта: Согласия/)).toBeVisible(); + await expect(page.getByText(/Привязка ФСП ID необязательна/)).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + await expect(page.getByText("Анкета еще не сохранена")).toBeVisible(); + await expectNoHorizontalOverflow(page); + await page.setViewportSize({ width: 1280, height: 900 }); + await expectKeyboardReachesLink(page, "Заполнить профиль"); + + await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click(); + await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible(); + await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат"); + const profileSaved = page.waitForResponse( + (response) => + response.request().method() === "PUT" && + new URL(response.url()).pathname === "/api/v1/me/profile", + ); + await page.getByRole("button", { name: "Сохранить профиль" }).click(); + expect((await profileSaved).status()).toBe(200); + + // Filled profile: the next step is the questionnaire. + await page.getByRole("link", { name: "Главная", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Заполните анкету" })).toBeVisible(); + await page.getByRole("link", { name: "Заполнить анкету", exact: true }).first().click(); + await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByLabel("Моя оценка уровня").selectOption("middle"); + await page.getByRole("checkbox", { name: "Python", exact: true }).check(); + await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + const questionnaireSaved = page.waitForResponse( + (response) => + response.request().method() === "PUT" && + new URL(response.url()).pathname === "/api/v1/me/questionnaire", + ); + await page.getByRole("button", { name: "Сохранить анкету" }).click(); + expect((await questionnaireSaved).status()).toBe(200); + + // Saved questionnaire, no category: the test is next and the declared + // grade is shown apart from the (absent) confirmed category. + const availability = page.waitForResponse(isApiPath("/api/v1/me/assessment-availability")); + await page.getByRole("link", { name: "Главная", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + const availabilityBody = (await (await availability).json()) as { + specializations: { specialization: string; confirmed_grade: string | null }[]; + }; + expect(availabilityBody.specializations[0]).toMatchObject({ + specialization: "backend", + confirmed_grade: null, + }); + await expect(page.getByText("Заявлено: Middle")).toBeVisible(); + await expect(page.getByText("Пока не подтверждена")).toBeVisible(); + await expect(page.getByText(/Подтверждено тестом:/)).toHaveCount(0); + // The server advances the stored step only from the matching step, so it + // still reads "Согласия" here; the next step follows the saved data. + await expect(page.getByText(/Сохраненный шаг аккаунта: Согласия/)).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + + // A refresh reads the same server state again. + const refreshed = page.waitForResponse(isApiPath("/api/v1/me/assessment-availability")); + await page.reload(); + expect((await refreshed).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + await expect(page.getByText("Заявлено: Middle")).toBeVisible(); + + // Returning after signing in again: the saved step opens first, and the + // home shows the same state as before. + await page.context().clearCookies(); + await signIn(page, email); + await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible(); + await page.getByRole("link", { name: "Главная", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + await expect(page.getByText("Заявлено: Middle")).toBeVisible(); + }); +}); + +const accountId = "11111111-1111-4111-8111-111111111111"; +const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80"; + +type Stub = { status: number; body: unknown }; + +type Scenario = { + step?: string; + profileVersion?: number; + declared?: { specialization: string; grade: string }; + confirmed?: string | null; + results?: unknown[]; + privacy?: unknown; + /** Replaces the answer for one API path, for error and forbidden states. */ + stubs?: Record; +}; + +function problem(status: number, code: string, title: string): Stub { + return { + status, + body: { type: `urn:lincodex:problem:${code}`, title, status, code }, + }; +} + +function realResult(outcome: "confirmed" | "not_confirmed") { + const confirmed = outcome === "confirmed"; + return { + attempt_id: attemptId, + specialization: "backend", + target_grade: "junior", + root_attempt_id: null, + chain_deadline: null, + task_language: "python", + kind: "root", + mode: "demo_basic", + versions: { + policy_version: 1, + bank_version: "backend-demo.2026-10.1", + algorithm_version: "basic.1", + }, + outcome, + not_determined_reason: null, + confirmed_grade: confirmed ? "junior" : null, + previous_confirmed_grade: null, + category_decision: { + status: confirmed ? "assigned" : "not_confirmed", + previous_confirmed_grade: null, + current_confirmed_grade: confirmed ? "junior" : null, + method: confirmed ? "demo_basic_pass_mark" : null, + source: confirmed ? "synthetic_demo" : null, + calibration_status: "uncalibrated", + }, + strength: null, + calibration_status: "uncalibrated", + limitations: ["demo_bank"], + uncertainty: null, + basic_score: null, + practices: [], + gaps: [], + durations: { items_seconds: 600, practice_seconds: null }, + next_steps: [], + decided_at: "2026-10-08T10:00:00Z", + }; +} + +const closedPrivacy = { + publication: { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, + }, + search_status: { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, + }, + hidden_organizations_total: 0, +}; + +function scenarioAnswer(scenario: Scenario, pathname: string): Stub { + const stub = scenario.stubs?.[pathname]; + if (stub) return stub; + const declared = scenario.declared; + switch (pathname) { + case "/api/v1/identity/sessions/current": + return { + status: 200, + body: { + account: { + id: accountId, + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: scenario.step ?? "candidate_profile", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), + }, + }; + case "/api/v1/me/profile": + // The home reads only the version; the profile form is not opened here. + return { status: 200, body: { version: scenario.profileVersion ?? 0 } }; + case "/api/v1/me/questionnaire": + return { + status: 200, + body: { + version: declared ? 1 : 0, + specializations: declared + ? [ + { + specialization: declared.specialization, + self_assessed_grade: declared.grade, + task_languages: [], + stack: [], + experience: null, + }, + ] + : [], + work_context: null, + updated_at: declared ? "2026-10-07T12:30:00Z" : null, + }, + }; + case "/api/v1/me/assessment-availability": + return { + status: 200, + body: { + specializations: declared + ? [ + { + specialization: declared.specialization, + confirmed_grade: scenario.confirmed ?? null, + active_attempt_id: null, + grades: [ + { + grade: declared.grade, + status: "available", + mode: "demo_basic", + available_at: null, + time_limit_seconds: 3600, + max_sessions: 2, + max_items: 20, + practice_required: false, + }, + ], + }, + ] + : [], + }, + }; + case "/api/v1/me/assessment-results": + return { + status: 200, + body: { + items: scenario.results ?? [], + page: { has_more: false, next_cursor: null }, + }, + }; + case "/api/v1/me/privacy": + return { status: 200, body: scenario.privacy ?? closedPrivacy }; + default: + return problem(404, "not_found", "Not found"); + } +} + +async function mockCandidateApi(page: Page, scenario: Scenario): Promise { + await page.route("**/api/v1/**", async (route: Route) => { + const { pathname } = new URL(route.request().url()); + const answer = + route.request().method() === "GET" + ? scenarioAnswer(scenario, pathname) + : problem(405, "method_not_allowed", "Method not allowed"); + await route.fulfill({ + status: answer.status, + contentType: answer.status >= 400 ? "application/problem+json" : "application/json", + body: JSON.stringify(answer.body), + }); + }); +} + +test.describe("candidate home states with a stubbed API", () => { + test("shows the declared grade and the confirmed category apart and links to the result and privacy", async ({ + page, + }) => { + await mockCandidateApi(page, { + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "middle" }, + confirmed: "junior", + results: [realResult("confirmed")], + }); + await page.goto("/candidate"); + + await expect(page.getByRole("heading", { name: "Категория получена" })).toBeVisible(); + await expect(page.getByText("Заявлено: Middle")).toBeVisible(); + await expect(page.getByText("Подтверждено тестом: Junior")).toBeVisible(); + await expect(page.getByText(/Закрыта: компании ее не видят/)).toBeVisible(); + await expect(page.getByRole("link", { name: "Открыть результат" })).toHaveAttribute( + "href", + "/candidate/results", + ); + await expect( + page.getByRole("link", { name: "Настроить видимость", exact: true }), + ).toHaveAttribute("href", "/candidate/privacy"); + await expect(page.getByRole("link", { name: "Открыть разбор результата" })).toHaveAttribute( + "href", + `/candidate/results/${attemptId}`, + ); + await expect(page.getByRole("alert")).toHaveCount(0); + await expectNoHorizontalOverflow(page); + await captureReviewScreenshots(page, "candidate-home-category"); + }); + + test("shows an open card and an active search status exactly as the API returns them", async ({ + page, + }) => { + await mockCandidateApi(page, { + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "junior" }, + confirmed: "junior", + results: [realResult("confirmed")], + privacy: { + publication: { + state: "published", + closed_reason: null, + fields: ["categories", "stack"], + consent_id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81", + published_at: "2026-10-08T10:00:00Z", + version: 2, + }, + search_status: { + value: "looking", + lapsed: false, + confirmed_at: "2026-10-08T10:00:00Z", + lapses_at: "2099-11-07T10:00:00Z", + version: 1, + }, + hidden_organizations_total: 0, + }, + }); + await page.goto("/candidate"); + + await expect(page.getByText("Открыта: компании видят выбранные поля")).toBeVisible(); + await expect(page.getByText("Показывается", { exact: true })).toBeVisible(); + await expect(page.getByText(/Ищу работу, статус действует до/)).toBeVisible(); + }); + + test("without a category the test stays next and a missing result is not an error", async ({ + page, + }) => { + await mockCandidateApi(page, { + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "middle" }, + results: [], + }); + await page.goto("/candidate"); + + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + await expect( + page.getByRole("link", { name: "Перейти к тесту", exact: true }).first(), + ).toHaveAttribute("href", "/candidate/assessment"); + await expect(page.getByText("Пока не подтверждена")).toBeVisible(); + await expect(page.getByText(/Подтверждено тестом:/)).toHaveCount(0); + await expect(page.getByText("Завершенных попыток пока нет")).toBeVisible(); + await expect(page.getByText(/Привязка ФСП ID необязательна/)).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + await captureReviewScreenshots(page, "candidate-home-no-category"); + }); + + test("a failed attempt keeps the category empty and the test available", async ({ page }) => { + await mockCandidateApi(page, { + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "junior" }, + results: [realResult("not_confirmed")], + }); + await page.goto("/candidate"); + + await expect(page.getByText("Уровень пока не подтвержден: Backend, Junior.")).toBeVisible(); + await expect(page.getByText("Пока не подтверждена")).toBeVisible(); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + }); + + test("a failed read shows an error with retry instead of a guessed step", async ({ page }) => { + let fail = true; + await mockCandidateApi(page, { + profileVersion: 1, + declared: { specialization: "backend", grade: "junior" }, + }); + await page.route("**/api/v1/me/assessment-availability", async (route) => { + if (fail) { + await route.fulfill({ + status: 500, + contentType: "application/problem+json", + body: JSON.stringify(problem(500, "internal", "Internal error").body), + }); + return; + } + await route.fallback(); + }); + await page.goto("/candidate"); + + const alert = page.getByRole("alert"); + await expect(alert).toContainText("Не удалось определить следующий шаг"); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Заполните профиль" })).toHaveCount(0); + + fail = false; + await alert.getByRole("button", { name: "Повторить" }).click(); + await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + }); + + test("a denied read shows the forbidden state without a retry", async ({ page }) => { + await mockCandidateApi(page, { + stubs: { "/api/v1/me/profile": problem(403, "forbidden", "Forbidden") }, + }); + await page.goto("/candidate"); + + await expect(page.getByText("Нет доступа")).toBeVisible(); + await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0); + }); + + test("a failed privacy read does not hide the next step", async ({ page }) => { + await mockCandidateApi(page, { + profileVersion: 0, + stubs: { "/api/v1/me/privacy": problem(500, "internal", "Internal error") }, + }); + await page.goto("/candidate"); + + await expect(page.getByRole("heading", { name: "Заполните профиль" })).toBeVisible(); + await expect( + page.getByRole("link", { name: "Заполнить профиль", exact: true }).first(), + ).toHaveAttribute("href", "/candidate/profile"); + await expect(page.getByRole("alert")).toContainText("Сервис временно недоступен"); + }); + + test("an expired session sends the candidate to sign-in", async ({ page }) => { + await mockCandidateApi(page, { + stubs: { + "/api/v1/identity/sessions/current": problem(401, "unauthenticated", "Unauthenticated"), + }, + }); + await page.goto("/candidate"); + + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + }); +}); diff --git a/frontend/src/app/router/candidate-home-route.test.tsx b/frontend/src/app/router/candidate-home-route.test.tsx new file mode 100644 index 0000000..6c607f0 --- /dev/null +++ b/frontend/src/app/router/candidate-home-route.test.tsx @@ -0,0 +1,44 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToString } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../shared/api/schemas"; +import { CandidateHomeRoute } from "./candidate-home-route"; + +function render(step: Session["account"]["onboarding_step"]): string { + const queryClient = new QueryClient(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: step, + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), + } satisfies Session); + return renderToString( + + + + + , + ); +} + +describe("CandidateHomeRoute", () => { + it.each([ + "candidate_consents", + "candidate_profile", + "candidate_questionnaire", + "candidate_assessment", + "completed", + ] as const)("shows the home at the saved step %s instead of redirecting", (step) => { + const html = render(step); + + expect(html).toMatch(/]*>Главная<\/h1>/); + expect(html).toContain("Определяем следующий шаг..."); + }); +}); diff --git a/frontend/src/app/router/candidate-home-route.tsx b/frontend/src/app/router/candidate-home-route.tsx index a95a334..4450a97 100644 --- a/frontend/src/app/router/candidate-home-route.tsx +++ b/frontend/src/app/router/candidate-home-route.tsx @@ -1,13 +1,9 @@ -import { Navigate } from "react-router-dom"; -import { getOnboardingDestination } from "../../entities/session"; -import { PlaceholderPage } from "../../pages/placeholder"; -import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity"; +import { CandidateHomePage } from "../../pages/candidate-home"; +/** + * The candidate home opens at every saved onboarding step: it shows the saved + * step and leads to the next action itself instead of redirecting away. + */ export function CandidateHomeRoute() { - const session = useGetCurrentSession(); - if (!session.data) return ; - if (session.data.account.onboarding_step !== "completed") { - return ; - } - return ; + return ; } diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 6a99a3b..4921a43 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -283,7 +283,7 @@ describe("product readiness", () => { }); it("labels the remaining cabinet scaffolds as placeholders", async () => { - for (const path of ["/candidate", "/employer/candidates"]) { + for (const path of ["/candidate/invitations", "/employer/candidates"]) { expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач"); } }); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 1946e5f..07a0524 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -1,5 +1,6 @@ import { redirect, type RouteObject } from "react-router-dom"; import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment"; +import { AssessmentResultPage, AssessmentResultsPage } from "../../pages/assessment-result"; import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; import { CompanyPage } from "../../pages/company"; @@ -74,10 +75,8 @@ export const routes: RouteObject[] = [ path: `${paths.candidate.assessment}/:attemptId`, element: , }, - { - path: paths.candidate.results, - element: , - }, + { path: paths.candidate.results, element: }, + { path: `${paths.candidate.results}/:attemptId`, element: }, { path: paths.candidate.invitations, element: , diff --git a/frontend/src/entities/assessment/api/assessment-queries.test.ts b/frontend/src/entities/assessment/api/assessment-queries.test.ts new file mode 100644 index 0000000..f2be950 --- /dev/null +++ b/frontend/src/entities/assessment/api/assessment-queries.test.ts @@ -0,0 +1,128 @@ +import { QueryClient } from "@tanstack/react-query"; +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { invalidResponseCode } from "../../../shared/api"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; +import { demoBasicAssigned, notConfirmedAfterJunior } from "../model/result.fixtures"; +import { assessmentResultHistoryOptions } from "./assessment-queries"; + +const server = setupServer(); +const historyUrl = "http://localhost/api/v1/me/assessment-results"; + +const session = { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), +} satisfies Session; + +beforeAll(() => server.listen()); +afterEach(() => { + vi.unstubAllGlobals(); + server.resetHandlers(); +}); +afterAll(() => server.close()); + +function signedInClient(): QueryClient { + const queryClient = new QueryClient(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), session); + return queryClient; +} + +function stubRelativeFetch() { + const realFetch = globalThis.fetch; + vi.stubGlobal("fetch", (input: string, init?: RequestInit) => + realFetch(new URL(input, "http://localhost"), init), + ); +} + +describe("assessmentResultHistoryOptions", () => { + it("reads pages with the server cursor and stops when the server says so", async () => { + stubRelativeFetch(); + const requests: URL[] = []; + server.use( + http.get(historyUrl, ({ request }) => { + const url = new URL(request.url); + requests.push(url); + return url.searchParams.has("cursor") + ? HttpResponse.json({ + items: [notConfirmedAfterJunior()], + page: { has_more: false, next_cursor: null }, + }) + : HttpResponse.json({ + items: [demoBasicAssigned()], + page: { has_more: true, next_cursor: "cursor_page_2" }, + }); + }), + ); + const queryClient = signedInClient(); + const data = await queryClient.fetchInfiniteQuery({ + ...assessmentResultHistoryOptions({ actor: session, queryClient }), + pages: 3, + }); + + expect(data.pages).toHaveLength(2); + expect(requests.map((url) => url.search)).toEqual([ + "?limit=20", + "?limit=20&cursor=cursor_page_2", + ]); + }); + + it("rejects a page that does not match the contract", async () => { + stubRelativeFetch(); + server.use( + http.get(historyUrl, () => + HttpResponse.json({ + items: [{ attempt_id: "not-a-result" }], + page: { has_more: false, next_cursor: null }, + }), + ), + ); + const queryClient = signedInClient(); + await expect( + queryClient.fetchInfiniteQuery( + assessmentResultHistoryOptions({ actor: session, queryClient }), + ), + ).rejects.toMatchObject({ code: invalidResponseCode }); + }); + + it("sends no request when the cached session is not the actor session", async () => { + stubRelativeFetch(); + const requested = vi.fn(); + server.use( + http.get(historyUrl, () => { + requested(); + return HttpResponse.json({ items: [], page: { has_more: false, next_cursor: null } }); + }), + ); + const queryClient = new QueryClient(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + ...session, + account: { ...session.account, id: "22222222-2222-4222-8222-222222222222" }, + }); + await expect( + queryClient.fetchInfiniteQuery( + assessmentResultHistoryOptions({ actor: session, queryClient }), + ), + ).rejects.toThrow("candidate session changed"); + expect(requested).not.toHaveBeenCalled(); + }); + + it("keeps the history of different sessions under different keys", () => { + const queryClient = signedInClient(); + const mine = assessmentResultHistoryOptions({ actor: session, queryClient }).queryKey; + const other = assessmentResultHistoryOptions({ + actor: { ...session, csrf_token: "B".repeat(43) }, + queryClient, + }).queryKey; + expect(mine).not.toEqual(other); + expect(mine).toContain(session.account.id); + }); +}); diff --git a/frontend/src/entities/assessment/api/assessment-queries.ts b/frontend/src/entities/assessment/api/assessment-queries.ts index 2ec5222..ae18443 100644 --- a/frontend/src/entities/assessment/api/assessment-queries.ts +++ b/frontend/src/entities/assessment/api/assessment-queries.ts @@ -1,9 +1,15 @@ -import { useQuery, type QueryClient } from "@tanstack/react-query"; +import { + infiniteQueryOptions, + useInfiniteQuery, + useQuery, + type QueryClient, +} from "@tanstack/react-query"; import { acknowledgeMyAssessmentSignalNotice, getMyAssessmentAvailability, getMyAssessmentAttempt, getMyAssessmentResult, + listMyAssessmentResults, getMyAssessmentSignalNotice, } from "../../../shared/api/endpoints/assessment/assessment"; import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate"; @@ -11,17 +17,23 @@ import type { AssessmentAttempt, AssessmentAvailability, AssessmentResult, + AssessmentResultHistoryPage, AssessmentSignalNotice, Session, } from "../../../shared/api/schemas"; import { parseAssessmentAvailabilityResponse, parseAssessmentAttemptResponse, + parseAssessmentResultHistoryResponse, parseAssessmentResultResponse, parseAssessmentSignalNoticeResponse, parseCandidateQuestionnaireResponse, } from "../model/contract-validation"; -import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session"; +import { + assessmentQueryKeys, + assessmentQueryPrefix, + assertCurrentAssessmentSession, +} from "../model/session"; type AssessmentQueryOptions = { enabled?: boolean; @@ -45,7 +57,7 @@ export function useAssessmentAvailability({ return useQuery({ queryKey: actor ? assessmentQueryKeys.availability(actor) - : [...assessmentQueryKeysPrefix, "availability"], + : [...assessmentQueryPrefix, "availability"], enabled: Boolean(actor && enabled), ...privateQueryOptions, queryFn: async ({ signal }) => { @@ -65,7 +77,7 @@ export function useAssessmentQuestionnaire({ return useQuery({ queryKey: actor ? assessmentQueryKeys.questionnaire(actor) - : [...assessmentQueryKeysPrefix, "questionnaire"], + : [...assessmentQueryPrefix, "questionnaire"], enabled: Boolean(actor && enabled), ...privateQueryOptions, queryFn: async ({ signal }) => { @@ -86,7 +98,7 @@ export function useAssessmentAttempt({ return useQuery({ queryKey: actor ? assessmentQueryKeys.attempt(actor, attemptId) - : [...assessmentQueryKeysPrefix, "attempt", attemptId], + : [...assessmentQueryPrefix, "attempt", attemptId], enabled: Boolean(actor && attemptId && enabled), ...privateQueryOptions, refetchInterval: (query) => { @@ -111,7 +123,7 @@ export function useAssessmentResult({ return useQuery({ queryKey: actor ? assessmentQueryKeys.result(actor, attemptId) - : [...assessmentQueryKeysPrefix, "result", attemptId], + : [...assessmentQueryPrefix, "result", attemptId], enabled: Boolean(actor && attemptId && enabled), ...privateQueryOptions, queryFn: async ({ signal }) => { @@ -123,6 +135,47 @@ export function useAssessmentResult({ }); } +/** Page size of the result history; the contract allows 1 to 50. */ +export const assessmentHistoryPageSize = 20; + +/** + * Options of the result history query. The cursor is opaque and comes from + * the server; it is never built or stored by the client. Express runs are + * not part of this list by contract. + */ +export function assessmentResultHistoryOptions({ + actor, + enabled = true, + queryClient, +}: AssessmentQueryOptions) { + return infiniteQueryOptions({ + queryKey: actor + ? assessmentQueryKeys.resultHistory(actor) + : [...assessmentQueryPrefix, "result-history"], + enabled: Boolean(actor && enabled), + ...privateQueryOptions, + initialPageParam: null as string | null, + getNextPageParam: (last: AssessmentResultHistoryPage) => + last.page.has_more ? last.page.next_cursor : undefined, + queryFn: async ({ pageParam, signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const response = await listMyAssessmentResults( + pageParam + ? { limit: assessmentHistoryPageSize, cursor: pageParam } + : { limit: assessmentHistoryPageSize }, + { signal }, + ); + assertCurrentAssessmentSession(queryClient, actor); + return parseAssessmentResultHistoryResponse(response); + }, + }); +} + +/** Immutable real results of the current candidate, newest first. */ +export function useAssessmentResultHistory(options: AssessmentQueryOptions) { + return useInfiniteQuery(assessmentResultHistoryOptions(options)); +} + /** * Server-owned state of the notice about the collected signals. It is read * again on mount so an acknowledgement made in another window or browser is @@ -136,7 +189,7 @@ export function useAssessmentSignalNotice({ return useQuery({ queryKey: actor ? assessmentQueryKeys.signalNotice(actor) - : [...assessmentQueryKeysPrefix, "signal-notice"], + : [...assessmentQueryPrefix, "signal-notice"], enabled: Boolean(actor && enabled), ...privateQueryOptions, queryFn: async ({ signal }) => { @@ -168,5 +221,3 @@ export async function acknowledgeAssessmentSignalNotice( queryClient.setQueryData(assessmentQueryKeys.signalNotice(actor), notice); return notice; } - -const assessmentQueryKeysPrefix = ["candidate-assessment"] as const; diff --git a/frontend/src/entities/assessment/index.ts b/frontend/src/entities/assessment/index.ts index d3ef242..0ee8d1d 100644 --- a/frontend/src/entities/assessment/index.ts +++ b/frontend/src/entities/assessment/index.ts @@ -1,9 +1,12 @@ export { acknowledgeAssessmentSignalNotice, + assessmentHistoryPageSize, + assessmentResultHistoryOptions, useAssessmentAttempt, useAssessmentAvailability, useAssessmentQuestionnaire, useAssessmentResult, + useAssessmentResultHistory, useAssessmentSignalNotice, } from "./api/assessment-queries"; export { @@ -18,9 +21,28 @@ export { export { isOutcomeAmbiguous } from "./model/idempotency"; export { parseAssessmentAttemptResponse, + parseAssessmentResultHistoryResponse, parseAssessmentResultResponse, } from "./model/contract-validation"; export { assessmentResultSummary } from "./model/result-summary"; +export { + describeAssessmentResult, + formatResultDate, + formatResultDay, + type AssessmentResultPresentation, +} from "./model/result-presentation"; +export { + isAssessmentAccessLoss, + isAssessmentSessionEnded, + useAssessmentActor, +} from "./model/use-assessment-actor"; +export { + actorIdentity, + shouldPurgeAssessmentCache, + trackActorIdentity, +} from "./model/actor-transition"; +export { AssessmentActorGate } from "./ui/assessment-actor-gate"; +export { AssessmentResultView } from "./ui/assessment-result-view"; export { availabilityLabels, gradeLabels, diff --git a/frontend/src/entities/assessment/model/actor-transition.test.ts b/frontend/src/entities/assessment/model/actor-transition.test.ts new file mode 100644 index 0000000..7c038f0 --- /dev/null +++ b/frontend/src/entities/assessment/model/actor-transition.test.ts @@ -0,0 +1,102 @@ +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 { actorIdentity, shouldPurgeAssessmentCache, trackActorIdentity } from "./actor-transition"; +import { demoBasicAssigned } from "./result.fixtures"; +import { assessmentQueryKeys } from "./session"; + +function sessionFor(accountId: string, csrfToken: string): Session { + return { + account: { + id: accountId, + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: csrfToken, + }; +} + +const first = sessionFor("11111111-1111-4111-8111-111111111111", "A".repeat(43)); +const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"; + +/** A client that holds the first account's cached assessment answers. */ +function seededClient(): QueryClient { + const queryClient = new QueryClient(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), first); + queryClient.setQueryData(assessmentQueryKeys.result(first, attemptId), demoBasicAssigned()); + queryClient.setQueryData(assessmentQueryKeys.resultHistory(first), { + pages: [{ items: [demoBasicAssigned()], page: { has_more: false, next_cursor: null } }], + pageParams: [null], + }); + queryClient.setQueryData(["unrelated"], "kept"); + return queryClient; +} + +function assessmentEntries(queryClient: QueryClient): number { + return queryClient.getQueryCache().findAll({ queryKey: ["candidate-assessment"] }).length; +} + +describe("shouldPurgeAssessmentCache", () => { + const before = actorIdentity(first, true); + + it("keeps the cache while the identity is the same", () => { + expect(shouldPurgeAssessmentCache(before, actorIdentity(first, true))).toBe(false); + }); + + it("purges when the account changes", () => { + const other = sessionFor("22222222-2222-4222-8222-222222222222", first.csrf_token); + expect(shouldPurgeAssessmentCache(before, actorIdentity(other, true))).toBe(true); + }); + + it("purges when the session token changes for the same account", () => { + const renewed = sessionFor(first.account.id, "B".repeat(43)); + expect(shouldPurgeAssessmentCache(before, actorIdentity(renewed, true))).toBe(true); + }); + + it("purges when the session is lost and has nothing to purge before one exists", () => { + expect(shouldPurgeAssessmentCache(before, actorIdentity(first, false))).toBe(true); + expect(shouldPurgeAssessmentCache(null, actorIdentity(first, true))).toBe(false); + }); +}); + +describe("trackActorIdentity on a real query client", () => { + it("removes only the assessment queries when the account changes", () => { + const queryClient = seededClient(); + expect(assessmentEntries(queryClient)).toBe(2); + const other = sessionFor("22222222-2222-4222-8222-222222222222", "C".repeat(43)); + const next = trackActorIdentity( + queryClient, + actorIdentity(first, true), + actorIdentity(other, true), + ); + expect(next).toEqual({ accountId: other.account.id, csrfToken: other.csrf_token }); + expect(assessmentEntries(queryClient)).toBe(0); + expect(queryClient.getQueryData(assessmentQueryKeys.result(first, attemptId))).toBeUndefined(); + expect(queryClient.getQueryData(assessmentQueryKeys.resultHistory(first))).toBeUndefined(); + expect(queryClient.getQueryData(["unrelated"])).toBe("kept"); + expect(queryClient.getQueryData(getGetCurrentSessionQueryKey())).toEqual(first); + }); + + it("removes them when the session token changes", () => { + const queryClient = seededClient(); + const renewed = sessionFor(first.account.id, "B".repeat(43)); + trackActorIdentity(queryClient, actorIdentity(first, true), actorIdentity(renewed, true)); + expect(assessmentEntries(queryClient)).toBe(0); + }); + + it("removes them when the session ends", () => { + const queryClient = seededClient(); + trackActorIdentity(queryClient, actorIdentity(first, true), null); + expect(assessmentEntries(queryClient)).toBe(0); + }); + + it("keeps them while nothing changed", () => { + const queryClient = seededClient(); + trackActorIdentity(queryClient, actorIdentity(first, true), actorIdentity(first, true)); + expect(assessmentEntries(queryClient)).toBe(2); + }); +}); diff --git a/frontend/src/entities/assessment/model/actor-transition.ts b/frontend/src/entities/assessment/model/actor-transition.ts new file mode 100644 index 0000000..bc206eb --- /dev/null +++ b/frontend/src/entities/assessment/model/actor-transition.ts @@ -0,0 +1,36 @@ +import type { QueryClient } from "@tanstack/react-query"; +import type { Session } from "../../../shared/api/schemas"; +import { removeAssessmentQueries } from "./session"; + +export type ActorIdentity = { + readonly accountId: string; + readonly csrfToken: string; +}; + +/** The identity of a confirmed session, or null while there is none. */ +export function actorIdentity(actor: Session | undefined, ready: boolean): ActorIdentity | null { + return actor && ready ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null; +} + +/** + * Cached assessment data belongs to one session. It must go when the account + * changes, when the session token changes (a new sign-in), or when the + * session is lost. + */ +export function shouldPurgeAssessmentCache( + before: ActorIdentity | null, + next: ActorIdentity | null, +): boolean { + if (!before) return false; + return !next || before.accountId !== next.accountId || before.csrfToken !== next.csrfToken; +} + +/** Removes the assessment queries when the identity moved; returns the new one. */ +export function trackActorIdentity( + queryClient: QueryClient, + before: ActorIdentity | null, + next: ActorIdentity | null, +): ActorIdentity | null { + if (shouldPurgeAssessmentCache(before, next)) removeAssessmentQueries(queryClient); + return next; +} diff --git a/frontend/src/entities/assessment/model/contract-validation.ts b/frontend/src/entities/assessment/model/contract-validation.ts index 5815b0e..64a2723 100644 --- a/frontend/src/entities/assessment/model/contract-validation.ts +++ b/frontend/src/entities/assessment/model/contract-validation.ts @@ -3,11 +3,13 @@ import { AssessmentAttempt as assessmentAttemptSchema, AssessmentAvailability as assessmentAvailabilitySchema, AssessmentResult as assessmentResultSchema, + AssessmentResultHistoryPage as assessmentResultHistoryPageSchema, AssessmentSignalNotice as assessmentSignalNoticeSchema, CandidateQuestionnaire as candidateQuestionnaireSchema, type AssessmentAttempt, type AssessmentAvailability, type AssessmentResult, + type AssessmentResultHistoryPage, type AssessmentSignalNotice, type CandidateQuestionnaire, } from "../../../shared/api/schemas"; @@ -50,6 +52,15 @@ export function parseAssessmentResultResponse(value: unknown, status = 200): Ass return parsed.data; } +export function parseAssessmentResultHistoryResponse( + value: unknown, + status = 200, +): AssessmentResultHistoryPage { + const parsed = assessmentResultHistoryPageSchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} + export function parseAssessmentSignalNoticeResponse( value: unknown, status = 200, diff --git a/frontend/src/entities/assessment/model/result-presentation.test.ts b/frontend/src/entities/assessment/model/result-presentation.test.ts new file mode 100644 index 0000000..5fc8935 --- /dev/null +++ b/frontend/src/entities/assessment/model/result-presentation.test.ts @@ -0,0 +1,305 @@ +import { describe, expect, it } from "vitest"; +import { parseAssessmentResultResponse } from "./contract-validation"; +import { + describeAssessmentResult, + formatDecimal, + formatDuration, + type AssessmentResultPresentation, +} from "./result-presentation"; +import { + adaptiveConfirmed, + decisionFixture, + demoBasicAssigned, + expressFixture, + notConfirmedAfterJunior, +} from "./result.fixtures"; + +const options = { timeZone: "UTC" } as const; +const categoryLabel = "Категория после этого результата"; + +function fact(view: AssessmentResultPresentation, label: string): string | undefined { + return view.facts.find((item) => item.label === label)?.value; +} + +describe("result fixtures", () => { + it("match the response contract", () => { + for (const result of [ + demoBasicAssigned(), + adaptiveConfirmed(), + notConfirmedAfterJunior(), + expressFixture(), + ]) { + expect(() => parseAssessmentResultResponse(result)).not.toThrow(); + } + }); +}); + +describe("describeAssessmentResult for a demo_basic result", () => { + const view = describeAssessmentResult(demoBasicAssigned(), options); + + it("shows the category, date, method, and the provisional status", () => { + expect(fact(view, categoryLabel)).toBe("Backend, Middle (присвоена этим результатом)"); + expect(fact(view, "Дата решения")).toBe("8 октября 2026 г. в 09:30 UTC"); + expect(fact(view, "Метод")).toBe("Базовая проверка по фиксированному набору заданий"); + expect(fact(view, "Статус")).toBe("предварительный, пороги не калибровались"); + expect(fact(view, "Происхождение решения")).toBe("синтетическая демонстрация стенда"); + expect(view.isProvisional).toBe(true); + }); + + it("states the method limitation and invents no percentile or estimate", () => { + expect(view.methodLimitation).toContain("Перцентиль"); + expect(view.methodLimitation).toContain("не рассчитываются"); + expect(view.uncertainty).toBeNull(); + expect(view.uncertaintyNote).toBeNull(); + expect(view.strength).toBeNull(); + expect(view.score).toBe("17 из 20, проходной балл 14"); + expect(view.limitations).toContain( + "Результат получен на небольшом проверенном демонстрационном банке заданий.", + ); + }); +}); + +describe("describeAssessmentResult for an adaptive result", () => { + it("shows the actual theta, SE, interval, P_G, strength, gap, and retry date", () => { + const view = describeAssessmentResult(adaptiveConfirmed(), options); + expect(view.uncertainty).toEqual({ + theta: "0,42", + standardError: "0,21", + interval: "от −0,19 до 1,03", + pGrade: "0,80", + }); + expect(view.strength).toBe("средняя"); + expect(view.gaps).toEqual(["Базы данных"]); + expect(view.practices).toEqual(["Основная практика: 2 из 3"]); + expect(view.durations).toEqual(["Задания: 25 мин", "Практика: 12 мин"]); + expect(view.nextSteps).toEqual([ + { + action: "take_higher_grade", + text: "Пройти проверку на более высокий уровень: Senior.", + availability: "Доступно с 12 ноября 2026 г. в 10:00 UTC.", + leadsToTest: true, + isOffer: false, + }, + ]); + }); + + it("never replaces missing uncertainty fields with zeros", () => { + const view = describeAssessmentResult( + adaptiveConfirmed({ uncertainty: null, strength: null, gaps: [], practices: [] }), + options, + ); + expect(view.uncertainty).toBeNull(); + expect(view.strength).toBeNull(); + expect(view.uncertaintyNote).toBe( + "Сервер не вернул оценку способности и неопределенности для этой попытки.", + ); + expect(view.gapsNote).toBe("Сервер не отметил областей со слабыми доказательствами."); + expect(JSON.stringify(view)).not.toContain("0,00"); + }); + + it("keeps a real zero estimate as a value", () => { + const view = describeAssessmentResult( + adaptiveConfirmed({ + uncertainty: { + theta: 0, + standard_error: 0.5, + interval_95: { low: -0.98, high: 0.98 }, + p_grade: 0.5, + }, + }), + options, + ); + expect(view.uncertainty?.theta).toBe("0,00"); + expect(view.uncertainty?.pGrade).toBe("0,50"); + }); + + it("calls calibrated thresholds calibrated only when the server says so", () => { + const view = describeAssessmentResult( + adaptiveConfirmed({ + calibration_status: "calibrated", + category_decision: decisionFixture("assigned", { + current_confirmed_grade: "middle", + calibration_status: "calibrated", + }), + }), + options, + ); + expect(view.isProvisional).toBe(false); + expect(fact(view, "Статус")).toBe("пороги откалиброваны"); + }); +}); + +describe("describeAssessmentResult for a failed attempt", () => { + const view = describeAssessmentResult(notConfirmedAfterJunior(), options); + + it("keeps the previous grade and shows the attempt result separately", () => { + expect(view.summary.text).toBe("Уровень пока не подтвержден: Backend, Middle."); + expect(view.summary.reason).toBe("Прежний подтвержденный уровень Junior сохраняется."); + expect(fact(view, categoryLabel)).toBe("Backend, Junior (прежняя, сохраняется)"); + }); + + it("takes every next step from the server, in its order", () => { + expect(view.nextSteps.map((step) => step.action)).toEqual([ + "retake_same_grade", + "take_lower_grade", + "accept_lower_grade", + ]); + expect(view.nextSteps[0]?.availability).toBe("Доступно с 7 ноября 2026 г. в 09:30 UTC."); + expect(view.nextSteps[1]?.availability).toBe( + "Было доступно сразу на момент решения, без ожидания пересдачи.", + ); + }); + + it("presents accepting a lower grade as an offer, not as a done change", () => { + const offer = view.nextSteps[2]; + expect(offer?.isOffer).toBe(true); + expect(offer?.leadsToTest).toBe(false); + expect(offer?.text).toContain("предлагает"); + expect(fact(view, categoryLabel)).not.toContain("Junior (присвоена"); + }); + + it("says what stays true when there was no earlier grade", () => { + const first = describeAssessmentResult( + notConfirmedAfterJunior({ + previous_confirmed_grade: null, + category_decision: decisionFixture("not_confirmed"), + }), + options, + ); + expect(fact(first, categoryLabel)).toBe("не присвоена"); + expect(first.categoryNote).toContain("ничего не понижает"); + }); + + it("reports an empty list of next steps instead of inventing one", () => { + const none = describeAssessmentResult(notConfirmedAfterJunior({ next_steps: [] }), options); + expect(none.nextSteps).toEqual([]); + expect(none.nextStepsNote).toBe("Сервер не вернул следующих шагов для этого результата."); + }); +}); + +describe("describeAssessmentResult for a result without a category", () => { + it("does not show a category when the threshold passed but none was assigned", () => { + const view = describeAssessmentResult( + demoBasicAssigned({ + confirmed_grade: null, + category_decision: decisionFixture("not_eligible", { + method: null, + source: null, + calibration_status: null, + }), + }), + options, + ); + expect(fact(view, categoryLabel)).toBe("не присвоена"); + expect(view.summary.text).toContain("категория не присвоена"); + }); + + it("keeps the higher category when a reviewed result is unchanged", () => { + const view = describeAssessmentResult( + demoBasicAssigned({ + previous_confirmed_grade: "senior", + category_decision: decisionFixture("unchanged", { + previous_confirmed_grade: "senior", + current_confirmed_grade: "senior", + }), + }), + options, + ); + expect(fact(view, categoryLabel)).toBe("Backend, Senior (без изменений)"); + }); +}); + +describe("describeAssessmentResult for old and unassigned results", () => { + it("says the decision was not stored for a result without category_decision", () => { + const view = describeAssessmentResult( + demoBasicAssigned({ confirmed_grade: null, category_decision: undefined }), + options, + ); + expect(fact(view, categoryLabel)).toBe("решение о категории не сохранено"); + }); + + it("shows the kept category when the threshold passed but nothing was assigned", () => { + const view = describeAssessmentResult( + demoBasicAssigned({ + confirmed_grade: null, + previous_confirmed_grade: "junior", + category_decision: decisionFixture("not_eligible", { + previous_confirmed_grade: "junior", + current_confirmed_grade: "junior", + method: null, + source: null, + calibration_status: null, + }), + }), + options, + ); + expect(fact(view, categoryLabel)).toBe("Backend, Junior (прежняя, сохраняется)"); + }); + + it("marks next steps as computed at the decision time", () => { + const view = describeAssessmentResult(adaptiveConfirmed(), options); + expect(view.nextSteps[0]?.availability).toBe("Доступно с 12 ноября 2026 г. в 10:00 UTC."); + const immediate = describeAssessmentResult(demoBasicAssigned(), options); + expect(immediate.nextSteps[0]?.availability).toBe("Было доступно сразу на момент решения."); + }); + + it("does not round a near-certain probability up to one", () => { + const view = describeAssessmentResult( + adaptiveConfirmed({ + uncertainty: { + theta: 1.2, + standard_error: 0.0004, + interval_95: { low: 1.19, high: 1.21 }, + p_grade: 0.9996, + }, + }), + options, + ); + expect(view.uncertainty?.pGrade).toBe("больше 0,999"); + expect(view.uncertainty?.standardError).toBe("меньше 0,001"); + }); +}); + +describe("describeAssessmentResult for an express result", () => { + const view = describeAssessmentResult(expressFixture(), options); + + it("is a demonstration without a category, estimate, or next steps", () => { + expect(view.isExpress).toBe(true); + expect(fact(view, "Категория")).toBe("не присваивается"); + expect(fact(view, "Статус")).toBe("демонстрация"); + expect(view.expressSummary).toBe("Вы ответили на три учебных задания."); + expect(view.uncertainty).toBeNull(); + expect(view.score).toBeNull(); + expect(view.nextSteps).toEqual([]); + expect(view.nextStepsNote).toBeNull(); + expect(view.limitations).toEqual([ + "Запуск служит демонстрацией механики и не является квалификационной оценкой.", + ]); + }); +}); + +describe("number and duration formats", () => { + it("uses a comma with two to three fraction digits", () => { + expect(formatDecimal(0.8)).toBe("0,80"); + expect(formatDecimal(0.853)).toBe("0,853"); + expect(formatDecimal(-0.1999)).toBe("−0,20"); + }); + + it("never shows a nonzero value as zero or a probability as one", () => { + expect(formatDecimal(0.0004, 1)).toBe("меньше 0,001"); + expect(formatDecimal(0.0004)).toBe("меньше 0,001"); + expect(formatDecimal(0.001)).toBe("0,001"); + expect(formatDecimal(0)).toBe("0,00"); + expect(formatDecimal(1, 1)).toBe("1,00"); + expect(formatDecimal(0.9996, 1)).toBe("больше 0,999"); + expect(formatDecimal(0.999, 1)).toBe("0,999"); + expect(formatDecimal(-0.0004)).toBe("больше −0,001"); + expect(formatDecimal(-0.19)).toBe("−0,19"); + }); + + it("formats durations from seconds", () => { + expect(formatDuration(45)).toBe("45 сек"); + expect(formatDuration(754)).toBe("12 мин 34 сек"); + expect(formatDuration(3720)).toBe("1 ч 2 мин"); + }); +}); diff --git a/frontend/src/entities/assessment/model/result-presentation.ts b/frontend/src/entities/assessment/model/result-presentation.ts new file mode 100644 index 0000000..63b6d1f --- /dev/null +++ b/frontend/src/entities/assessment/model/result-presentation.ts @@ -0,0 +1,368 @@ +import type { + AssessmentLimitation, + AssessmentNextAction, + AssessmentResult, + GradeCode, +} from "../../../shared/api/schemas"; +import { gradeLabels, methodLabel, specializationLabels } from "./labels"; +import { assessmentResultSummary, type AssessmentResultSummary } from "./result-summary"; + +/** A result that can change the candidate category (root or corrective). */ +type RealResult = Exclude; + +export type ResultFact = { + readonly label: string; + readonly value: string; +}; + +/** Ability estimate of an adaptive attempt, exactly as the server returned it. */ +export type ResultUncertaintyView = { + readonly theta: string; + readonly standardError: string; + readonly interval: string; + readonly pGrade: string; +}; + +export type ResultNextStepView = { + readonly action: AssessmentNextAction; + /** What the server allows, in one sentence. */ + readonly text: string; + /** When the step opens, or null when the server gave no extra note. */ + readonly availability: string | null; + /** True when the step starts a test, so the screen may link to the checks. */ + readonly leadsToTest: boolean; + /** True for an offer that changes the category only by a later command. */ + readonly isOffer: boolean; +}; + +export type AssessmentResultPresentation = { + readonly isExpress: boolean; + readonly attemptId: string; + /** Specialization and target grade, or the express title. */ + readonly title: string; + readonly kindLabel: string; + /** Decision date without the time, for short names. */ + readonly decidedDay: string; + readonly summary: AssessmentResultSummary; + /** The server feedback text of an express run, otherwise null. */ + readonly expressSummary: string | null; + /** Category, date, method, and the provisional status as label-value rows. */ + readonly facts: readonly ResultFact[]; + /** Extra sentence about the category, or null when the summary says it all. */ + readonly categoryNote: string | null; + readonly isProvisional: boolean; + /** Plain statement about what the method does and does not measure. */ + readonly methodLimitation: string; + readonly limitations: readonly string[]; + /** Raw score of a demo_basic attempt, or null when none was recorded. */ + readonly score: string | null; + readonly uncertainty: ResultUncertaintyView | null; + /** Why no uncertainty is shown, or null when it is shown or not expected. */ + readonly uncertaintyNote: string | null; + readonly strength: string | null; + readonly gaps: readonly string[]; + readonly gapsNote: string | null; + readonly practices: readonly string[]; + readonly durations: readonly string[]; + readonly nextSteps: readonly ResultNextStepView[]; + /** Said when the server returned no next step for this result. */ + readonly nextStepsNote: string | null; +}; + +export type ResultPresentationOptions = { + /** IANA zone for dates; the browser zone when omitted. Tests pin it. */ + readonly timeZone?: string; +}; + +const limitationLabels: Readonly> = { + uncalibrated_thresholds: "Пороги пока не проверены на пилотной выборке.", + demo_bank: "Результат получен на небольшом проверенном демонстрационном банке заданий.", + practice_not_included: "В попытке не было кодовой практики: песочница не была включена.", + unproctored: "Проверка пройдена онлайн без наблюдения.", + demonstration_only: + "Запуск служит демонстрацией механики и не является квалификационной оценкой.", +}; + +const strengthLabels = { + high: "высокая", + medium: "средняя", +} as const; + +const practiceKindLabels = { + main: "Основная практика", + additional: "Дополнительная практика", +} as const; + +export function formatResultDate(value: string, timeZone?: string): string { + return new Intl.DateTimeFormat("ru-RU", { + day: "numeric", + month: "long", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + timeZoneName: "short", + ...(timeZone ? { timeZone } : {}), + }).format(new Date(value)); +} + +/** Date without the time, for names that must stay short. */ +export function formatResultDay(value: string, timeZone?: string): string { + return new Intl.DateTimeFormat("ru-RU", { + dateStyle: "long", + ...(timeZone ? { timeZone } : {}), + }).format(new Date(value)); +} + +const minusSign = "\u2212"; + +/** + * Decimal with a comma, the typographic minus, and two to three fraction + * digits. The value is only rounded for display and a nonzero value never + * shows as zero: a tiny positive value reads "меньше 0,001". With `upperBound` + * (a probability), a value just below it reads "больше 0,999" instead of + * rounding up to the bound. + */ +export function formatDecimal(value: number, upperBound?: number): string { + if (value > 0 && value < 0.001) return "меньше 0,001"; + if (value < 0 && value > -0.001) return `больше ${minusSign}0,001`; + if (upperBound !== undefined && value < upperBound && value > upperBound - 0.001) { + return `больше ${formatDecimal(upperBound - 0.001)}`; + } + let text = Math.abs(value).toFixed(3); + if (text.endsWith("0")) text = text.slice(0, -1); + return `${value < 0 ? minusSign : ""}${text.replace(".", ",")}`; +} + +export function formatDuration(seconds: number): string { + const hours = Math.floor(seconds / 3600); + const minutes = Math.floor((seconds % 3600) / 60); + const rest = seconds % 60; + if (hours > 0) return minutes > 0 ? `${hours} ч ${minutes} мин` : `${hours} ч`; + if (minutes === 0) return `${rest} сек`; + return rest > 0 ? `${minutes} мин ${rest} сек` : `${minutes} мин`; +} + +function categoryName(result: RealResult, grade: GradeCode): string { + return `${specializationLabels[result.specialization]}, ${gradeLabels[grade]}`; +} + +/** + * The category in force after this result, as the server recorded it. A + * grade is taken only from the decision or from the confirmed fields, never + * from the target grade. + */ +function categoryFact(result: RealResult): string { + const decision = result.category_decision; + if (decision?.status === "assigned" || decision?.status === "unchanged") { + const grade = decision.current_confirmed_grade ?? result.confirmed_grade; + if (grade) { + return decision.status === "assigned" + ? `${categoryName(result, grade)} (присвоена этим результатом)` + : `${categoryName(result, grade)} (без изменений)`; + } + } + const kept = decision?.current_confirmed_grade ?? result.previous_confirmed_grade; + if (kept && (decision !== undefined || result.outcome !== "confirmed")) { + return `${categoryName(result, kept)} (прежняя, сохраняется)`; + } + // A result stored before category decisions cannot say what the category was. + return decision === undefined ? "решение о категории не сохранено" : "не присвоена"; +} + +/** A failed attempt with no earlier grade: say what stays true. */ +function failedWithoutGradeNote(result: RealResult): string | null { + if (result.outcome === "confirmed") return null; + const kept = result.category_decision?.current_confirmed_grade ?? result.previous_confirmed_grade; + if (kept) return null; + return "По этой специализации еще нет подтвержденного уровня. Неудачная попытка ничего не понижает."; +} + +function methodLimitationText(result: AssessmentResult): string { + if (result.kind === "demo_express") { + return "Экспресс-запуск показывает механику проверки. Он не создает категорию, перцентиль, оценку неопределенности и квалификационные доказательства."; + } + if (result.mode === "demo_basic") { + return "Базовая проверка считает только баллы по фиксированному набору заданий и сравнивает их с проходным баллом. Перцентиль, оценка способности, интервал, вероятность P_G и сила подтверждения не рассчитываются."; + } + return "Адаптивная проверка оценивает способность на шкале специализации. Оценка способности, интервал и вероятность P_G не являются баллом или перцентилем."; +} + +function isProvisional(result: AssessmentResult): boolean { + if (result.kind === "demo_express") return true; + return ( + result.calibration_status === "uncalibrated" || + result.category_decision?.calibration_status === "uncalibrated" + ); +} + +function uncertaintyView(result: RealResult): ResultUncertaintyView | null { + const value = result.uncertainty; + if (!value) return null; + return { + theta: formatDecimal(value.theta), + standardError: formatDecimal(value.standard_error), + interval: `от ${formatDecimal(value.interval_95.low)} до ${formatDecimal(value.interval_95.high)}`, + pGrade: formatDecimal(value.p_grade, 1), + }; +} + +function nextStepView( + step: RealResult["next_steps"][number], + timeZone: string | undefined, +): ResultNextStepView { + const grade = gradeLabels[step.grade]; + const date = step.available_at ? formatResultDate(step.available_at, timeZone) : null; + switch (step.action) { + case "retake_same_grade": + return { + action: step.action, + text: `Пересдать тот же уровень: ${grade}.`, + availability: date ? `Доступно с ${date}.` : "Было доступно сразу на момент решения.", + leadsToTest: true, + isOffer: false, + }; + case "take_lower_grade": + return { + action: step.action, + text: `Пройти проверку на меньший уровень: ${grade}.`, + availability: date + ? `Доступно с ${date}.` + : "Было доступно сразу на момент решения, без ожидания пересдачи.", + leadsToTest: true, + isOffer: false, + }; + case "accept_lower_grade": + return { + action: step.action, + text: `Сервер предлагает принять меньший уровень ${grade} по данным этой попытки.`, + availability: date ? `Доступно с ${date}.` : null, + leadsToTest: false, + isOffer: true, + }; + case "take_higher_grade": + return { + action: step.action, + text: `Пройти проверку на более высокий уровень: ${grade}.`, + availability: date ? `Доступно с ${date}.` : "Было доступно сразу на момент решения.", + leadsToTest: true, + isOffer: false, + }; + } +} + +function limitationList(result: AssessmentResult): string[] { + return result.limitations.map((code) => limitationLabels[code]); +} + +function expressPresentation( + result: Extract, + options: ResultPresentationOptions, +): AssessmentResultPresentation { + return { + isExpress: true, + attemptId: result.attempt_id, + title: methodLabel("demo_express"), + kindLabel: "Демонстрация без реального грейда", + decidedDay: formatResultDay(result.decided_at, options.timeZone), + summary: assessmentResultSummary(result), + expressSummary: result.summary, + facts: [ + { label: "Категория", value: "не присваивается" }, + { label: "Дата", value: formatResultDate(result.decided_at, options.timeZone) }, + { label: "Метод", value: methodLabel("demo_express") }, + { label: "Статус", value: "демонстрация" }, + ], + categoryNote: null, + isProvisional: true, + methodLimitation: methodLimitationText(result), + limitations: limitationList(result), + score: null, + uncertainty: null, + uncertaintyNote: null, + strength: null, + gaps: [], + gapsNote: null, + practices: [], + durations: durationList(result), + nextSteps: [], + nextStepsNote: null, + }; +} + +function durationList(result: AssessmentResult): string[] { + const durations: string[] = [`Задания: ${formatDuration(result.durations.items_seconds)}`]; + if (result.durations.practice_seconds !== null) { + durations.push(`Практика: ${formatDuration(result.durations.practice_seconds)}`); + } + return durations; +} + +/** + * Turns a stored result into display values. It restates server fields only: + * a field the server left null stays absent, no grade is derived, and an + * absent estimate is never shown as zero. + */ +export function describeAssessmentResult( + result: AssessmentResult, + options: ResultPresentationOptions = {}, +): AssessmentResultPresentation { + if (result.kind === "demo_express") return expressPresentation(result, options); + + const decision = result.category_decision; + const facts: ResultFact[] = [ + { label: "Категория после этого результата", value: categoryFact(result) }, + { label: "Дата решения", value: formatResultDate(result.decided_at, options.timeZone) }, + { label: "Метод", value: methodLabel(result.mode) }, + { + label: "Статус", + value: isProvisional(result) + ? "предварительный, пороги не калибровались" + : "пороги откалиброваны", + }, + ]; + if (decision?.source === "synthetic_demo") { + facts.push({ label: "Происхождение решения", value: "синтетическая демонстрация стенда" }); + } + const uncertainty = uncertaintyView(result); + const basic = result.basic_score; + + return { + isExpress: false, + attemptId: result.attempt_id, + title: `${specializationLabels[result.specialization]}, ${gradeLabels[result.target_grade]}`, + decidedDay: formatResultDay(result.decided_at, options.timeZone), + kindLabel: + result.kind === "corrective" ? "Проверка меньшего уровня после неудачи" : "Основная проверка", + summary: assessmentResultSummary(result), + expressSummary: null, + facts, + categoryNote: failedWithoutGradeNote(result), + isProvisional: isProvisional(result), + methodLimitation: methodLimitationText(result), + limitations: limitationList(result), + score: basic + ? `${basic.points} из ${basic.max_points}, проходной балл ${basic.pass_points}` + : null, + uncertainty, + uncertaintyNote: + uncertainty === null && result.mode === "adaptive" + ? "Сервер не вернул оценку способности и неопределенности для этой попытки." + : null, + strength: result.strength ? strengthLabels[result.strength] : null, + gaps: result.gaps.map((gap) => gap.title), + gapsNote: + result.gaps.length === 0 && result.mode === "adaptive" + ? "Сервер не отметил областей со слабыми доказательствами." + : null, + practices: result.practices.map( + (practice) => + `${practiceKindLabels[practice.kind]}: ${practice.verdict.score} из ${practice.verdict.max_score}`, + ), + durations: durationList(result), + nextSteps: result.next_steps.map((step) => nextStepView(step, options.timeZone)), + nextStepsNote: + result.next_steps.length === 0 + ? "Сервер не вернул следующих шагов для этого результата." + : null, + }; +} diff --git a/frontend/src/entities/assessment/model/result-summary.test.ts b/frontend/src/entities/assessment/model/result-summary.test.ts index f369e99..3ebf74f 100644 --- a/frontend/src/entities/assessment/model/result-summary.test.ts +++ b/frontend/src/entities/assessment/model/result-summary.test.ts @@ -50,10 +50,22 @@ describe("assessmentResultSummary", () => { }), ); expect(summary.text).toBe("Уровень подтвержден: Backend, Middle."); + expect(summary.reason).toBe("Это демонстрационная категория: пороги не калибровались."); + expect(summary.isDemonstration).toBe(false); + }); + + it("names the demonstration bank only when the server lists it", () => { + const summary = assessmentResultSummary( + result({ + outcome: "confirmed", + confirmed_grade: "middle", + limitations: ["demo_bank"], + category_decision: decision("assigned", { current_confirmed_grade: "middle" }), + }), + ); expect(summary.reason).toBe( "Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.", ); - expect(summary.isDemonstration).toBe(false); }); it("keeps the higher grade when a reviewed result does not change the category", () => { @@ -70,7 +82,7 @@ describe("assessmentResultSummary", () => { ); expect(summary.text).toBe("Уровень подтвержден: Backend, Middle."); expect(summary.reason).toBe( - "Прежний подтвержденный уровень Senior сохраняется. Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.", + "Прежний подтвержденный уровень Senior сохраняется. Это демонстрационная категория: пороги не калибровались.", ); }); @@ -90,6 +102,36 @@ describe("assessmentResultSummary", () => { expect(summary.reason).toBeNull(); }); + it("describes an adaptive result only by the flags the server set", () => { + const decision_ = decision("assigned", { current_confirmed_grade: "middle" }); + const uncalibratedOnly = assessmentResultSummary( + result({ + mode: "adaptive", + outcome: "confirmed", + confirmed_grade: "middle", + limitations: ["unproctored"], + category_decision: decision_, + }), + ); + expect(uncalibratedOnly.reason).toBe("Результат предварительный: пороги не калибровались."); + expect(uncalibratedOnly.reason).not.toContain("демонстрационн"); + + const withBank = assessmentResultSummary( + result({ + mode: "adaptive", + outcome: "confirmed", + confirmed_grade: "middle", + calibration_status: "calibrated", + limitations: ["demo_bank"], + category_decision: decision("assigned", { + current_confirmed_grade: "middle", + calibration_status: "calibrated", + }), + }), + ); + expect(withBank.reason).toBe("Результат предварительный: банк заданий демонстрационный."); + }); + it("says that the threshold was reached but no category was assigned", () => { const summary = assessmentResultSummary( result({ diff --git a/frontend/src/entities/assessment/model/result-summary.ts b/frontend/src/entities/assessment/model/result-summary.ts index 2416cd5..bbe81bf 100644 --- a/frontend/src/entities/assessment/model/result-summary.ts +++ b/frontend/src/entities/assessment/model/result-summary.ts @@ -64,16 +64,20 @@ export function assessmentResultSummary(result: AssessmentResult): AssessmentRes isDemonstration, }; } - const demonstrational = + const flags = [ result.category_decision?.calibration_status === "uncalibrated" || - result.calibration_status === "uncalibrated" || - result.limitations.includes("demo_bank"); - const reason = [ - decisionStatus === "unchanged" ? keptGrade : null, - demonstrational - ? "Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный." + result.calibration_status === "uncalibrated" + ? "пороги не калибровались" : null, - ] + result.limitations.includes("demo_bank") ? "банк заданий демонстрационный" : null, + ].filter(Boolean); + // Only the basic method yields a demonstration category; other methods + // are described by the flags the server actually set. + const caveat = + flags.length === 0 + ? null + : `${result.mode === "demo_basic" ? "Это демонстрационная категория" : "Результат предварительный"}: ${flags.join(", ")}.`; + const reason = [decisionStatus === "unchanged" ? keptGrade : null, caveat] .filter(Boolean) .join(" "); return { diff --git a/frontend/src/entities/assessment/model/result.fixtures.ts b/frontend/src/entities/assessment/model/result.fixtures.ts new file mode 100644 index 0000000..1924332 --- /dev/null +++ b/frontend/src/entities/assessment/model/result.fixtures.ts @@ -0,0 +1,150 @@ +import type { AssessmentResult } from "../../../shared/api/schemas"; + +/* + * Contract-shaped results for tests. They are inputs, not evidence that the + * backend produces the same values. + */ + +type Patch = Record; + +const realBase = { + attempt_id: "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff", + specialization: "backend", + target_grade: "middle", + root_attempt_id: null, + chain_deadline: null, + task_language: "go", + kind: "root", + mode: "demo_basic", + versions: { bank_version: "demo-1", algorithm_version: "basic-1", policy_version: 1 }, + outcome: "confirmed", + not_determined_reason: null, + confirmed_grade: null, + previous_confirmed_grade: null, + strength: null, + calibration_status: "uncalibrated", + limitations: ["uncalibrated_thresholds", "demo_bank", "unproctored"], + uncertainty: null, + basic_score: null, + practices: [], + gaps: [], + durations: { items_seconds: 754, practice_seconds: null }, + next_steps: [], + decided_at: "2026-10-08T09:30:00Z", +} as const; + +function real(patch: Patch): AssessmentResult { + return { ...realBase, ...patch } as unknown as AssessmentResult; +} + +export function decisionFixture(status: string, patch: Patch = {}): Patch { + return { + status, + previous_confirmed_grade: null, + current_confirmed_grade: null, + method: "demo_basic_pass_mark", + source: "synthetic_demo", + calibration_status: "uncalibrated", + ...patch, + }; +} + +/** A passed demo_basic attempt that assigned a demonstration category. */ +export function demoBasicAssigned(patch: Patch = {}): AssessmentResult { + return real({ + confirmed_grade: "middle", + basic_score: { points: 17, max_points: 20, pass_points: 14 }, + category_decision: decisionFixture("assigned", { current_confirmed_grade: "middle" }), + next_steps: [{ action: "take_higher_grade", grade: "senior", available_at: null }], + ...patch, + }); +} + +/** An adaptive attempt: P_G = 0.80 with medium strength and full uncertainty. */ +export function adaptiveConfirmed(patch: Patch = {}): AssessmentResult { + return real({ + mode: "adaptive", + confirmed_grade: "middle", + strength: "medium", + calibration_status: "uncalibrated", + limitations: ["uncalibrated_thresholds", "unproctored"], + uncertainty: { + theta: 0.42, + standard_error: 0.21, + interval_95: { low: -0.19, high: 1.03 }, + p_grade: 0.8, + }, + gaps: [{ domain: "databases", title: "Базы данных" }], + practices: [ + { + kind: "main", + verdict: { + score: 2, + max_score: 3, + groups: [ + { group: 1, passed: true }, + { group: 2, passed: true }, + { group: 3, passed: false }, + ], + }, + }, + ], + durations: { items_seconds: 1500, practice_seconds: 720 }, + category_decision: decisionFixture("assigned", { + current_confirmed_grade: "middle", + method: null, + source: null, + }), + next_steps: [ + { action: "take_higher_grade", grade: "senior", available_at: "2026-11-12T10:00:00Z" }, + ], + ...patch, + }); +} + +/** A failed attempt after an earlier confirmed grade. */ +export function notConfirmedAfterJunior(patch: Patch = {}): AssessmentResult { + return real({ + outcome: "not_confirmed", + previous_confirmed_grade: "junior", + basic_score: { points: 8, max_points: 20, pass_points: 14 }, + category_decision: decisionFixture("not_confirmed", { + previous_confirmed_grade: "junior", + current_confirmed_grade: "junior", + }), + next_steps: [ + { action: "retake_same_grade", grade: "middle", available_at: "2026-11-07T09:30:00Z" }, + { action: "take_lower_grade", grade: "junior", available_at: null }, + { action: "accept_lower_grade", grade: "junior", available_at: null }, + ], + ...patch, + }); +} + +export function expressFixture(patch: Patch = {}): AssessmentResult { + return { + attempt_id: "0199b4f2-7c1e-7d3a-9f00-112233445566", + specialization: null, + target_grade: null, + task_language: null, + kind: "demo_express", + mode: "demo_express", + versions: { bank_version: "express-1", algorithm_version: "express-1", policy_version: 1 }, + outcome: "demonstration", + not_determined_reason: null, + confirmed_grade: null, + previous_confirmed_grade: null, + strength: null, + calibration_status: "uncalibrated", + limitations: ["demonstration_only"], + uncertainty: null, + basic_score: null, + practices: [], + gaps: [], + durations: { items_seconds: 200, practice_seconds: null }, + next_steps: [], + summary: "Вы ответили на три учебных задания.", + decided_at: "2026-10-08T10:00:00Z", + ...patch, + } as unknown as AssessmentResult; +} diff --git a/frontend/src/entities/assessment/model/session.ts b/frontend/src/entities/assessment/model/session.ts index e211f27..57de69e 100644 --- a/frontend/src/entities/assessment/model/session.ts +++ b/frontend/src/entities/assessment/model/session.ts @@ -47,6 +47,8 @@ export const assessmentQueryKeys = { [...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, + resultHistory: (actor: Session) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result-history"] as const, signalNotice: (actor: Session) => [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "signal-notice"] as const, }; diff --git a/frontend/src/entities/assessment/model/use-assessment-actor.ts b/frontend/src/entities/assessment/model/use-assessment-actor.ts new file mode 100644 index 0000000..5c8a4a9 --- /dev/null +++ b/frontend/src/entities/assessment/model/use-assessment-actor.ts @@ -0,0 +1,54 @@ +import { useEffect, useRef } from "react"; +import { useQueryClient, type QueryClient } from "@tanstack/react-query"; +import { ApiRequestError } from "../../../shared/api"; +import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; +import { actorIdentity, trackActorIdentity, type ActorIdentity } from "./actor-transition"; +import { isCurrentAssessmentSession } from "./session"; + +export type AssessmentActor = { + readonly queryClient: QueryClient; + readonly session: ReturnType; + /** The signed-in session, or undefined until the server answers. */ + readonly actor: Session | undefined; + /** True when the cached session is the successful candidate session. */ + readonly actorReady: boolean; +}; + +/** Access loss as the API reports it: no session, no right, or not the owner. */ +export function isAssessmentAccessLoss(error: unknown): error is ApiRequestError { + return error instanceof ApiRequestError && [401, 403, 404].includes(error.status); +} + +/** The session itself is gone: only a 401 means that. */ +export function isAssessmentSessionEnded(error: unknown): error is ApiRequestError { + return error instanceof ApiRequestError && error.status === 401; +} + +/** + * Current candidate session for the assessment screens. Cached assessment + * data is private to one session: when the account or its session token + * changes, or the session ends, every cached assessment query is dropped so + * the next account never sees it. + */ +export function useAssessmentActor(): AssessmentActor { + 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 previous = useRef(null); + + useEffect(() => { + previous.current = trackActorIdentity( + queryClient, + previous.current, + actorIdentity(actor, actorReady), + ); + }, [actor, actorReady, queryClient]); + + return { queryClient, session, actor, actorReady }; +} diff --git a/frontend/src/entities/assessment/ui/assessment-actor-gate.tsx b/frontend/src/entities/assessment/ui/assessment-actor-gate.tsx new file mode 100644 index 0000000..8cdc63e --- /dev/null +++ b/frontend/src/entities/assessment/ui/assessment-actor-gate.tsx @@ -0,0 +1,50 @@ +import type { ReactNode } from "react"; +import type { QueryClient } from "@tanstack/react-query"; +import { ApiRequestError } from "../../../shared/api"; +import type { Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config/paths"; +import { ButtonLink, ErrorState, ForbiddenState, LoadingState } from "../../../shared/ui"; +import { useAssessmentActor } from "../model/use-assessment-actor"; + +type AssessmentActorGateProps = { + /** Rendered only for a confirmed candidate session. */ + children: (context: { actor: Session; queryClient: QueryClient }) => ReactNode; +}; + +function refusesAccess(error: unknown): boolean { + return error instanceof ApiRequestError && (error.status === 401 || error.status === 403); +} + +/** + * Shows the content of an assessment screen only for the current candidate + * session. A refused session or another scenario renders a state instead of + * data; a network or server failure offers a retry instead of claiming that + * access was lost. + */ +export function AssessmentActorGate({ children }: AssessmentActorGateProps) { + const { queryClient, session, actor, actorReady } = useAssessmentActor(); + + if (session.isError && !refusesAccess(session.error)) { + return ( + void session.refetch()} + title="Не удалось проверить вход" + /> + ); + } + if (session.isError || (actor && actor.account.scenario !== "candidate")) { + return ( + Перейти ко входу} + /> + ); + } + if (session.isPending || !actor) return ; + if (!actorReady) return ; + return <>{children({ actor, queryClient })}; +} diff --git a/frontend/src/entities/assessment/ui/assessment-result-view.module.css b/frontend/src/entities/assessment/ui/assessment-result-view.module.css new file mode 100644 index 0000000..526a4b0 --- /dev/null +++ b/frontend/src/entities/assessment/ui/assessment-result-view.module.css @@ -0,0 +1,124 @@ +.root { + display: grid; + gap: var(--space-4); + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-inline-start: var(--line-strong) solid var(--color-accent); + border-radius: var(--radius-m); + background: var(--color-canvas); +} + +.root[data-express="true"] { + border-inline-start-style: dashed; +} + +.root p { + margin: 0; + overflow-wrap: anywhere; +} + +.header { + display: grid; + gap: var(--space-2); +} + +.kind { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.title { + margin: 0; + font-size: var(--font-size-xl); + line-height: var(--line-height-snug); + overflow-wrap: anywhere; +} + +.badges { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.badges:empty { + display: none; +} + +.badge { + padding: var(--space-1) var(--space-3); + border: var(--line-strong) solid var(--color-border-strong); + border-radius: var(--radius-pill); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-bold); +} + +.summary { + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); +} + +.demo { + font-weight: var(--font-weight-bold); +} + +.facts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); + gap: var(--space-3) var(--space-4); + margin: 0; +} + +.facts > div { + display: grid; + gap: var(--space-1); + min-width: 0; +} + +.facts dt { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +.block { + display: grid; + gap: var(--space-3); + min-width: 0; + padding-block-start: var(--space-3); + border-block-start: var(--line-thin) solid var(--color-divider); +} + +.block-title { + margin: 0; + font-size: var(--font-size-m); +} + +.list, +.steps { + display: grid; + gap: var(--space-2); + margin: 0; + padding-inline-start: var(--space-5); +} + +.steps { + gap: var(--space-3); +} + +.note { + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +@media (width < 42rem) { + .root { + padding: var(--space-3); + } +} diff --git a/frontend/src/entities/assessment/ui/assessment-result-view.test.tsx b/frontend/src/entities/assessment/ui/assessment-result-view.test.tsx new file mode 100644 index 0000000..e32cafb --- /dev/null +++ b/frontend/src/entities/assessment/ui/assessment-result-view.test.tsx @@ -0,0 +1,113 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import type { AssessmentResult } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { + adaptiveConfirmed, + demoBasicAssigned, + expressFixture, + notConfirmedAfterJunior, +} from "../model/result.fixtures"; +import { AssessmentResultView } from "./assessment-result-view"; + +function render(result: AssessmentResult): string { + return renderToStaticMarkup( + + + , + ); +} + +describe("AssessmentResultView for demo_basic", () => { + const html = render(demoBasicAssigned()); + + it("shows the category, date, method, and provisional status", () => { + expect(html).toContain("Уровень подтвержден: Backend, Middle."); + expect(html).toContain("Backend, Middle (присвоена этим результатом)"); + expect(html).toContain("8 октября 2026 г. в 09:30 UTC"); + expect(html).toContain("Базовая проверка по фиксированному набору заданий"); + expect(html).toContain("Предварительный результат"); + expect(html).toContain("предварительный, пороги не калибровались"); + }); + + it("names the method limitation and shows no estimate rows", () => { + expect(html).toContain("Перцентиль, оценка способности, интервал, вероятность P_G"); + expect(html).not.toContain("Стандартная ошибка"); + expect(html).not.toContain("95% интервал"); + expect(html).not.toContain("Сила подтверждения"); + expect(html).toContain("17 из 20, проходной балл 14"); + }); +}); + +describe("AssessmentResultView for an adaptive result", () => { + it("labels P_G, strength, SE, interval, and the retry date with the returned values", () => { + const html = render(adaptiveConfirmed()); + expect(html).toContain("Вероятность достичь порога выбранного грейда (P_G)"); + expect(html).toContain("0,80"); + expect(html).toContain("Сила подтверждения"); + expect(html).toContain("средняя"); + expect(html).toContain("Стандартная ошибка (SE)"); + expect(html).toContain("0,21"); + expect(html).toContain("от −0,19 до 1,03"); + expect(html).toContain("Базы данных"); + expect(html).toContain("Доступно с 12 ноября 2026 г. в 10:00 UTC."); + expect(html).toContain("остается предварительной оценкой"); + }); + + it("draws no estimate and no zeros once the fields are removed", () => { + const html = render( + adaptiveConfirmed({ uncertainty: null, strength: null, gaps: [], practices: [] }), + ); + expect(html).not.toContain("P_G)"); + expect(html).not.toContain("Стандартная ошибка"); + expect(html).not.toContain("Сила подтверждения"); + expect(html).not.toContain("0,00"); + expect(html).toContain("Сервер не вернул оценку способности и неопределенности"); + }); +}); + +describe("AssessmentResultView for a failed attempt", () => { + const html = render(notConfirmedAfterJunior()); + + it("explains that the previous grade stays and shows the attempt result", () => { + expect(html).toContain("Уровень пока не подтвержден: Backend, Middle."); + expect(html).toContain("Прежний подтвержденный уровень Junior сохраняется."); + expect(html).toContain("Backend, Junior (прежняя, сохраняется)"); + }); + + it("lists the server next steps and offers the lower grade only as text", () => { + expect(html).toContain("Следующие шаги на момент решения"); + expect(html).toContain("Шаги рассчитаны сервером в момент решения."); + expect(html).toContain("Проверить актуальную доступность"); + expect(html).toContain("Пересдать тот же уровень: Middle."); + expect(html).toContain("Доступно с 7 ноября 2026 г. в 09:30 UTC."); + expect(html).toContain("Пройти проверку на меньший уровень: Junior."); + expect(html).toContain("предлагает принять меньший уровень Junior"); + expect(html).toContain("Категория не изменится, пока вы сами не подтвердите это действие."); + expect(html).not.toContain(" { + const html = render(expressFixture()); + + it("is marked as a demonstration without a grade", () => { + expect(html).toContain("Демонстрация без реального грейда"); + expect(html).toContain( + "Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.", + ); + expect(html).toContain("Вы ответили на три учебных задания."); + expect(html).toContain("не присваивается"); + expect(html).not.toContain("Подтвержденный уровень"); + expect(html).not.toContain("Предварительный результат"); + }); + + it("offers the full test and does not replace it", () => { + expect(html).toContain("Перейти к полной проверке"); + expect(html).toContain(`href="${paths.candidate.assessment}"`); + expect(html).toContain("Категорию дает только полная проверка."); + }); +}); diff --git a/frontend/src/entities/assessment/ui/assessment-result-view.tsx b/frontend/src/entities/assessment/ui/assessment-result-view.tsx new file mode 100644 index 0000000..86ef7da --- /dev/null +++ b/frontend/src/entities/assessment/ui/assessment-result-view.tsx @@ -0,0 +1,215 @@ +import { useId, type ReactNode } from "react"; +import type { AssessmentResult } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config/paths"; +import { ButtonLink, Mono } from "../../../shared/ui"; +import { describeAssessmentResult } from "../model/result-presentation"; +import styles from "./assessment-result-view.module.css"; + +type AssessmentResultViewProps = { + result: AssessmentResult; + /** Level of the result heading; its blocks use the next level. */ + headingLevel?: 2 | 3; + /** IANA zone for dates; the browser zone when omitted. */ + timeZone?: string; +}; + +type BlockProps = { + title: string; + level: 3 | 4; + children: ReactNode; +}; + +function Block({ title, level, children }: BlockProps) { + const Heading = level === 3 ? "h3" : "h4"; + return ( +
+ {title} + {children} +
+ ); +} + +/** + * Stored result of one attempt. Every value is a restatement of a server + * field: an absent estimate is not drawn, a lower-grade offer is text and + * never a control that changes the category, and an express run is marked as + * a demonstration without a grade. + */ +export function AssessmentResultView({ + result, + headingLevel = 2, + timeZone, +}: AssessmentResultViewProps) { + const titleId = useId(); + const view = describeAssessmentResult(result, timeZone ? { timeZone } : {}); + const Heading = headingLevel === 2 ? "h2" : "h3"; + const blockLevel = headingLevel === 2 ? 3 : 4; + const testLinkVisible = view.nextSteps.some((step) => step.leadsToTest); + + return ( +
+
+

{view.kindLabel}

+ + {view.title} + +

+ {view.isExpress ? Демонстрация : null} + {!view.isExpress && view.isProvisional ? ( + Предварительный результат + ) : null} +

+
+ +

{view.summary.text}

+ {view.summary.reason ?

{view.summary.reason}

: null} + {view.isExpress ? ( + <> +

+ Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд. +

+ {view.expressSummary ?

{view.expressSummary}

: null} + + ) : null} + +
+ {view.facts.map((fact) => ( +
+
{fact.label}
+
{fact.value}
+
+ ))} +
+ {view.categoryNote ?

{view.categoryNote}

: null} + + +

{view.methodLimitation}

+ {view.limitations.length > 0 ? ( +
    + {view.limitations.map((limitation, index) => ( +
  • {limitation}
  • + ))} +
+ ) : null} + {view.score ? ( +

+ Баллы за задания: {view.score}. +

+ ) : null} +
+ + {view.uncertainty ? ( + +
+
+
Оценка способности (θ)
+
+ {view.uncertainty.theta} +
+
+
+
Стандартная ошибка (SE)
+
+ {view.uncertainty.standardError} +
+
+
+
95% интервал способности
+
+ {view.uncertainty.interval} +
+
+
+
Вероятность достичь порога выбранного грейда (P_G)
+
+ {view.uncertainty.pGrade} +
+
+ {view.strength ? ( +
+
Сила подтверждения
+
{view.strength}
+
+ ) : null} +
+

+ Значения даны на шкале специализации. + {view.isProvisional + ? " Пока пороги не откалиброваны, вероятность остается предварительной оценкой, а не измеренной долей." + : ""} +

+
+ ) : null} + {!view.uncertainty && view.strength ? ( +

+ Сила подтверждения: {view.strength}. +

+ ) : null} + {view.uncertaintyNote ?

{view.uncertaintyNote}

: null} + + {view.gaps.length > 0 ? ( + +
    + {view.gaps.map((gap, index) => ( +
  • {gap}
  • + ))} +
+
+ ) : null} + {view.gapsNote ?

{view.gapsNote}

: null} + + {view.practices.length > 0 || view.durations.length > 0 ? ( + + {view.practices.length > 0 ? ( +
    + {view.practices.map((practice, index) => ( +
  • {practice}
  • + ))} +
+ ) : null} +

+ {view.durations.join(". ")}. Время записано отдельной меткой и не влияет на решение. +

+
+ ) : null} + + {view.isExpress ? ( + +

Категорию дает только полная проверка. Демонстрация ее не заменяет.

+ Перейти к полной проверке +
+ ) : ( + + {view.nextSteps.length > 0 ? ( +
    + {view.nextSteps.map((step) => ( +
  • +

    {step.text}

    + {step.isOffer ? ( +

    + Категория не изменится, пока вы сами не подтвердите это действие. Такой + команды в интерфейсе пока нет. +

    + ) : null} + {step.availability ?

    {step.availability}

    : null} +
  • + ))} +
+ ) : null} + {view.nextStepsNote ?

{view.nextStepsNote}

: null} + {view.nextSteps.length > 0 ? ( +

+ Шаги рассчитаны сервером в момент решения. Сейчас доступность может быть другой: ее + показывает страница проверок. +

+ ) : null} + {testLinkVisible ? ( + + Проверить актуальную доступность + + ) : null} +
+ )} +
+ ); +} diff --git a/frontend/src/entities/candidate/api/home-queries.test.ts b/frontend/src/entities/candidate/api/home-queries.test.ts new file mode 100644 index 0000000..efe4638 --- /dev/null +++ b/frontend/src/entities/candidate/api/home-queries.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from "vitest"; +import { ApiRequestError, networkErrorCode } from "../../../shared/api"; +import type { + AssessmentAvailability, + CandidateProfile, + CandidateQuestionnaire, +} from "../../../shared/api/schemas"; +import { combineJourneyReads } from "./home-queries"; + +function read( + status: "pending" | "error" | "success", + data?: T, + error: Error | null = null, + refetch: () => unknown = () => undefined, +) { + return { status, data, error, isRefetching: false, refetch }; +} + +const profile = { version: 1 } as CandidateProfile; +const questionnaire = { + version: 1, + specializations: [ + { + specialization: "backend", + self_assessed_grade: "junior", + task_languages: [], + stack: [], + experience: null, + }, + ], + work_context: null, + updated_at: null, +} as CandidateQuestionnaire; +const availability = { + specializations: [ + { specialization: "backend", confirmed_grade: null, active_attempt_id: null, grades: [] }, + ], +} as AssessmentAvailability; + +function apiError(status: number) { + return new ApiRequestError({ status, code: networkErrorCode, title: "Failed." }); +} + +describe("combineJourneyReads", () => { + it("stays pending until all three reads arrive", () => { + const state = combineJourneyReads( + "candidate_profile", + read("success", profile), + read("pending"), + read("success", availability), + ); + + expect(state).toEqual({ status: "pending" }); + }); + + it("builds the journey from the three reads", () => { + const state = combineJourneyReads( + "candidate_assessment", + read("success", profile), + read("success", questionnaire), + read("success", availability), + ); + + expect(state.status).toBe("success"); + if (state.status === "success") { + expect(state.journey.savedStep).toBe("candidate_assessment"); + expect(state.journey.nextStep).toEqual({ kind: "assessment" }); + } + }); + + it("fails as a whole instead of guessing a step from partial data", () => { + const failure = apiError(500); + const state = combineJourneyReads( + "candidate_profile", + read("error", undefined, failure), + read("success", questionnaire), + read("success", availability), + ); + + expect(state).toMatchObject({ status: "error", error: failure }); + }); + + it("shows a denied read before other failures and retries only failed reads", () => { + const denied = apiError(403); + const failedProfile = vi.fn(); + const failedAvailability = vi.fn(); + const okQuestionnaire = vi.fn(); + const state = combineJourneyReads( + "candidate_profile", + read("error", undefined, apiError(500), failedProfile), + read("success", questionnaire, null, okQuestionnaire), + read("error", undefined, denied, failedAvailability), + ); + + expect(state.status).toBe("error"); + if (state.status === "error") { + expect(state.error).toBe(denied); + state.retry(); + } + expect(failedProfile).toHaveBeenCalledOnce(); + expect(failedAvailability).toHaveBeenCalledOnce(); + expect(okQuestionnaire).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/entities/candidate/api/home-queries.ts b/frontend/src/entities/candidate/api/home-queries.ts new file mode 100644 index 0000000..28e8350 --- /dev/null +++ b/frontend/src/entities/candidate/api/home-queries.ts @@ -0,0 +1,202 @@ +import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"; +import type { z } from "zod"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import { + getMyAssessmentAvailability, + listMyAssessmentResults, +} from "../../../shared/api/endpoints/assessment/assessment"; +import { + getMyProfile, + getMyQuestionnaire, +} from "../../../shared/api/endpoints/candidate/candidate"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import { getMyPrivacySettings } from "../../../shared/api/endpoints/privacy/privacy"; +import { + AssessmentAvailability, + AssessmentResultHistoryPage, + CandidateProfile, + CandidateQuestionnaire, + PrivacySettings, + type Session, +} from "../../../shared/api/schemas"; +import { buildCandidateJourney, type CandidateJourney } from "../model/home"; + +// The home needs only the version of the profile: 0 means it was never saved. +// The profile form validates the rest of the document itself. +const profileVersionSchema = CandidateProfile.pick({ version: true }); +type CandidateProfileVersion = Pick; + +const homeQueryPrefix = ["candidate-home"] as const; + +/** Account-scoped keys: a response for one account never fills another's cache. */ +export const candidateHomeQueryKeys = { + root: homeQueryPrefix, + profile: (accountId: string) => [...homeQueryPrefix, accountId, "profile"] as const, + questionnaire: (accountId: string) => [...homeQueryPrefix, accountId, "questionnaire"] as const, + availability: (accountId: string) => [...homeQueryPrefix, accountId, "availability"] as const, + latestResult: (accountId: string) => [...homeQueryPrefix, accountId, "latest-result"] as const, + privacy: (accountId: string) => [...homeQueryPrefix, accountId, "privacy"] as const, +}; + +// Personal data is not kept after the screen closes, and every visit reads the +// current state: the home screen must match the API after a refresh. +const privateQueryOptions = { + gcTime: 0, + staleTime: 0, + retry: false, + refetchOnMount: "always" as const, + refetchOnWindowFocus: "always" as const, +}; + +function parseResponse(schema: z.ZodType, value: unknown): unknown { + const parsed = schema.safeParse(value); + if (!parsed.success) { + throw new ApiRequestError({ + status: 200, + code: invalidResponseCode, + title: "The response does not match the API contract.", + }); + } + return parsed.data; +} + +function assertSameAccount(queryClient: QueryClient, accountId: string): void { + const current = queryClient.getQueryData(getGetCurrentSessionQueryKey()); + if (current?.account.id !== accountId) { + throw new Error("The candidate session changed during the home request."); + } +} + +function useHomeQuery( + session: Session | undefined, + key: (accountId: string) => readonly unknown[], + read: (signal: AbortSignal) => Promise, + schema: z.ZodType, +) { + const queryClient = useQueryClient(); + const accountId = session?.account.id; + const enabled = session?.account.scenario === "candidate"; + return useQuery({ + queryKey: key(accountId ?? "no-session"), + enabled, + ...privateQueryOptions, + queryFn: async ({ signal }) => { + if (!accountId) throw new Error("A candidate session is required."); + assertSameAccount(queryClient, accountId); + const response = await read(signal); + assertSameAccount(queryClient, accountId); + return parseResponse(schema, response) as T; + }, + }); +} + +export function useCandidateProfileRead(session: Session | undefined) { + return useHomeQuery( + session, + candidateHomeQueryKeys.profile, + (signal) => getMyProfile({ signal }), + profileVersionSchema, + ); +} + +export function useCandidateQuestionnaireRead(session: Session | undefined) { + return useHomeQuery( + session, + candidateHomeQueryKeys.questionnaire, + (signal) => getMyQuestionnaire({ signal }), + CandidateQuestionnaire, + ); +} + +export function useCandidateAvailabilityRead(session: Session | undefined) { + return useHomeQuery( + session, + candidateHomeQueryKeys.availability, + (signal) => getMyAssessmentAvailability({ signal }), + AssessmentAvailability, + ); +} + +/** Newest real result only: the home screen links to the full history. */ +export function useCandidateLatestResultRead(session: Session | undefined) { + return useHomeQuery( + session, + candidateHomeQueryKeys.latestResult, + (signal) => listMyAssessmentResults({ limit: 1 }, { signal }), + AssessmentResultHistoryPage, + ); +} + +export function useCandidatePrivacyRead(session: Session | undefined) { + return useHomeQuery( + session, + candidateHomeQueryKeys.privacy, + (signal) => getMyPrivacySettings({ signal }), + PrivacySettings, + ); +} + +type ReadResult = { + status: "pending" | "error" | "success"; + data: T | undefined; + error: Error | null; + isRefetching: boolean; + refetch: () => unknown; +}; + +export type CandidateJourneyState = + | { status: "pending" } + | { status: "error"; error: unknown; isRetrying: boolean; retry: () => void } + | { status: "success"; journey: CandidateJourney }; + +function isAccessError(error: unknown): boolean { + return error instanceof ApiRequestError && (error.status === 401 || error.status === 403); +} + +/** + * Joins the three reads that the next step depends on. One failed read fails + * the whole state, because a step chosen from partial data could send the + * candidate to a form they already completed. A denied read wins over other + * failures so that the forbidden state is shown instead of a retry. + */ +export function combineJourneyReads( + savedStep: CandidateJourney["savedStep"], + profile: ReadResult, + questionnaire: ReadResult, + availability: ReadResult, +): CandidateJourneyState { + const reads = [profile, questionnaire, availability]; + const failed = reads.filter((read) => read.status === "error"); + if (failed.length > 0) { + const denied = failed.find((read) => isAccessError(read.error)); + return { + status: "error", + error: (denied ?? failed[0])?.error, + isRetrying: failed.some((read) => read.isRefetching), + retry: () => { + for (const read of failed) void read.refetch(); + }, + }; + } + if (profile.data === undefined || questionnaire.data === undefined || !availability.data) { + return { status: "pending" }; + } + return { + status: "success", + journey: buildCandidateJourney({ + savedStep, + profileVersion: profile.data.version, + questionnaire: questionnaire.data, + availability: availability.data, + }), + }; +} + +/** Next-step state of the signed-in candidate, read from the current API state. */ +export function useCandidateJourney(session: Session | undefined): CandidateJourneyState { + const profile = useCandidateProfileRead(session); + const questionnaire = useCandidateQuestionnaireRead(session); + const availability = useCandidateAvailabilityRead(session); + if (!session) return { status: "pending" }; + return combineJourneyReads(session.account.onboarding_step, profile, questionnaire, availability); +} diff --git a/frontend/src/entities/candidate/index.ts b/frontend/src/entities/candidate/index.ts index 926adb9..6b1f251 100644 --- a/frontend/src/entities/candidate/index.ts +++ b/frontend/src/entities/candidate/index.ts @@ -26,3 +26,21 @@ export { type SoftSkillDraft, type StackDraft, } from "./model/profile-form"; +export { + buildCandidateJourney, + onboardingStepLabels, + summarizeVisibility, + type CandidateJourney, + type CandidateJourneyInput, + type CandidateNextStep, + type SpecializationStanding, + type VisibilitySummary, +} from "./model/home"; +export { + candidateHomeQueryKeys, + combineJourneyReads, + useCandidateJourney, + useCandidateLatestResultRead, + useCandidatePrivacyRead, + type CandidateJourneyState, +} from "./api/home-queries"; diff --git a/frontend/src/entities/candidate/model/home.test.ts b/frontend/src/entities/candidate/model/home.test.ts new file mode 100644 index 0000000..4d10c0d --- /dev/null +++ b/frontend/src/entities/candidate/model/home.test.ts @@ -0,0 +1,277 @@ +import { describe, expect, it } from "vitest"; +import type { + AssessmentAvailability, + GradeCode, + PrivacySettings, + SpecializationCode, +} from "../../../shared/api/schemas"; +import { buildCandidateJourney, summarizeVisibility, type CandidateJourneyInput } from "./home"; + +type Availability = AssessmentAvailability["specializations"][number]; + +function gradeRows(status: "available" | "cooldown"): Availability["grades"] { + return (["intern", "junior", "middle", "senior"] as const).map((grade) => ({ + grade, + status, + mode: null, + available_at: null, + time_limit_seconds: null, + max_sessions: null, + max_items: null, + practice_required: null, + })); +} + +function availabilityRow( + specialization: SpecializationCode, + options: { + confirmed?: GradeCode | null; + attemptId?: string | null; + status?: "available" | "cooldown"; + } = {}, +): Availability { + return { + specialization, + confirmed_grade: options.confirmed ?? null, + active_attempt_id: options.attemptId ?? null, + grades: gradeRows(options.status ?? "available"), + }; +} + +function questionnaire( + declared: [SpecializationCode, GradeCode][], + version = declared.length > 0 ? 1 : 0, +): CandidateJourneyInput["questionnaire"] { + return { + version, + specializations: declared.map(([specialization, grade]) => ({ + specialization, + self_assessed_grade: grade, + task_languages: [], + stack: [], + experience: null, + })), + }; +} + +function input(overrides: Partial = {}): CandidateJourneyInput { + return { + savedStep: "candidate_consents", + profileVersion: 0, + questionnaire: questionnaire([]), + availability: { specializations: [] }, + ...overrides, + }; +} + +describe("buildCandidateJourney next step", () => { + it("leads an empty profile to the profile form", () => { + expect(buildCandidateJourney(input()).nextStep).toEqual({ kind: "profile" }); + }); + + it("leads a saved profile without a questionnaire to the questionnaire", () => { + const journey = buildCandidateJourney(input({ profileVersion: 3 })); + + expect(journey.profileSaved).toBe(true); + expect(journey.nextStep).toEqual({ kind: "questionnaire" }); + }); + + it("does not wait for the stored step to advance past the consents step", () => { + // The server advances the stored step only from the matching step, so a + // saved profile can coexist with the stored consents step. + const journey = buildCandidateJourney( + input({ savedStep: "candidate_consents", profileVersion: 1 }), + ); + + expect(journey.savedStep).toBe("candidate_consents"); + expect(journey.nextStep).toEqual({ kind: "questionnaire" }); + }); + + it("leads a saved questionnaire to the test and keeps the declared grade", () => { + const journey = buildCandidateJourney( + input({ + savedStep: "candidate_assessment", + profileVersion: 1, + questionnaire: questionnaire([["backend", "middle"]]), + availability: { specializations: [availabilityRow("backend")] }, + }), + ); + + expect(journey.nextStep).toEqual({ kind: "assessment" }); + expect(journey.confirmed).toEqual([]); + expect(journey.standings).toEqual([ + { + specialization: "backend", + declaredGrade: "middle", + confirmedGrade: null, + activeAttemptId: null, + canStartAttempt: true, + }, + ]); + }); + + it("treats a questionnaire version without specializations as not saved", () => { + const journey = buildCandidateJourney( + input({ profileVersion: 1, questionnaire: questionnaire([], 2) }), + ); + + expect(journey.questionnaireSaved).toBe(false); + expect(journey.nextStep).toEqual({ kind: "questionnaire" }); + }); + + it("resumes the active attempt instead of offering a new test", () => { + const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80"; + const journey = buildCandidateJourney( + input({ + profileVersion: 1, + questionnaire: questionnaire([["backend", "junior"]]), + availability: { specializations: [availabilityRow("backend", { attemptId })] }, + }), + ); + + expect(journey.nextStep).toEqual({ + kind: "resume_attempt", + attemptId, + specialization: "backend", + }); + }); + + it("leads an obtained category to the result and keeps declared and confirmed apart", () => { + const journey = buildCandidateJourney( + input({ + savedStep: "candidate_assessment", + profileVersion: 1, + questionnaire: questionnaire([["backend", "middle"]]), + availability: { specializations: [availabilityRow("backend", { confirmed: "junior" })] }, + }), + ); + + expect(journey.nextStep).toEqual({ kind: "result" }); + expect(journey.confirmed).toHaveLength(1); + expect(journey.standings[0]).toMatchObject({ + declaredGrade: "middle", + confirmedGrade: "junior", + }); + }); + + it("offers the result even when the profile is still empty", () => { + const journey = buildCandidateJourney( + input({ + questionnaire: questionnaire([["qa", "junior"]]), + availability: { specializations: [availabilityRow("qa", { confirmed: "junior" })] }, + }), + ); + + expect(journey.nextStep).toEqual({ kind: "result" }); + }); + + it("reports that no test can start when every grade is blocked", () => { + const journey = buildCandidateJourney( + input({ + profileVersion: 1, + questionnaire: questionnaire([["backend", "junior"]]), + availability: { specializations: [availabilityRow("backend", { status: "cooldown" })] }, + }), + ); + + expect(journey.standings[0]?.canStartAttempt).toBe(false); + expect(journey.nextStep).toEqual({ kind: "assessment" }); + }); + + it("never turns a declared grade into a confirmed one", () => { + const journey = buildCandidateJourney( + input({ + savedStep: "completed", + profileVersion: 1, + questionnaire: questionnaire([["frontend", "senior"]]), + availability: { specializations: [] }, + }), + ); + + expect(journey.confirmed).toEqual([]); + expect(journey.standings[0]).toMatchObject({ + declaredGrade: "senior", + confirmedGrade: null, + }); + expect(journey.nextStep).toEqual({ kind: "assessment" }); + }); +}); + +describe("summarizeVisibility", () => { + function settings(overrides: { + publication?: Partial; + search?: Partial; + }): PrivacySettings { + return { + publication: { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, + ...overrides.publication, + }, + search_status: { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, + ...overrides.search, + }, + hidden_organizations_total: 0, + }; + } + + it("restates a closed card with its reason", () => { + expect(summarizeVisibility(settings({}))).toEqual({ + published: false, + closedReason: "never_published", + showsCategory: false, + searchStatus: { looking: false, lapsed: false, lapsesAt: null }, + }); + }); + + it("reports whether a published card includes the category", () => { + const published = { state: "published", closed_reason: null } as const; + + expect( + summarizeVisibility( + settings({ publication: { ...published, fields: ["categories", "stack"] } }), + ), + ).toMatchObject({ published: true, showsCategory: true }); + expect( + summarizeVisibility(settings({ publication: { ...published, fields: ["stack"] } })), + ).toMatchObject({ published: true, showsCategory: false }); + }); + + it("keeps the lapse moment only for a status that holds now", () => { + expect( + summarizeVisibility( + settings({ + search: { + value: "looking", + confirmed_at: "2026-10-01T10:00:00Z", + lapses_at: "2026-10-31T10:00:00Z", + }, + }), + ).searchStatus, + ).toEqual({ looking: true, lapsed: false, lapsesAt: "2026-10-31T10:00:00Z" }); + }); + + it("marks a lapsed search status", () => { + expect( + summarizeVisibility( + settings({ + search: { + lapsed: true, + confirmed_at: "2026-09-01T10:00:00Z", + lapses_at: "2026-10-01T10:00:00Z", + version: 4, + }, + }), + ).searchStatus, + ).toEqual({ looking: false, lapsed: true, lapsesAt: null }); + }); +}); diff --git a/frontend/src/entities/candidate/model/home.ts b/frontend/src/entities/candidate/model/home.ts new file mode 100644 index 0000000..6f4533d --- /dev/null +++ b/frontend/src/entities/candidate/model/home.ts @@ -0,0 +1,170 @@ +import type { + Account, + AssessmentAvailability, + CandidateQuestionnaire, + GradeCode, + PrivacySettings, + SpecializationCode, +} from "../../../shared/api/schemas"; + +type OnboardingStep = Account["onboarding_step"]; + +/** Plain names of the stored onboarding steps, for the saved-step line. */ +export const onboardingStepLabels: Readonly> = { + candidate_consents: "Согласия", + candidate_profile: "Профиль", + candidate_questionnaire: "Анкета", + candidate_assessment: "Тест", + employer_company: "Компания", + completed: "Онбординг завершен", +}; + +/** + * One questionnaire specialization with the two facts that must never be + * merged: what the candidate declared and what an assessment confirmed. + */ +export type SpecializationStanding = { + specialization: SpecializationCode; + /** Self-assessed grade from the questionnaire; a claim, not a category. */ + declaredGrade: GradeCode | null; + /** Grade that an assessment result confirmed, or null. */ + confirmedGrade: GradeCode | null; + /** Active attempt of this specialization that can be resumed. */ + activeAttemptId: string | null; + /** True when at least one grade can start a new attempt now. */ + canStartAttempt: boolean; +}; + +/** The single main action offered on the home screen. */ +export type CandidateNextStep = + | { kind: "profile" } + | { kind: "questionnaire" } + | { kind: "assessment" } + | { kind: "resume_attempt"; attemptId: string; specialization: SpecializationCode } + | { kind: "result" }; + +export type CandidateJourneyInput = { + /** `onboarding_step` of the current session account. */ + savedStep: OnboardingStep; + /** `version` of the profile read; 0 means it was never saved. */ + profileVersion: number; + questionnaire: Pick; + availability: Pick; +}; + +export type CandidateJourney = { + savedStep: OnboardingStep; + profileSaved: boolean; + questionnaireSaved: boolean; + standings: readonly SpecializationStanding[]; + /** Standings whose grade an assessment confirmed. */ + confirmed: readonly SpecializationStanding[]; + nextStep: CandidateNextStep; +}; + +function buildStandings(input: CandidateJourneyInput): SpecializationStanding[] { + const standings = new Map(); + + // The availability list is the server's view of the questionnaire + // specializations; the questionnaire adds the declared grade. + for (const item of input.availability.specializations) { + standings.set(item.specialization, { + specialization: item.specialization, + declaredGrade: null, + confirmedGrade: item.confirmed_grade, + activeAttemptId: item.active_attempt_id, + canStartAttempt: item.grades.some((grade) => grade.status === "available"), + }); + } + for (const item of input.questionnaire.specializations) { + const existing = standings.get(item.specialization); + standings.set(item.specialization, { + specialization: item.specialization, + declaredGrade: item.self_assessed_grade, + confirmedGrade: existing?.confirmedGrade ?? null, + activeAttemptId: existing?.activeAttemptId ?? null, + canStartAttempt: existing?.canStartAttempt ?? false, + }); + } + return [...standings.values()]; +} + +/** + * Chooses the main action from what the server returned. The stored + * onboarding step is kept for display and is never overridden; it is not the + * only input because the server advances it only when the profile or the + * questionnaire is saved from the matching step, so a saved profile can sit + * behind an earlier stored step. Presence of saved data therefore decides + * between the profile, the questionnaire, and the test. + * + * The client invents no category, grade, or threshold: a category exists only + * when the availability read returns a confirmed grade. + */ +export function buildCandidateJourney(input: CandidateJourneyInput): CandidateJourney { + const standings = buildStandings(input); + const confirmed = standings.filter((standing) => standing.confirmedGrade !== null); + const profileSaved = input.profileVersion > 0; + const questionnaireSaved = + input.questionnaire.version > 0 && input.questionnaire.specializations.length > 0; + + return { + savedStep: input.savedStep, + profileSaved, + questionnaireSaved, + standings, + confirmed, + nextStep: chooseNextStep({ profileSaved, questionnaireSaved, standings, confirmed }), + }; +} + +function chooseNextStep(state: { + profileSaved: boolean; + questionnaireSaved: boolean; + standings: readonly SpecializationStanding[]; + confirmed: readonly SpecializationStanding[]; +}): CandidateNextStep { + if (state.confirmed.length > 0) return { kind: "result" }; + if (!state.profileSaved) return { kind: "profile" }; + if (!state.questionnaireSaved) return { kind: "questionnaire" }; + const resumable = state.standings.find((standing) => standing.activeAttemptId !== null); + if (resumable?.activeAttemptId) { + return { + kind: "resume_attempt", + attemptId: resumable.activeAttemptId, + specialization: resumable.specialization, + }; + } + return { kind: "assessment" }; +} + +export type VisibilitySummary = { + /** True while organizations can read the card. */ + published: boolean; + /** Why the card is closed, or null while it is published. */ + closedReason: PrivacySettings["publication"]["closed_reason"]; + /** True only for a published card that includes the confirmed category. */ + showsCategory: boolean; + searchStatus: { + looking: boolean; + /** True when "looking" ran out because it was not confirmed again. */ + lapsed: boolean; + /** Moment the confirmed status lapses, for a status that holds now. */ + lapsesAt: string | null; + }; +}; + +/** Restates the privacy settings read without adding rules of its own. */ +export function summarizeVisibility(settings: PrivacySettings): VisibilitySummary { + const published = settings.publication.state === "published"; + return { + published, + closedReason: published ? null : settings.publication.closed_reason, + showsCategory: published && settings.publication.fields.includes("categories"), + searchStatus: { + looking: settings.search_status.value === "looking", + lapsed: settings.search_status.lapsed, + lapsesAt: + settings.search_status.value === "looking" ? settings.search_status.lapses_at : null, + }, + }; +} diff --git a/frontend/src/pages/assessment-result/index.ts b/frontend/src/pages/assessment-result/index.ts new file mode 100644 index 0000000..df9fdf4 --- /dev/null +++ b/frontend/src/pages/assessment-result/index.ts @@ -0,0 +1,2 @@ +export { AssessmentResultPage } from "./ui/assessment-result-page"; +export { AssessmentResultsPage } from "./ui/assessment-results-page"; diff --git a/frontend/src/pages/assessment-result/ui/assessment-result-page.module.css b/frontend/src/pages/assessment-result/ui/assessment-result-page.module.css new file mode 100644 index 0000000..0441164 --- /dev/null +++ b/frontend/src/pages/assessment-result/ui/assessment-result-page.module.css @@ -0,0 +1,20 @@ +.layout { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.back { + display: flex; + flex-wrap: wrap; +} + +.pending { + display: grid; + gap: var(--space-3); + justify-items: start; +} + +.pending p { + margin: 0; +} diff --git a/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx b/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx new file mode 100644 index 0000000..a59079e --- /dev/null +++ b/frontend/src/pages/assessment-result/ui/assessment-result-page.tsx @@ -0,0 +1,142 @@ +import { useEffect } from "react"; +import { useParams } from "react-router-dom"; +import type { QueryClient } from "@tanstack/react-query"; +import { ApiRequestError } from "../../../shared/api"; +import type { Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config/paths"; +import { + Button, + ButtonLink, + ErrorState, + ForbiddenState, + LoadingState, + Page, +} from "../../../shared/ui"; +import { + AssessmentActorGate, + AssessmentResultView, + isAssessmentAccessLoss, + isAssessmentSessionEnded, + removeAssessmentQueries, + useAssessmentResult, +} from "../../../entities/assessment"; +import styles from "./assessment-result-page.module.css"; + +const attemptIdPattern = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +/** One stored result, opened by a direct URL; only its owner can read it. */ +export function AssessmentResultPage() { + const { attemptId = "" } = useParams(); + return ( + + + {({ actor, queryClient }) => ( + + )} + + + ); +} + +function StoredResult({ + actor, + queryClient, + attemptId, +}: { + actor: Session; + queryClient: QueryClient; + attemptId: string; +}) { + const validId = attemptIdPattern.test(attemptId); + const result = useAssessmentResult({ actor, attemptId, enabled: validId, queryClient }); + const accessLost = result.isError && isAssessmentAccessLoss(result.error); + const sessionEnded = result.isError && isAssessmentSessionEnded(result.error); + + useEffect(() => { + if (sessionEnded) removeAssessmentQueries(queryClient); + }, [sessionEnded, queryClient]); + + const back = ( +
+ + К истории результатов + +
+ ); + + if (!validId) { + return ( + <> + + {back} + + ); + } + if (accessLost) { + return ( + <> + Перейти ко входу} + /> + {back} + + ); + } + if (result.isPending) return ; + if (!result.data) { + return ( + <> + {result.error instanceof ApiRequestError && result.error.status === 409 ? ( +
+

Сервер еще завершает обработку результата. Повторите проверку позже.

+ +
+ ) : ( + void result.refetch()} + title="Не удалось загрузить результат" + /> + )} + {back} + + ); + } + return ( +
+ {result.isError ? ( + void result.refetch()} + title="Не удалось обновить результат. Показан ранее загруженный." + /> + ) : null} + + {back} +
+ ); +} diff --git a/frontend/src/pages/assessment-result/ui/assessment-result-pages.test.tsx b/frontend/src/pages/assessment-result/ui/assessment-result-pages.test.tsx new file mode 100644 index 0000000..2e947a2 --- /dev/null +++ b/frontend/src/pages/assessment-result/ui/assessment-result-pages.test.tsx @@ -0,0 +1,246 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { AssessmentResult, Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { assessmentQueryKeys } from "../../../entities/assessment"; +import { AssessmentResultPage } from "./assessment-result-page"; +import { AssessmentResultsPage } from "./assessment-results-page"; + +const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"; + +const session = { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), +} satisfies Session; + +const adaptive = { + attempt_id: attemptId, + specialization: "backend", + target_grade: "middle", + root_attempt_id: null, + chain_deadline: null, + task_language: "go", + kind: "root", + mode: "adaptive", + versions: { bank_version: "demo-1", algorithm_version: "adaptive-1", policy_version: 1 }, + outcome: "confirmed", + not_determined_reason: null, + confirmed_grade: "middle", + previous_confirmed_grade: null, + category_decision: { + status: "assigned", + previous_confirmed_grade: null, + current_confirmed_grade: "middle", + method: null, + source: null, + calibration_status: "uncalibrated", + }, + strength: "medium", + calibration_status: "uncalibrated", + limitations: ["uncalibrated_thresholds"], + uncertainty: { + theta: 0.42, + standard_error: 0.21, + interval_95: { low: -0.19, high: 1.03 }, + p_grade: 0.8, + }, + basic_score: null, + practices: [], + gaps: [], + durations: { items_seconds: 900, practice_seconds: null }, + next_steps: [{ action: "take_higher_grade", grade: "senior", available_at: null }], + decided_at: "2026-10-08T09:30:00Z", +} as unknown as AssessmentResult; + +type Prepare = (queryClient: QueryClient) => void; + +function signedIn(queryClient: QueryClient) { + queryClient.setQueryData(getGetCurrentSessionQueryKey(), session); +} + +function sessionRefused(queryClient: QueryClient) { + queryClient + .getQueryCache() + .build(queryClient, { queryKey: getGetCurrentSessionQueryKey() }) + .setState({ + status: "error", + error: new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }), + errorUpdateCount: 1, + fetchStatus: "idle", + }); +} + +function render(path: string, prepare: Prepare): string { + // Server rendering refetches an errored query on mount unless told not to. + const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } }); + prepare(queryClient); + return renderToStaticMarkup( + + + + } /> + } + /> + + + , + ); +} + +describe("AssessmentResultPage", () => { + it("opens the stored result of the signed-in candidate by its URL", () => { + const html = render(paths.candidate.result(attemptId), (queryClient) => { + signedIn(queryClient); + queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive); + }); + expect(html).toContain("Уровень подтвержден: Backend, Middle."); + expect(html).toContain("0,80"); + expect(html).toContain("средняя"); + expect(html).toContain(`href="${paths.candidate.results}"`); + }); + + it("shows no data by a direct URL when the session was refused", () => { + const html = render(paths.candidate.result(attemptId), (queryClient) => { + sessionRefused(queryClient); + queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive); + }); + expect(html).toContain("Результаты недоступны"); + expect(html).toContain(`href="${paths.login}"`); + expect(html).not.toContain("Backend"); + expect(html).not.toContain("0,80"); + }); + + it("shows no data for a result of another session key", () => { + const html = render(paths.candidate.result(attemptId), (queryClient) => { + signedIn(queryClient); + queryClient.setQueryData( + assessmentQueryKeys.result( + { + ...session, + account: { ...session.account, id: "22222222-2222-4222-8222-222222222222" }, + }, + attemptId, + ), + adaptive, + ); + }); + expect(html).not.toContain("Backend"); + expect(html).toContain("Загружаем сохраненный результат..."); + }); + + it("refuses to read a malformed identifier", () => { + const html = render(`${paths.candidate.results}/not-an-id`, signedIn); + expect(html).toContain("Не удалось открыть результат"); + }); + + it("explains a result the server does not return for this candidate", () => { + const html = render(paths.candidate.result(attemptId), (queryClient) => { + signedIn(queryClient); + queryClient + .getQueryCache() + .build(queryClient, { queryKey: assessmentQueryKeys.result(session, attemptId) }) + .setState({ + status: "error", + error: new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }), + errorUpdateCount: 1, + fetchStatus: "idle", + }); + }); + expect(html).toContain("Результат недоступен"); + expect(html).not.toContain("Backend"); + }); +}); + +describe("AssessmentResultPage failures", () => { + function failWith(error: ApiRequestError, withData = false): Prepare { + return (queryClient) => { + signedIn(queryClient); + const key = assessmentQueryKeys.result(session, attemptId); + if (withData) queryClient.setQueryData(key, adaptive); + queryClient + .getQueryCache() + .build(queryClient, { queryKey: key }) + .setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" }); + }; + } + + it("tells an ended session from a missing result", () => { + const ended = render( + paths.candidate.result(attemptId), + failWith(new ApiRequestError({ status: 401, code: "unauthenticated", title: "No session" })), + ); + const missing = render( + paths.candidate.result(attemptId), + failWith(new ApiRequestError({ status: 404, code: "not_found", title: "Not found" })), + ); + expect(ended).toContain("Сеанс закончился."); + expect(missing).toContain("Сервер не нашел этот результат среди ваших."); + expect(missing).not.toContain("Сеанс закончился."); + }); + + it("offers exactly one retry for a server error", () => { + const html = render( + paths.candidate.result(attemptId), + failWith(new ApiRequestError({ status: 500, code: "internal", title: "Internal error" })), + ); + expect(html).toContain("Не удалось загрузить результат"); + expect(html.match(/Повторить/g)).toHaveLength(1); + expect(html).not.toContain("Обновить результат"); + }); + + it("keeps the loaded result when a refresh fails", () => { + const html = render( + paths.candidate.result(attemptId), + failWith( + new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }), + true, + ), + ); + expect(html).toContain("Уровень подтвержден: Backend, Middle."); + expect(html).toContain("Не удалось обновить результат. Показан ранее загруженный."); + }); + + it("offers a retry instead of claiming lost access when the session check fails", () => { + const html = render(paths.candidate.result(attemptId), (queryClient) => { + queryClient + .getQueryCache() + .build(queryClient, { queryKey: getGetCurrentSessionQueryKey() }) + .setState({ + status: "error", + error: new ApiRequestError({ status: 503, code: "internal", title: "Unavailable" }), + errorUpdateCount: 1, + fetchStatus: "idle", + }); + }); + expect(html).toContain("Не удалось проверить вход"); + expect(html).toContain("Повторить"); + expect(html).not.toContain("Результаты недоступны"); + }); +}); + +describe("AssessmentResultsPage", () => { + it("shows the history heading for the signed-in candidate", () => { + const html = render(paths.candidate.results, signedIn); + expect(html).toContain("Результаты проверок"); + expect(html).toContain("Загружаем историю результатов..."); + }); + + it("opens no history without a session", () => { + const html = render(paths.candidate.results, sessionRefused); + expect(html).toContain("Результаты недоступны"); + expect(html).not.toContain("Загружаем историю результатов..."); + }); +}); diff --git a/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx b/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx new file mode 100644 index 0000000..d10178c --- /dev/null +++ b/frontend/src/pages/assessment-result/ui/assessment-results-page.tsx @@ -0,0 +1,18 @@ +import { Page } from "../../../shared/ui"; +import { AssessmentActorGate } from "../../../entities/assessment"; +import { AssessmentHistory } from "../../../widgets/assessment-history"; + +/** History of the signed-in candidate's real assessment results. */ +export function AssessmentResultsPage() { + return ( + + + {({ actor, queryClient }) => } + + + ); +} diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css index 0bec27a..6cd7d36 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.module.css @@ -15,7 +15,6 @@ .resume, .finalize, .info, -.result, .item { display: grid; gap: var(--space-3); @@ -27,8 +26,7 @@ .resume p, .finalize p, -.info p, -.result p { +.info p { margin: 0; } @@ -73,12 +71,9 @@ } .result { - border-inline-start: var(--line-strong) solid var(--color-accent); - background: var(--color-canvas); -} - -.demo-label { - font-weight: var(--font-weight-bold); + display: grid; + gap: var(--space-3); + min-width: 0; } .result-error { @@ -95,8 +90,17 @@ .resume, .finalize, .info, - .result, .item { padding: var(--space-3); } } + +.result-heading { + margin: 0; + font-size: var(--font-size-l); +} + +.result-heading:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx index 65d21c4..04b1154 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx @@ -13,6 +13,7 @@ import { import type { AssessmentAttempt, AssessmentFinalization, + AssessmentResult, Session, } from "../../../shared/api/schemas"; import { paths } from "../../../shared/config/paths"; @@ -24,10 +25,11 @@ import { LoadingState, Page, Section, + VisuallyHidden, } from "../../../shared/ui"; import { + AssessmentResultView, assessmentQueryKeys, - assessmentResultSummary, assessmentSessionMatches, gradeLabels, isOutcomeAmbiguous, @@ -679,11 +681,22 @@ function ResultView({ resultQuery }: { resultQuery: ReturnType; } - if (resultQuery.isError || !resultQuery.data) { + if (!resultQuery.data) { return (
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? ( -

Сервер еще завершает обработку результата. Повторите проверку позже.

+ <> +

+ Сервер еще завершает обработку результата. Повторите проверку позже. +

+ + ) : ( )} -
); } - const result = resultQuery.data; - const summary = assessmentResultSummary(result); + return ; +} + +/** + * The result of a finished attempt. Only a short phrase is a live message; + * the full record is ordinary content, and the focus moves to its heading so + * a screen reader starts reading at the result. + */ +function ResultPanel({ result }: { result: AssessmentResult }) { + const headingRef = useRef(null); + useEffect(() => { + headingRef.current?.focus(); + }, []); return ( -
-

Результат с сервера

-

{summary.text}

- {summary.reason ?

{summary.reason}

: null} - {summary.isDemonstration ? ( -

- Только демонстрация. Подтвержденный грейд не присваивается. -

- ) : null} +
+

+ Результат получен. +

+

+ Результат с сервера +

+ +
+ + Открыть на странице результатов + +
); } diff --git a/frontend/src/pages/candidate-home/index.ts b/frontend/src/pages/candidate-home/index.ts new file mode 100644 index 0000000..016a383 --- /dev/null +++ b/frontend/src/pages/candidate-home/index.ts @@ -0,0 +1 @@ +export { CandidateHomePage } from "./ui/candidate-home-page"; diff --git a/frontend/src/pages/candidate-home/ui/candidate-home-page.module.css b/frontend/src/pages/candidate-home/ui/candidate-home-page.module.css new file mode 100644 index 0000000..e77cebf --- /dev/null +++ b/frontend/src/pages/candidate-home/ui/candidate-home-page.module.css @@ -0,0 +1,53 @@ +.columns { + display: grid; + gap: var(--space-6); +} + +@media (width >= 64rem) { + .columns { + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; + } +} + +.facts { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--space-1) var(--space-4); + margin: 0; +} + +@media (width >= 48rem) { + .facts { + grid-template-columns: minmax(10rem, auto) minmax(0, 1fr); + } +} + +.facts dt { + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.facts dd { + min-width: 0; + margin: 0 0 var(--space-2); + overflow-wrap: anywhere; +} + +.result-text { + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); + line-height: var(--line-height-snug); +} + +.reason { + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.links { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-5); +} diff --git a/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx b/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx new file mode 100644 index 0000000..a33bb89 --- /dev/null +++ b/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx @@ -0,0 +1,256 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToString } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { candidateHomeQueryKeys } from "../../../entities/candidate"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; +import { CandidateHomePage } from "./candidate-home-page"; + +const accountId = "11111111-1111-4111-8111-111111111111"; +const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80"; + +const session = { + account: { + id: accountId, + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "candidate_consents", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), +} satisfies Session; + +type Seed = { + step?: Session["account"]["onboarding_step"]; + profileVersion?: number; + declared?: { specialization: string; grade: string } | null; + confirmed?: string | null; + activeAttempt?: string | null; + results?: unknown[]; + privacy?: unknown; +}; + +const closedPrivacy = { + publication: { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, + }, + search_status: { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, + }, + hidden_organizations_total: 0, +}; + +function render(seed: Seed = {}): string { + const queryClient = new QueryClient(); + queryClient.setQueryData(getGetCurrentSessionQueryKey(), { + ...session, + account: { ...session.account, onboarding_step: seed.step ?? "candidate_consents" }, + }); + queryClient.setQueryData(candidateHomeQueryKeys.profile(accountId), { + version: seed.profileVersion ?? 0, + }); + queryClient.setQueryData(candidateHomeQueryKeys.questionnaire(accountId), { + version: seed.declared ? 1 : 0, + specializations: seed.declared + ? [ + { + specialization: seed.declared.specialization, + self_assessed_grade: seed.declared.grade, + task_languages: [], + stack: [], + experience: null, + }, + ] + : [], + work_context: null, + updated_at: null, + }); + queryClient.setQueryData(candidateHomeQueryKeys.availability(accountId), { + specializations: seed.declared + ? [ + { + specialization: seed.declared.specialization, + confirmed_grade: seed.confirmed ?? null, + active_attempt_id: seed.activeAttempt ?? null, + grades: [ + { + grade: seed.declared.grade, + status: "available", + mode: null, + available_at: null, + time_limit_seconds: null, + max_sessions: null, + max_items: null, + practice_required: null, + }, + ], + }, + ] + : [], + }); + queryClient.setQueryData(candidateHomeQueryKeys.latestResult(accountId), { + items: seed.results ?? [], + page: { has_more: false, next_cursor: null }, + }); + queryClient.setQueryData( + candidateHomeQueryKeys.privacy(accountId), + seed.privacy ?? closedPrivacy, + ); + + return renderToString( + + + + + , + ); +} + +function linkTo(html: string, href: string, text: string): boolean { + return new RegExp(`]*href="${href}"[^>]*>${text}`).test(html); +} + +describe("candidate home", () => { + it("leads an empty profile to the form without requiring any linking", () => { + const html = render(); + + expect(html).toMatch(/]*>Главная<\/h1>/); + expect(html).toContain("Заполните профиль"); + expect(linkTo(html, "/candidate/profile", "Заполнить профиль")).toBe(true); + expect(html).toContain("Сохраненный шаг аккаунта: Согласия"); + expect(html).toContain("Привязка ФСП ID необязательна"); + // A missing FSP link or ML result is never an error. + expect(html).not.toContain('role="alert"'); + }); + + it("leads a filled profile to the questionnaire", () => { + const html = render({ profileVersion: 2 }); + + expect(html).toContain("Заполните анкету"); + expect(linkTo(html, "/candidate/questionnaire", "Заполнить анкету")).toBe(true); + }); + + it("leads a saved questionnaire to the test and shows no confirmed category", () => { + const html = render({ + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "middle" }, + }); + + expect(html).toContain("Подтвердите уровень тестом"); + expect(linkTo(html, "/candidate/assessment", "Перейти к тесту")).toBe(true); + expect(html).toContain("Заявлено: Middle"); + expect(html).toContain("Пока не подтверждена"); + expect(html).not.toContain("Подтверждено тестом:"); + expect(html).toContain("Завершенных попыток пока нет"); + }); + + it("resumes an active attempt", () => { + const html = render({ + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "junior" }, + activeAttempt: attemptId, + }); + + expect(html).toContain("Продолжите тест"); + expect(linkTo(html, `/candidate/assessment/${attemptId}`, "Продолжить попытку")).toBe(true); + }); + + it("shows the result, the privacy link, and the declared grade apart from the category", () => { + const html = render({ + step: "candidate_assessment", + profileVersion: 2, + declared: { specialization: "backend", grade: "middle" }, + confirmed: "junior", + }); + + expect(html).toContain("Категория получена"); + expect(linkTo(html, "/candidate/results", "Открыть результат")).toBe(true); + expect(linkTo(html, "/candidate/privacy", "Настроить видимость")).toBe(true); + expect(html).toContain("Заявлено: Middle"); + expect(html).toContain("Подтверждено тестом: Junior"); + expect(html).toContain("Закрыта: компании ее не видят. Вы еще не публиковали карточку."); + }); + + it("restates a published card and an active search status from the API", () => { + const html = render({ + profileVersion: 1, + declared: { specialization: "qa", grade: "junior" }, + confirmed: "junior", + privacy: { + publication: { + state: "published", + closed_reason: null, + fields: ["categories"], + consent_id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81", + published_at: "2026-10-08T10:00:00Z", + version: 2, + }, + search_status: { + value: "looking", + lapsed: false, + confirmed_at: "2026-10-08T10:00:00Z", + lapses_at: "2026-11-07T10:00:00Z", + version: 1, + }, + hidden_organizations_total: 0, + }, + }); + + expect(html).toContain("Открыта: компании видят выбранные поля"); + expect(html).toContain("Показывается"); + expect(html).toContain("Ищу работу, статус действует до"); + }); + + it("describes a result that did not assign a category without presenting a grade", () => { + const html = render({ + step: "candidate_assessment", + profileVersion: 1, + declared: { specialization: "backend", grade: "junior" }, + results: [ + { + attempt_id: attemptId, + specialization: "backend", + target_grade: "junior", + root_attempt_id: null, + chain_deadline: null, + task_language: null, + kind: "root", + mode: "demo_basic", + versions: {}, + outcome: "not_confirmed", + not_determined_reason: null, + confirmed_grade: null, + previous_confirmed_grade: null, + strength: null, + calibration_status: "uncalibrated", + limitations: [], + uncertainty: null, + basic_score: null, + practices: [], + gaps: [], + durations: {}, + next_steps: [], + decided_at: "2026-10-08T10:00:00Z", + }, + ], + }); + + expect(html).toContain("Уровень пока не подтвержден: Backend, Junior."); + expect(linkTo(html, `/candidate/results/${attemptId}`, "Открыть разбор результата")).toBe(true); + expect(html).not.toContain("Подтверждено тестом:"); + expect(html).toContain("Пока не подтверждена"); + }); +}); diff --git a/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx b/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx new file mode 100644 index 0000000..1b0c202 --- /dev/null +++ b/frontend/src/pages/candidate-home/ui/candidate-home-page.tsx @@ -0,0 +1,147 @@ +import { + summarizeVisibility, + useCandidateLatestResultRead, + useCandidatePrivacyRead, + type VisibilitySummary, +} from "../../../entities/candidate"; +import { assessmentResultSummary } from "../../../entities/assessment"; +import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; +import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { ButtonLink, EmptyState, Page, QueryView, Section, TextLink } from "../../../shared/ui"; +import { CandidateNextStep } from "../../../widgets/candidate-next-step"; +import styles from "./candidate-home-page.module.css"; + +const closedReasonText: Readonly, string>> = { + never_published: "Вы еще не публиковали карточку.", + closed_by_candidate: "Вы закрыли карточку.", + consent_revoked: "Согласие C2 отозвано, поэтому карточка закрыта.", +}; + +function formatDate(value: string): string { + return new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium" }).format(new Date(value)); +} + +function searchStatusText(search: VisibilitySummary["searchStatus"]): string { + if (search.looking) { + return search.lapsesAt + ? `Ищу работу, статус действует до ${formatDate(search.lapsesAt)}` + : "Ищу работу"; + } + return search.lapsed + ? "Статус «Ищу работу» истек, сейчас: не ищу. Подтвердите его на странице приватности." + : "Не ищу работу"; +} + +function VisibilityFacts({ settings }: { settings: PrivacySettings }) { + const visibility = summarizeVisibility(settings); + return ( + <> +
+
Карточка для компаний
+
+ {visibility.published + ? "Открыта: компании видят выбранные поля" + : `Закрыта: компании ее не видят. ${ + visibility.closedReason ? closedReasonText[visibility.closedReason] : "" + }`.trim()} +
+ {visibility.published ? ( + <> +
Категория в карточке
+
{visibility.showsCategory ? "Показывается" : "Не показывается"}
+ + ) : null} +
Статус поиска
+
{searchStatusText(visibility.searchStatus)}
+
+
+ + Настроить видимость и согласия + +
+ + ); +} + +function VisibilitySection() { + const session = useGetCurrentSession(); + const privacy = useCandidatePrivacyRead(session.data); + return ( +
+ + {(settings) => } + +
+ ); +} + +function LatestResult({ page }: { page: AssessmentResultHistoryPage }) { + const [latest] = page.items; + if (!latest) return null; + const summary = assessmentResultSummary(latest); + return ( + <> +

{summary.text}

+ {summary.reason ?

{summary.reason}

: null} +

Решение сохранено: {formatDate(latest.decided_at)}

+
+ + Открыть разбор результата + + История результатов +
+ + ); +} + +function LatestResultSection() { + const session = useGetCurrentSession(); + const results = useCandidateLatestResultRead(session.data); + return ( +
+ page.items.length === 0} + empty={ + + } + > + {(page) => } + +
+ ); +} + +/** + * Candidate home: the next step and links to available actions, then the + * last assessment result and the current visibility of the profile. The + * independent blocks fail on their own, so one failed read never hides the + * next step. + */ +export function CandidateHomePage() { + return ( + + +
+ + +
+
+ ); +} diff --git a/frontend/src/shared/config/paths.ts b/frontend/src/shared/config/paths.ts index 78b2037..6ee77a1 100644 --- a/frontend/src/shared/config/paths.ts +++ b/frontend/src/shared/config/paths.ts @@ -18,6 +18,7 @@ export const paths = { assessmentAttempt: (attemptId: string) => `/candidate/assessment/${encodeURIComponent(attemptId)}`, results: "/candidate/results", + result: (attemptId: string) => `/candidate/results/${encodeURIComponent(attemptId)}`, invitations: "/candidate/invitations", privacy: "/candidate/privacy", supportCases: "/candidate/support/cases", diff --git a/frontend/src/widgets/assessment-history/index.ts b/frontend/src/widgets/assessment-history/index.ts new file mode 100644 index 0000000..4886583 --- /dev/null +++ b/frontend/src/widgets/assessment-history/index.ts @@ -0,0 +1,2 @@ +export { AssessmentHistory } from "./ui/assessment-history"; +export { AssessmentHistoryList } from "./ui/assessment-history-list"; diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx b/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx new file mode 100644 index 0000000..d385a2e --- /dev/null +++ b/frontend/src/widgets/assessment-history/ui/assessment-history-list.tsx @@ -0,0 +1,45 @@ +import type { Ref } from "react"; +import type { AssessmentResult } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config/paths"; +import { TextLink } from "../../../shared/ui"; +import { describeAssessmentResult } from "../../../entities/assessment"; +import styles from "./assessment-history.module.css"; + +type AssessmentHistoryListProps = { + items: readonly AssessmentResult[]; + /** IANA zone for dates; the browser zone when omitted. */ + timeZone?: string; + listRef?: Ref; +}; + +/** + * Compact rows of stored results, newest first as the server ordered them. + * Each row restates the server decision; the full record is one link away. + */ +export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHistoryListProps) { + return ( +
    + {items.map((item) => { + const view = describeAssessmentResult(item, timeZone ? { timeZone } : {}); + return ( +
  1. +

    {view.kindLabel}

    +

    {view.title}

    +

    {view.summary.text}

    +
    + {view.facts.map((fact) => ( +
    +
    {fact.label}
    +
    {fact.value}
    +
    + ))} +
    + + Открыть результат: {view.title}, {view.decidedDay} + +
  2. + ); + })} +
+ ); +} diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history.module.css b/frontend/src/widgets/assessment-history/ui/assessment-history.module.css new file mode 100644 index 0000000..63b35f0 --- /dev/null +++ b/frontend/src/widgets/assessment-history/ui/assessment-history.module.css @@ -0,0 +1,87 @@ +.root { + display: grid; + gap: var(--space-4); + min-width: 0; +} + +.note { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.list { + display: grid; + gap: var(--space-4); + margin: 0; + padding: 0; + list-style: none; +} + +.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); + background: var(--color-surface); +} + +.item p { + margin: 0; + overflow-wrap: anywhere; +} + +.kind { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.title { + margin: 0; + font-size: var(--font-size-l); + line-height: var(--line-height-snug); + overflow-wrap: anywhere; +} + +.summary { + font-weight: var(--font-weight-bold); +} + +.facts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr)); + gap: var(--space-3); + margin: 0; +} + +.facts > div { + display: grid; + gap: var(--space-1); + min-width: 0; +} + +.facts dt { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +@media (width < 42rem) { + .item { + padding: var(--space-3); + } +} + +.live { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history.test.tsx b/frontend/src/widgets/assessment-history/ui/assessment-history.test.tsx new file mode 100644 index 0000000..d315a1a --- /dev/null +++ b/frontend/src/widgets/assessment-history/ui/assessment-history.test.tsx @@ -0,0 +1,217 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import type { AssessmentResult, Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config"; +import { assessmentQueryKeys } from "../../../entities/assessment"; +import { AssessmentHistory } from "./assessment-history"; +import { AssessmentHistoryList } from "./assessment-history-list"; + +const session = { + account: { + id: "11111111-1111-4111-8111-111111111111", + email: "person@example.test", + email_verified: true, + scenario: "candidate", + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), +} satisfies Session; + +function stored(id: string, patch: Record = {}): AssessmentResult { + return { + attempt_id: id, + specialization: "backend", + target_grade: "middle", + root_attempt_id: null, + chain_deadline: null, + task_language: "go", + kind: "root", + mode: "demo_basic", + versions: { bank_version: "demo-1", algorithm_version: "basic-1", policy_version: 1 }, + outcome: "confirmed", + not_determined_reason: null, + confirmed_grade: "middle", + previous_confirmed_grade: null, + category_decision: { + status: "assigned", + previous_confirmed_grade: null, + current_confirmed_grade: "middle", + method: "demo_basic_pass_mark", + source: "synthetic_demo", + calibration_status: "uncalibrated", + }, + strength: null, + calibration_status: "uncalibrated", + limitations: ["demo_bank"], + uncertainty: null, + basic_score: { points: 17, max_points: 20, pass_points: 14 }, + practices: [], + gaps: [], + durations: { items_seconds: 600, practice_seconds: null }, + next_steps: [], + decided_at: "2026-10-08T09:30:00Z", + ...patch, + } as unknown as AssessmentResult; +} + +function render(prepare: (queryClient: QueryClient) => void): string { + // Server rendering refetches an errored query on mount unless told not to. + const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } }); + prepare(queryClient); + return renderToStaticMarkup( + + + + + , + ); +} + +function seedPages(queryClient: QueryClient, pages: unknown[]) { + queryClient.setQueryData(assessmentQueryKeys.resultHistory(session), { + pages, + pageParams: pages.map(() => null), + }); +} + +function seedError(queryClient: QueryClient, error: Error) { + queryClient + .getQueryCache() + .build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) }) + .setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" }); +} + +const firstId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"; +const secondId = "0199b4f2-7c1e-7d3a-9f00-112233445566"; + +describe("AssessmentHistory", () => { + it("lists stored results with a link to each and says express runs are excluded", () => { + const html = render((queryClient) => + seedPages(queryClient, [ + { + items: [stored(firstId), stored(secondId, { outcome: "not_confirmed" })], + page: { has_more: false, next_cursor: null }, + }, + ]), + ); + expect(html).toContain("Backend, Middle"); + expect(html).toContain(`href="${paths.candidate.result(firstId)}"`); + expect(html).toContain(`href="${paths.candidate.result(secondId)}"`); + expect(html).toContain("Демонстрационные запуски сюда не попадают"); + expect(html).not.toContain("Показать еще"); + }); + + it("offers the next page only while the server reports one", () => { + const html = render((queryClient) => + seedPages(queryClient, [ + { items: [stored(firstId)], page: { has_more: true, next_cursor: "next_page" } }, + ]), + ); + expect(html).toContain("Показать еще"); + }); + + it("shows an empty state with a way to the checks", () => { + const html = render((queryClient) => + seedPages(queryClient, [{ items: [], page: { has_more: false, next_cursor: null } }]), + ); + expect(html).toContain("Результатов пока нет"); + expect(html).toContain(`href="${paths.candidate.assessment}"`); + }); + + it("shows a load error with a retry and no stale rows", () => { + const html = render((queryClient) => + seedError( + queryClient, + new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }), + ), + ); + expect(html).toContain("Не удалось загрузить историю результатов"); + expect(html).toContain("Повторить"); + expect(html).not.toContain("Backend"); + }); + + it("shows no data once the server refuses access", () => { + const html = render((queryClient) => + seedError( + queryClient, + new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }), + ), + ); + expect(html).toContain("История результатов недоступна"); + expect(html).toContain(`href="${paths.login}"`); + expect(html).not.toContain("Backend"); + }); + + it("names each link with the title and the decision date", () => { + const html = render((queryClient) => + seedPages(queryClient, [ + { items: [stored(firstId)], page: { has_more: false, next_cursor: null } }, + ]), + ); + expect(html).toMatch(/Открыть результат: Backend, Middle, \d{1,2} \S+ 2026 г\./); + }); + + it("separates an ended session from a refused one", () => { + const ended = render((queryClient) => + seedError( + queryClient, + new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }), + ), + ); + const refused = render((queryClient) => + seedError( + queryClient, + new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }), + ), + ); + expect(ended).toContain("Сеанс закончился."); + expect(refused).not.toContain("Сеанс закончился."); + expect(refused).toContain("История результатов недоступна"); + }); + + it("keeps the loaded rows and says so when a refresh fails", () => { + const html = render((queryClient) => { + seedPages(queryClient, [ + { items: [stored(firstId)], page: { has_more: false, next_cursor: null } }, + ]); + queryClient + .getQueryCache() + .build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) }) + .setState({ + status: "error", + error: new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }), + errorUpdateCount: 1, + fetchStatus: "idle", + }); + }); + expect(html).toContain("Backend, Middle"); + expect(html).toContain("Не удалось обновить историю. Показаны ранее загруженные результаты."); + }); + + it("shows the loading state before the first answer", () => { + const html = render(() => {}); + expect(html).toContain("Загружаем историю результатов..."); + }); +}); + +describe("AssessmentHistoryList", () => { + it("keeps the order the server sent", () => { + const html = renderToStaticMarkup( + + + , + ); + expect(html.indexOf("9 октября 2026")).toBeGreaterThan(-1); + expect(html.indexOf("9 октября 2026")).toBeLessThan(html.indexOf("1 октября 2026")); + }); +}); diff --git a/frontend/src/widgets/assessment-history/ui/assessment-history.tsx b/frontend/src/widgets/assessment-history/ui/assessment-history.tsx new file mode 100644 index 0000000..aa8acfe --- /dev/null +++ b/frontend/src/widgets/assessment-history/ui/assessment-history.tsx @@ -0,0 +1,141 @@ +import { useEffect, useRef, useState } from "react"; +import type { QueryClient } from "@tanstack/react-query"; +import type { Session } from "../../../shared/api/schemas"; +import { paths } from "../../../shared/config/paths"; +import { + Button, + ButtonLink, + EmptyState, + ErrorState, + ForbiddenState, + LoadingState, +} from "../../../shared/ui"; +import { + isAssessmentAccessLoss, + isAssessmentSessionEnded, + removeAssessmentQueries, + useAssessmentResultHistory, +} from "../../../entities/assessment"; +import { AssessmentHistoryList } from "./assessment-history-list"; +import styles from "./assessment-history.module.css"; + +type AssessmentHistoryProps = { + actor: Session; + queryClient: QueryClient; +}; + +/** + * Immutable real results of the signed-in candidate. The list is read for + * the current session only. A lost session removes the cached rows; a 403 or + * 404 shows no data but leaves other cached answers alone. A failed + * background refresh keeps the rows that were already loaded. Express runs + * are not part of the history. + */ +export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps) { + const history = useAssessmentResultHistory({ actor, queryClient }); + const accessLost = history.isError && isAssessmentAccessLoss(history.error); + const sessionEnded = history.isError && isAssessmentSessionEnded(history.error); + const listRef = useRef(null); + const focusFrom = useRef(null); + const [announcement, setAnnouncement] = useState(""); + const itemCount = history.data?.pages.reduce((total, page) => total + page.items.length, 0) ?? 0; + + useEffect(() => { + if (sessionEnded) removeAssessmentQueries(queryClient); + }, [sessionEnded, queryClient]); + + // After "Show more" the focus moves to the first new row, so the keyboard + // position is not lost when the button disappears or moves down. + useEffect(() => { + const from = focusFrom.current; + if (from === null || itemCount <= from) return; + focusFrom.current = null; + listRef.current?.querySelectorAll("li a")[from]?.focus(); + }, [itemCount]); + + async function loadMore() { + const before = itemCount; + focusFrom.current = before; + const result = await history.fetchNextPage(); + if (result.isError || !result.data) { + focusFrom.current = null; + return; + } + const total = result.data.pages.reduce((sum, page) => sum + page.items.length, 0); + setAnnouncement(`Загружено еще результатов: ${total - before}. Всего: ${total}.`); + } + + if (accessLost) { + return ( + Перейти ко входу} + /> + ); + } + if (history.isPending) return ; + if (history.isError && !history.data) { + return ( + void history.refetch()} + title="Не удалось загрузить историю результатов" + /> + ); + } + + const items = history.data?.pages.flatMap((page) => page.items) ?? []; + if (items.length === 0) { + return ( + К проверкам} + /> + ); + } + + return ( +
+

+ В истории только завершенные реальные проверки. Демонстрационные запуски сюда не попадают и + категорию не меняют. +

+ {history.isRefetchError && !history.isFetchNextPageError ? ( + void history.refetch()} + title="Не удалось обновить историю. Показаны ранее загруженные результаты." + /> + ) : null} + +

+ {announcement} +

+ {history.isFetchNextPageError ? ( + void loadMore()} + /> + ) : history.hasNextPage ? ( + + ) : null} +
+ ); +} diff --git a/frontend/src/widgets/candidate-next-step/index.ts b/frontend/src/widgets/candidate-next-step/index.ts new file mode 100644 index 0000000..3db2879 --- /dev/null +++ b/frontend/src/widgets/candidate-next-step/index.ts @@ -0,0 +1 @@ +export { CandidateNextStep } from "./ui/candidate-next-step"; diff --git a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css new file mode 100644 index 0000000..0ecedbd --- /dev/null +++ b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.module.css @@ -0,0 +1,126 @@ +.root { + display: grid; + gap: var(--space-6); +} + +/* The next step is the one dominant block of the home screen. */ +.card { + display: grid; + gap: var(--space-3); + padding: var(--space-5); + border: var(--line-strong) solid var(--color-border-strong); + border-radius: var(--radius-l); + background: var(--color-surface); +} + +.card-eyebrow { + color: var(--color-accent); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-bold); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.card-title { + font-size: var(--font-size-xl); + font-weight: var(--font-weight-bold); + line-height: var(--line-height-snug); +} + +.card-text { + max-width: 44rem; + font-size: var(--font-size-m); + line-height: var(--line-height-body); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + padding-top: var(--space-2); +} + +.note { + max-width: 44rem; + color: var(--color-text-secondary); + font-size: var(--font-size-s); + line-height: var(--line-height-body); +} + +.columns { + display: grid; + gap: var(--space-6); +} + +@media (width >= 64rem) { + .columns { + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; + } +} + +.standings, +.links { + display: grid; + gap: var(--space-3); + margin: 0; + padding: 0; + list-style: none; +} + +.standing, +.link { + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.standing-title { + margin-bottom: var(--space-3); + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); +} + +.facts { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--space-1) var(--space-4); + margin: 0; +} + +@media (width >= 48rem) { + .facts { + grid-template-columns: minmax(9rem, auto) minmax(0, 1fr); + align-items: center; + } +} + +.facts dt { + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.facts dd { + min-width: 0; + margin: 0 0 var(--space-2); + overflow-wrap: anywhere; +} + +.link { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: center; + justify-content: space-between; +} + +.link-label { + font-weight: var(--font-weight-bold); +} + +.link-status { + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} diff --git a/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx new file mode 100644 index 0000000..fd24eaa --- /dev/null +++ b/frontend/src/widgets/candidate-next-step/ui/candidate-next-step.tsx @@ -0,0 +1,300 @@ +import type { ReactNode } from "react"; +import { + onboardingStepLabels, + useCandidateJourney, + type CandidateJourney, + type CandidateNextStep as NextStep, + type SpecializationStanding, +} from "../../../entities/candidate"; +import { gradeLabels, specializationLabels } from "../../../entities/assessment"; +import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity"; +import { paths } from "../../../shared/config"; +import { + ButtonLink, + EmptyState, + ErrorState, + ForbiddenState, + isAccessDenied, + LoadingState, + Section, + TextLink, + TrustLevel, +} from "../../../shared/ui"; +import styles from "./candidate-next-step.module.css"; + +type StepView = { + title: string; + description: ReactNode; + action: { label: string; to: string }; + secondary?: { label: string; to: string }; + /** True while the optional FSP link is worth mentioning. */ + mentionsOptionalFsp: boolean; +}; + +function standingLabel(standing: SpecializationStanding): string { + return `${specializationLabels[standing.specialization]}, ${ + standing.declaredGrade ? gradeLabels[standing.declaredGrade] : "уровень не указан" + }`; +} + +function describeNextStep(journey: CandidateJourney, step: NextStep): StepView { + switch (step.kind) { + case "profile": + return { + title: "Заполните профиль", + description: + "Профиль еще не сохранен. Его можно заполнить вручную, без резюме и без привязки аккаунта ФСП.", + action: { label: "Заполнить профиль", to: paths.candidate.profile }, + mentionsOptionalFsp: true, + }; + case "questionnaire": + return { + title: "Заполните анкету", + description: + "Укажите специализацию и уровень, на который вы претендуете. Это самооценка: подтвержденную категорию присваивает только тест.", + action: { label: "Заполнить анкету", to: paths.candidate.questionnaire }, + mentionsOptionalFsp: true, + }; + case "assessment": { + const declared = journey.standings.map(standingLabel).join("; "); + const canStart = journey.standings.some((standing) => standing.canStartAttempt); + return { + title: "Подтвердите уровень тестом", + description: ( + <> + Заявлено: {declared}. Заявленный уровень не считается категорией, пока его не подтвердит + тест.{" "} + {canStart + ? "Тест можно начать сейчас." + : "Сейчас ни один уровень не открыт для начала; на странице теста указано, что мешает и когда это изменится."} + + ), + action: { label: "Перейти к тесту", to: paths.candidate.assessment }, + mentionsOptionalFsp: true, + }; + } + case "resume_attempt": + return { + title: "Продолжите тест", + description: `Есть незавершенная попытка: ${specializationLabels[step.specialization]}. Ответы хранятся на сервере.`, + action: { + label: "Продолжить попытку", + to: paths.candidate.assessmentAttempt(step.attemptId), + }, + mentionsOptionalFsp: true, + }; + case "result": + return { + title: "Категория получена", + description: `Подтверждено тестом: ${journey.confirmed + .flatMap((standing) => + standing.confirmedGrade + ? [ + `${specializationLabels[standing.specialization]}, ${gradeLabels[standing.confirmedGrade]}`, + ] + : [], + ) + .join("; ")}. Посмотрите результат и решите, кому видна ваша карточка.`, + action: { label: "Открыть результат", to: paths.candidate.results }, + secondary: { label: "Настроить видимость", to: paths.candidate.privacy }, + mentionsOptionalFsp: false, + }; + } +} + +function NextStepCard({ journey }: { journey: CandidateJourney }) { + const view = describeNextStep(journey, journey.nextStep); + return ( +
+

Следующий шаг

+

+ {view.title} +

+

{view.description}

+
+ {view.action.label} + {view.secondary ? ( + + {view.secondary.label} + + ) : null} +
+

+ Сохраненный шаг аккаунта: {onboardingStepLabels[journey.savedStep]}. + {view.mentionsOptionalFsp + ? " Привязка ФСП ID необязательна: путь до категории проходит через анкету и тест." + : null} +

+
+ ); +} + +function Standings({ journey }: { journey: CandidateJourney }) { + return ( +
+ {journey.standings.length === 0 ? ( + Заполнить анкету} + /> + ) : ( +
    + {journey.standings.map((standing) => ( +
  • +

    + {specializationLabels[standing.specialization]} +

    +
    +
    Заявлено (самооценка)
    +
    + +
    +
    Подтвержденная категория
    +
    + {standing.confirmedGrade ? ( + + ) : ( + + )} +
    +
    +
  • + ))} +
+ )} +
+ ); +} + +type SectionLink = { label: string; status: string; to: string | null; linkLabel: string }; + +function sectionLinks(journey: CandidateJourney): SectionLink[] { + const hasConfirmed = journey.confirmed.length > 0; + const hasActiveAttempt = journey.standings.some((standing) => standing.activeAttemptId !== null); + const testStatus = !journey.questionnaireSaved + ? "Откроется после анкеты" + : hasConfirmed + ? "Есть подтвержденная категория" + : hasActiveAttempt + ? "Есть незавершенная попытка" + : "Еще не пройден"; + + return [ + { + label: "Профиль", + status: journey.profileSaved ? "Сохранен" : "Не заполнен", + to: paths.candidate.profile, + linkLabel: journey.profileSaved ? "Открыть профиль" : "Заполнить профиль", + }, + { + label: "Анкета", + status: journey.questionnaireSaved ? "Сохранена" : "Не заполнена", + to: paths.candidate.questionnaire, + linkLabel: journey.questionnaireSaved ? "Открыть анкету" : "Заполнить анкету", + }, + { + label: "Тест", + status: testStatus, + to: journey.questionnaireSaved ? paths.candidate.assessment : null, + linkLabel: "Перейти к тесту", + }, + { + label: "Результаты", + status: hasConfirmed ? "Есть категория" : "Появятся после теста", + to: paths.candidate.results, + linkLabel: "Результаты и история", + }, + { + label: "Приватность", + status: "Согласия, видимость карточки, статус поиска", + to: paths.candidate.privacy, + linkLabel: "Открыть настройки", + }, + { + label: "Поддержка", + status: "Обращения и запрос ручной оценки", + to: paths.candidate.supportCases, + linkLabel: "Открыть обращения", + }, + ]; +} + +function AvailableActions({ journey }: { journey: CandidateJourney }) { + return ( +
+
    + {sectionLinks(journey).map((item) => ( +
  • +
    +

    {item.label}

    +

    {item.status}

    +
    + {item.to ? {item.linkLabel} : null} +
  • + ))} +
+
+ ); +} + +/** + * The main block of the candidate home: the next step, the declared and the + * confirmed level side by side, and links to the available actions. Everything + * comes from one read of the profile, the questionnaire, and the assessment + * availability; a failed read shows an error instead of a guessed step. + */ +export function CandidateNextStep() { + const session = useGetCurrentSession(); + const state = useCandidateJourney(session.data); + + if (session.isError) { + if (isAccessDenied(session.error)) return ; + return ( + void session.refetch()} + title="Не удалось проверить вход" + /> + ); + } + if (state.status === "pending") { + return ; + } + if (state.status === "error") { + if (isAccessDenied(state.error)) return ; + return ( + + ); + } + + return ( +
+ +
+ + +
+
+ ); +}