feat(frontend): complete candidate flow and public pages

This commit is contained in:
TakuyaYagam1 committed 2026-10-11 22:37:07 +03:00
1 parent a69b1a79bb
commit e4be4a3956
63 files changed
+1903 -746

No files matched your search

+38 -283
View File
@@ -2,304 +2,59 @@
[Русский](README.md) | English
A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API. Candidate search, the employer's read of an anonymous card, and sending an invitation from a search result use the API. The candidate reads incoming invitations, accepts them with a choice of contacts, and declines them. The owner of a company sees the list of its invitations with their states.
A React and TypeScript SPA for candidates and employers. Vite builds static files; Nginx serves them and proxies `/api/` to the backend. The application uses React Router, TanStack Query, Zod, and CSS Modules.
- `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page.
- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, candidate search, the invitation to a candidate, the company's invitation list, the candidate's incoming invitations, support cases, and technical status.
- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, the result history widget `assessment-history`, the search result widget `match-list`, the invitation preview `invitation-preview`, and the technical `system-status` widget.
- `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)), `company`, and `invitation`; `src/features/` holds user actions and forms.
- `src/shared/ui/` holds design tokens, fonts, the wordmark, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks.
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)).
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
- `e2e/` holds Playwright specs and `playwright.config.ts` configures them; they run only against a Compose stack.
## Structure
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
The code follows Feature-Sliced Design:
## Routes
| Directory in `src/` | Purpose |
| ------------------- | ---------------------------------------- |
| `app/` | Routing, providers, and global styles |
| `pages/` | Cabinet and public pages |
| `widgets/` | Larger interface blocks |
| `features/` | User actions |
| `entities/` | Domain models and their UI |
| `shared/` | API, UI components, and shared utilities |
| Group | Paths | Shell |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` |
| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` |
Imports go down the layers through slice public entry points. ESLint and `test:fsd` enforce the boundaries.
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.
## UI composition
`/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it.
Public legal pages live at `/terms` and `/privacy` inside `PublicShell`; private settings remain at `/candidate/privacy`. Shared `Page`, `Button`, `LabelValue`, and `ListRow` compose page headings, actions, and list rows. `Button` and `ButtonLink` support `default` and `small` sizes; confirmed categories reuse `Tag` with the `grade` tone. Palette, typography, spacing, and contrast guidance live in `shared/ui/theme/tokens.css`, applied by components through CSS Modules. Search and invitation screens display an opaque handle as `LX-...` while retaining its original value for API requests.
## Server data
## Run
Generated Orval hooks call the shared same-origin `apiRequest` client, so the `QueryClient` has no default query function. Defaults in `app/providers/query-client.ts`:
[.node-version](.node-version) declares Node.js; [package.json](package.json) declares pnpm. From the repository root:
- retries: up to two, only for no response (status 0) and 5xx except 501; 4xx and `invalid_response` fail at once;
- `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query;
- automatic mutation retries are disabled; company creation retries through an explicit action with the same body and `Idempotency-Key`.
```sh
make -C frontend install
make -C frontend dev
```
## Candidate profile
Vite proxies `/api` to `http://127.0.0.1:8080`. Start the backend separately. For the complete cookie and Origin flow, use [Compose](../docs/en/DEPLOYMENT.md): the public address must match `APP_PUBLIC_URL`.
`entities/candidate` holds the complete profile draft model and converts it to `CandidateProfileUpdate`. `features/edit-profile` owns the fields and saving, while `pages/profile` owns the page. Server data stays in React Query; contacts and drafts are not written to localStorage or sessionStorage.
## API and generation
The form goes in steps (`Stepper`): contacts, roles with the self-assessment and the confirmed categories, experience with the confirmation of parallel periods, projects, skills, terms, and review with saving. The server takes the whole profile with `expected_version`, so saving exists on the last step only. "Далее" validates the fields of the current step; a client or server error on save opens the step that owns the field. Inactive steps stay mounted with the hidden attribute: "Назад" keeps what was entered, and the links of fields to their hints and errors remain. A step change moves the focus to the step heading. A saved profile offers "К проверке и сохранению", and the review step leads to any step with "Изменить". A reload opens the first step with the server record; an unsaved draft is not restored.
The contract lives in [api/core/](../api/core/openapi.yml). Orval uses [codegen/orval.config.ts](codegen/orval.config.ts) to generate the client, query hooks, Zod schemas, and MSW handlers into `src/shared/api/endpoints/` and `schemas/`.
The form preserves the provenance of untouched suggestions, displays overlapping employment periods, and requires explicit confirmation of parallel work. Confirmation is bound to the current indices and dates; reordering or changing periods requires another review. Confirmed categories are displayed separately and never enter the save body. A 412 version conflict preserves the draft and offers an explicit replacement with current data.
```sh
make -C frontend generate
make -C frontend check
```
After saving, the form reloads the session and shows the account step returned by the server. Saving a profile does not complete the consent step; that transition is not implemented yet. Independent profile editing works without ML, a file, or FSP.
`shared/api/client.ts` and `index.ts` are handwritten. Generation clears its output directories; do not place custom code there. MSW supports tests and does not prove backend behavior.
The "Проекты" step is optional: up to 10 projects, each with a title (one line, up to 100 characters), a description (up to 500), up to 10 technology tags (chips; a tag is added by Enter, a comma, the "Добавить" button, or leaving the field, and duplicates are dropped without regard to letter case), and an optional repository address. The client accepts only `https://github.com/<owner>/<repository>`, as the contract and the server do: a trailing slash and `.git` are removed; other hosts, ports, credentials, paths, query strings, and fragments are rejected; one repository cannot be listed twice (letter case does not matter). An empty project row is not sent; a project without a title but with other values blocks the step. A note at the top says that the title and the description can identify the candidate and that companies never receive the repository address. The `projects` list always goes whole with `expected_version`; an untouched suggestion stays `extracted`. The repository check status comes from the latest profile response (`repository_check`) and is shown as a tag and in words: "Проверяется", "Публичный репозиторий найден", "Не найден или закрыт", "Лимит GitHub, повторим позже"; an address that the server has not stored yet reads "Проверка после сохранения". While a check is `pending`, the screen reloads the profile every 4 seconds (for at most two minutes) and leaves the draft alone. The mark only means that a public repository exists; it does not prove authorship. The "Проверить снова" button calls `RequestMyRepositoryChecks` once for all saved addresses and shows the number of scheduled checks. On a 429 the button is disabled with a countdown from `Retry-After` and the `detail` text of the server; when the server names no time there is no countdown and no time is invented.
## Checks
## Candidate questionnaire
| Command from the root | Checks |
| -------------------------------------- | ---------------------------------------------- |
| `make -C frontend typecheck` | Application, configuration, and E2E types |
| `make -C frontend test` | Vitest |
| `make -C frontend check` | Formatting, lint, types, tests, FSD, and build |
| `make -C deploy test-e2e` | Playwright on a separate Compose stand |
| `make -C deploy test-e2e-registration` | Browser flows with a local mail fixture |
`pages/questionnaire` reads the specialization catalog and the current candidate's private answers through Orval. The draft stays in component state, saved answers stay in React Query, and reload restores the server record. The form offers one or two specializations, self-assessed grades, currently available task languages, stack, experience, and work formats. A specialization without a published bank is marked in development and can be saved without FSP.
E2E artifacts live in `test-results/e2e/`. Some scenarios replace API responses; distinguish display checks from complete flows using the real backend. See [TESTING.md](../docs/en/TESTING.md).
The questionnaire goes in steps: directions (one or two specializations and the assessment availability from the catalog), level and experience for each chosen specialization (self-assessment, task language, stack, experience), work format, and review with saving. The step rules are the same as in the profile: one whole save with `expected_version` on the last step, "Далее" validates the current step, a server error opens its step, steps stay mounted but hidden, the focus goes to the step heading, and a reload opens the first step.
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. That page (`/candidate/onboarding`, the "Consents" step) shows the account steps (consents, profile, questionnaire, and test) with a `Stepper`, the current step, and its action.
## 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. The express test (`demo_express`) is shown as "Экспресс-тест" (express test) 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.
The attempt screen focuses on the item: a strip above it names the attempt and shows the progress of answered items, the time left until the server deadline `expires_at` in mono (a `timer` element that is not announced every second; color and a label mark the last minute), and the save state of the answer (a polite status message). Keys 1-9 choose an option, and Enter on an option sends the answer.
The `Idempotency-Key` of the express start is kept in the tab's sessionStorage per account until the run is finished or expired, and for 24 hours at most. When a new start gets 409 `state_conflict`, the page repeats the start with the key of the active run, and the server returns the stored 201 with that attempt: an unfinished demonstration continues after a reload. The key of a start with an unknown outcome (no response, 5xx) is kept and repeated as well. Without a key (another browser, a closed tab, blocked storage), the screen explains that the demonstration ends by itself within 5 minutes of its start.
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 dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, the one-window rule, and the watermark: a faint tile with the attempt code and the time and an invisible mark in the task text). The browser also records, as weak hints only, a screenshot key (PrintScreen, Cmd+Shift+3, 4, or 5, Win+Shift+S) and a guess that the developer tools are open from the window size; the server keeps the User-Agent only as a keyed digest. The dialog says plainly that a screenshot or a phone photo cannot be prevented and that signals lead only to a manual check. This is notice text version 4; an acknowledgement of an earlier version does not count for it. The page holds the single work session of a real attempt for its own open window (`features/assessment-work-session`) and says so when another window holds it. 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.
During a real attempt, `features/assessment-signals` collects the disclosed signals: focus loss with its duration, copy, paste and cut with a size only, and fullscreen exit. The collector's listeners are passive, block nothing, and show nothing (the measures of the next paragraph are a separate feature and do not depend on it). Events go in batches (every 10 seconds, when the tab is hidden, or at 20 queued events), and each batch keeps one `Idempotency-Key` across retries. When the page is closed (`pagehide`) or the collector unmounts, what remains is sent in one last request with `keepalive`, so closing the tab does not lose the last seconds of events; the result of that request is not awaited and not retried. A network failure never affects answer submission: a failed batch is sent again with the same key and body after a growing pause and is dropped after the attempt limit. A server refusal (no C3, finished attempt) stops collection. The demonstration run collects no signals.
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.
`features/assessment-lockdown` keeps a real attempt in fullscreen and hides the task when the candidate leaves it. The click on "Start or continue" requests fullscreen: the request has to be made inside the click, before the asynchronous notice check, because the browser accepts it only with a user gesture; closing the notice without confirming leaves fullscreen again. While the work runs, the task is covered when fullscreen is exited, the tab is hidden, or the window loses focus (`fullscreenchange`, `visibilitychange`, `focus` and `blur`). The cover replaces the task instead of blurring it: the prompt, the options, and the answer controls are not rendered, so they are not in the DOM, in a screenshot of the page, or in the accessibility tree. The answer form stays mounted and renders nothing, so the draft survives (and the sessionStorage copy of the draft is still kept). The timer stays the server's and stays on screen. After leaving fullscreen the candidate continues with a button, which is the user gesture the browser needs to enter fullscreen again; leaving only the tab or the window needs no click. These exits are recorded by the collector above (`fullscreen_exit`, `focus_loss`); the cover records nothing itself. A browser without element fullscreen (iPhone Safari) or one that refuses the request gets an information notice and takes the test with the tab watch alone (`fallback` `unsupported` or `denied`), so the screen is never a dead end. The express run and a finished attempt are not protected, and leaving the page or finishing the attempt leaves fullscreen.
The same panel (`ProtectedRegion`) keeps the task text of a real attempt from being taken out. The text cannot be selected (`user-select`, with the `-webkit-` form that Safari still needs, and a cancelled `selectstart`), the context menu and drag are cancelled on it, copy and cut are cancelled when the target or the selection reaches into the panel (the clipboard text is set to an empty string), and `@media print` hides the panel with the task, the options, and the answer fields. Fields are exempt: a text field keeps selection, its own context menu, and copy and cut of the candidate's own text. Paste into answer fields is refused (the `paste` event, and `beforeinput` of the paste kind), the screen says so with a short status that goes away on the next input, and dropping text into a field is refused everywhere. The code editor of a practice item carries `data-paste="allowed"`: pasting works there and its size goes out as the existing `paste` signal. The collector sees every paste, copy, and cut, including the refused ones, because the guard cancels the default action and never stops propagation, so a refused paste is still a signal with a size. The text stays in the page for screen readers (no canvas, no image text), typing and the focus order are untouched, and the express run is not restricted. These measures stop the casual route only: a screenshot, a second device, or a browser extension still takes the task out, and a paste by an on-screen keyboard that inserts text as typing is not visible to the page.
## 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 session ends through the API, not through the account menu, because the menu reloads the page). By contract, express tests are not part of the history; their result opens from the attempt screen or by a direct URL and is captioned "Экспресс-тест без грейда" (express test without a grade).
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 captioned "Экспресс-тест без грейда" (express test without a grade), shows no category or estimate, and leads to the full assessment; a prepared full attempt appears as a separate history record. A confirmed category looks the same for every decision basis: the interface prints no demo marks and no calibration status, and the values stay in the API response.
## Privacy settings
`pages/privacy` (`/candidate/privacy`) shows separate visibility settings. No action enables another: consent, publication, search status, and hiding an organization are saved by their own requests, each with its own version and its own saving state.
- Consents (`features/consent-management`): C1-C5 are granted and revoked separately, with the text and version shown before a grant. The block of each purpose has an anchor that the "Go to the C2 consent" button moves focus to.
- Publication (`features/profile-visibility`): step 1 shows whether C2 is active from the complete active consent history; an unknown or partly loaded state is not treated as consent, and saving stays unavailable. The step button only moves focus to the C2 block and grants nothing. The card state and fields are chosen next, and the publication is saved by a separate action (`SetMyPublication`, `expected_version` in the body). A 412 conflict keeps the draft on screen and offers an explicit reload of the current settings; a failed save does not reset the draft. Revoking C2 closes the card, and a new C2 does not reopen it.
- Closure explanation: from `closed_reason` the screen says that future reads are closed at once, that a new C2 does not reopen the card by itself, and that a former company needs a new invitation and a new C4 to read contacts. The same words appear after revoking C2, hiding an organization, unhiding it, and republishing: an earlier contact access is not restored. Hiding does not change the C4 record in the consent ledger, so next to the C4 of a hidden company a note says that the record does not bring contact access back.
- Projects in the publication. The `projects` field is its own choice, "Проекты: название, описание и технологии". The warning stands under it at all times (assistive technology reads it with the checkbox) and turns into a caution once the field is chosen: the candidate writes the project texts and can be recognized by them, the size of a group of similar candidates does not hide them, and the repository address and its owner are never shown to companies, which see only the mark that a public repository was found.
- Search status (`SetMySearchStatus`) is its own request and its own text. It does not change the publication and grants no consent.
- Employer preview (`EmployerCardPreview` from `entities/candidate-view`) is built only from the `GET /me/privacy/preview` response. The preview alias is separate from organization aliases. Confirmed categories and self-assessment are shown apart; each specialization has its own "Grade confirmed" or "Grade not confirmed" status (the Russian labels are "Грейд подтвержден" and "Грейд не подтвержден"), told apart by the shape of the mark and by text, not by color. A candidate without a confirmed grade sees the declared level (or "Level not specified") and the not-confirmed status for each specialization separately; a confirmed Backend is not carried over to a network specialization. The evidence block shows the skill, grade, confirmation level, year, and basis (`synthetic_demo` is shown as "Результат теста", a test result; calibration is not shown in the interface). A closed card is shown as an empty state. The preview creates no access record and ignores organization filters.
- Projects in the preview and in the employer's card are drawn by the shared `PublishedProjects` component (`shared/ui`): the title, the description (text with line breaks), the tags, and the badge "Подтвержден публичным репозиторием" for `repository_verified`, with a note that the mark does not prove authorship. There is no address or link in the data or in the markup, and all candidate text is shown as text.
- Hiding organizations: the hide button is offered only for organizations in the candidate's own access history (the server answers 404 for the rest), and only after the list of hidden organizations is fully loaded. Unhiding does not restore contact access.
- Histories: the settings history and the card access history are paginated; a partial page is never presented as complete. An access record shows the kind of access, the time, and the organization when the server names it (otherwise "Organization is not disclosed"); it carries no employees, queries, filters, or search position. An empty history and a load error are separate states.
- A link to request a manual assessment stays below.
The employer's card read and the search are described in [Candidate search](#candidate-search). The effect of hiding or a revoked C2 on a search is not yet checked from the employer's browser: the end-to-end suite does not repeat it on the employer side.
## Company profile
`pages/company` selects a company from the paginated active memberships of the current account. Only an owner may read or edit its profile. The form keeps its draft in memory, displays the server verification level without a promotion action, and builds its preview only from `candidate_card`.
Creation uses one idempotency key for retries of the same body after a lost response. A 412 version conflict preserves the draft; the user explicitly loads current data, reviews the reapplied changes, and saves again. Background refresh does not reset the draft. A 401/403/404 response hides the profile and clears its cached query, then reloads the company directory. This complements server membership checks rather than replacing them.
## Employer needs
`/employer/needs` shows a paginated list of organizations where the current account has an active owner membership and their needs. `/employer/needs/new?organization_id=...` creates a need, and `/employer/needs/:needId?organization_id=...` edits one. A URL or cached response grants no access: the client checks the current session and owner directory, and the server checks membership for every request. Cached data is scoped to the account and organization; a response from a prior session cannot populate the new cache. A 401/403/404 removes the organization's private queries.
The editor draft stays in memory. Fields and skills extracted from the source remain suggestions with provenance until the user confirms, edits, or deletes them. Unknown values are not replaced with defaults. Readiness questions appear next to missing fields; recommendation status and categories come from the API, with no fabricated results. If a create response is uncertain, retry sends the unchanged body with the same idempotency key. A 412 conflict retains the draft, offers the latest version, and requires review of reapplied changes before another save.
The form has five steps (the `Stepper` component): role and grade, skills, tasks and domain, work conditions, and review and save (`features/edit-need/model/steps.ts`). Inactive steps stay mounted and hidden with the `hidden` attribute, so going back or forward loses no draft; focus moves to the heading of the new step. Enter in a field moves to the next step, and only the last step saves. The title is required: step 1 does not let the employer leave without it, and step 4 does not let them leave with an incomplete range. A server field error opens the step of the first one and focuses the field. Beside the form (below it under 1200 px) sits a live summary of the need: the `BACKEND · MIDDLE` tag, stack tags, the range in mono, the number of unconfirmed suggestions, and, for a saved need, the categories and versions. A saved need has a "К проверке и сохранению" button on steps 1-4. The grade and the tax basis are chosen with a segmented control (`SegmentedControl`) and the work format with checkbox chips; an unknown grade is its own "Не указан" option, not a default.
## Need entity
`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. Need pages and forms live in `pages/needs`, `pages/need-editor`, and `features/edit-need`.
- `fromTransport` builds a draft from a `Need`. Each requirement field is an explicit state: `unknown` without a value, `extracted` as a stored suggestion with its provenance and quote, and `confirmed` as a confirmed value. An unknown field never becomes an empty string, an empty list, or a default value; a skill outside the taxonomy keeps `taxonomy_code: null`. Data that breaks the rule "value and source are null exactly when unknown" is rejected with `NeedTransportError`.
- `toUpdateBody(need, draft)` sends only the fields whose request value changed, plus the `expected_version` of the read version. An untouched suggestion is not sent; when its field or list is sent for another reason, it goes with status `extracted`. A cleared field is sent as null, an emptied list as `[]`, and an untouched list is absent.
- `toCreateBody(draft)` always sends the title and leaves out unknown fields and empty lists, so the server extracts them from `source_text`.
- The edit functions (`confirmField`, `setFieldValue`, `clearField`, `confirmSkill`, `moveSkill`, and others) keep the invariants: only an untouched suggestion has status `extracted`, an edited value becomes `confirmed`, and moving a skill between lists does not confirm it.
- `validateNeedCreate` and `validateNeedUpdate` check the body with the generated Zod schemas and tie the problems to form fields. The server checks cross-field rules (the salary width, a repeated skill), and `needFormFieldOf` maps its pointer to a form field.
The tests take their fixtures from the named contract examples in `api/core/openapi.bundle.yml` and check every body with the generated `NeedCreate` and `NeedUpdate` schemas.
## Candidate search
`/employer/candidates` (`pages/matches`) searches through `POST /organizations/{org_id}/matches` (`SearchOrganizationMatches`). The server model is in the [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations) and the contract in the [API](../api/README.en.md#match-search).
- Access. Only the active owner of a company can search. The organization comes from `organization_id`, and the owner's company list is read on every visit (as on the needs page). Without the right the page shows "Нужны права владельца компании"; 401 and 403 show the forbidden state, 404 shows the error "Потребность или компания не найдены", and other failures show a message with a retry. A 429, if one arrives, shows its `Retry-After`.
- Runs only on an action. The page and a reload never search: the result lives in a component mutation and is not stored. Above the "Найти кандидатов" button the form says that a search spends card view quota: each newly shown candidate counts as one view, and a candidate already shown in the current window is not charged again. A second press is ignored while a search runs.
- Basis. "По потребности": the first 100 needs of the company, the requirements version comes from the `GET` of the need (`requirements_version`, not the general `version`), filters are added on top; the grade of the need is not a filter, and the form says so under the picker. The "Подобрать кандидатов" link on a need opens the search with that need chosen. "По всем профилям": a request with filters only, and each specialization of a candidate arrives as its own entry.
- Filters (`features/filter-matches`): specialization, confirmed grade, confirmation status, the grade the candidate declared, card technologies (all required), work format (one common format is enough), and salary expectation compatibility. The declared and the confirmed grade are separate fields with separate labels, and the hint under the declared one says it is not a confirmation. The form sends exactly the filters that are on and relaxes nothing: a contradictory pair (for example "not confirmed" with a confirmed grade) is sent as it is and gives an empty result. If the form changes after a result, a note above the result says that it is out of date; the result does not refresh by itself.
- Result (`widgets/match-list`). The heading "Результат поиска" takes focus after a search. Below it come the basis and the current filters: for a search over all profiles these are the normalized filters of the response, and for a need search the response does not repeat them, so the sent filters are shown. Then the three groups in a fixed order: "Подтвержденные", "Близкие варианты", "Грейд не подтвержден". An empty group stays with the line "В этой группе записей нет.". The `truncated` flag is explained by "Показана часть выдачи; квота просмотров или предел группы" with no number. An empty result is explained separately: the filters stay on, the ones the employer can change are listed, and nothing is relaxed automatically.
- Specializations. An entry is one candidate under one specialization, so one alias can stand in two groups (confirmed in Backend, not confirmed in Networks). When the result holds more than one specialization a view switch appears ("Все специализации", then each one): it hides the entries of the other specializations, recomputes nothing, and carries no confirmation across. The alias is shortened for display (`entities/match/model/views.ts`); the full value is used only by requests and the invitation link.
- Entry (`entities/match`). It shows the specialization, the status "Грейд подтвержден: X" or "Грейд не подтвержден" (by icon shape and text), the confirmed category with its strength on a line apart from the grade the candidate declared, the safe card context (technologies, experience, formats, expectations), and the server's explanation of sources: every `evidence_summary` row with the state "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом", or "Пробел: подтверждения нет". A `null` context value is printed as "Нет значения в карточке", because the contract does not say whether it is hidden or absent. The entry has no contact, no real identifier, and no reason why a grade is unconfirmed.
- The explanation opens with a button that carries `aria-expanded`. It is built only from the components of the response: Fit, Cov, Dom, Sem, the percentile, V, Fr, Rsp, and the final score S appear exactly as they arrived, with no rounding beyond six decimals. A neutral value (`unknown_flags`) is labelled "Нейтральное значение, не измерено" with its reason (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed`, and others). A `null` percentile is printed as "Нет значения" and no number is invented. A zero competition value is called "не штраф". An entry without a confirmed grade has only Fit and Cov: the server computes no S, percentile, or category for it, and the screen draws none. Unknowns outside the scores (experience, formats, expectations, the assessment result) are listed under "Что неизвестно" with a note that they are not an absence of ability.
- Matches by meaning (`semanticBlock` in `entities/match`). Inside "Почему в подборке" the block "Совпадения по смыслу" prints `semantic_evidence` in the order and within the limit the server sent: a row "requirement kind and text → item kind and title" (requirement: "Обязательный навык", "Желательный навык", "Задача"; item: "Проект", "Стек", "Роль") and a tag "Высокое сходство" or "Среднее сходство". A project shows its title and, when `repository_verified`, a "Публичный репозиторий" badge; the stack and the roles have no title, so they read "Технологии карточки" and "Специализации и грейды карточки" and get no badge. When there are no rows because the server names the `semantics` component unknown with the reason `ml_unavailable`, the block says "Совпадения по смыслу: смысловой анализ недоступен." in the same words as the explanation; an empty list without such a flag (a search over all profiles, no matches) shows no block. A repository address or owner cannot reach the breakdown: the adapter rejects a response with a field outside the contract.
- Opening a card. The "Открыть карточку" button reads `GET /organizations/{org_id}/candidate-cards/{handle}` and, when the card has categories, the evidence section as well; the server refuses the section for a card without categories, so the request is not sent. Reads are neither retried automatically nor cached after the panel leaves the screen (`gcTime: 0`, no refetch on focus), because every read is an entry in the candidate's access history. A closed panel stays mounted, and opening it again does not read the card again. A 429 shows "Квота просмотров карточек исчерпана" and the time from `Retry-After`; when the server named none, no time is invented. A 404 replaces every hidden case with one text and names no reason. When the candidate published projects, the card panel shows them in a "Проекты" block (title, description, tags, the badge of a verified public repository) without an address.
- Invitation. Every entry has a "Пригласить" button, an unconfirmed one included. It leads to `/employer/invitations/new` with `organization_id`, `candidate_handle`, `specialization`, and, for a need search, `need_id` (see [Invitation to a candidate](#invitation-to-a-candidate)). The alias is scoped to the organization and is not a candidate identifier.
- Layout. The form sits above the result at every width: the basis of the search (a segmented control with "По потребности" and "По всем профилям"), the selects, a row of filter chips (technologies, format, salary compatibility; an applied chip is blue with a check mark), and the action; the result takes the full width. From 768 px an entry is a content column and an action column ("Пригласить", the explanation, the card); at 360 px the actions and the facts fold into one column. The "Почему в подборке" block is set in mono on a nested surface: the sign "+" (confirmed), "+/-" (partial), "?" (declared), "-" (gap) repeats the state word. A technology chip that the search asked for carries a dot and hidden text "совпадает с условием поиска". Every action works from the keyboard, focus is visible, and status is carried by text and shape, not by color.
Checks. Unit tests cover parsing and labels (`entities/match`), the request built from a draft (`features/filter-matches`), and the result markup (`widgets/match-list`). The Playwright suite `e2e/match-search.spec.ts` has two groups. The first runs on the real backend (it needs the mail and company fixtures): five synthetic candidates publish the same card with declared Backend and Networks grades, and the owner searches and checks the groups, the Backend/Networks switch for one alias, Fit and Cov against the response, a card read, an explained empty result for an impossible filter, no repeated search after a reload, and 360 px. The second group answers from a stub and covers what the stand cannot produce: the order of three groups with a confirmed Backend and unconfirmed Networks for one alias, neutral values and reasons, `truncated`, a 429 with `Retry-After`, a 404 card, errors, rights, and a need search. Confirmed groups are not checked on the real backend: a card is served only to a group of at least five identical cards, and a confirmed category on the stand needs each of them to pass an assessment. A real exhausted quota and hiding or revoking C2 from the employer's browser are not checked either.
## Invitation to a candidate
`/employer/invitations/new` (`pages/invitation-compose`) opens from the "Пригласить" button of a search result. The candidate is named only by the alias of the entry (`candidate_handle`, shortened on screen); an address without an alias offers to go to the search. The contract is in the [API](../api/README.en.md#invitations-and-contact-grants).
- Access. As with the search, only the active owner of the company in `organization_id` can use the screen: the company list is read on every visit, and a member with another role gets no send button ("Нужны права владельца компании"). The server checks the role itself and answers 403; the form shows it as lost access.
- Form (`features/send-invitation`). The fields follow `InvitationTerms` and nothing more: the role, the specialization (from the search entry), the grade, the offer type, the tasks (one per line), the team, the technologies, the work formats and the place of work, the channel with an optional note, the range in rubles with an explicit basis (net or gross), the four package conditions, and a response period of 3, 7, or 14 days. Each package condition is chosen explicitly: "Предусмотрено" with a description or "Не предусмотрено"; nothing is preselected. For a need search the form is prefilled only with the confirmed requirements of the need, and the draft refers to its `requirements_version`.
- Checks before a request. The client repeats the contract rules: required fields and lengths, a range in whole rubles with a step of 1000, a lower bound below the upper one, and a width from 10% to 40% of the midpoint (`entities/invitation/model/salary-range.ts`), a place of work for office and hybrid, and a technology repeated in another letter case. With an incomplete range, no communication method, or an unanswered package condition nothing is sent. Issues are listed in a focused summary at the top of the form and bound to their fields with `aria-invalid` and `aria-describedby`.
- The server decides. RFC 9457 errors from `errors[].pointer` are mapped to form fields (`fieldOfPointer`, for example `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); server text is not shown. `/candidate_handle` and `/need` give a general message without the reason.
- Steps. The form runs in four steps (`Stepper`): terms, package and response period, preview, send. "Далее" on the first step checks only its fields; "К предпросмотру" checks the whole form. An error opens the step of the first field in trouble and focuses the issue list above the step. The offer type, the grade, the tax basis, the package conditions, and the response period are segmented controls, and the work format is chips. Enter in a field moves to the next step, and only the last step sends.
- Preview (`widgets/invitation-preview`). "К предпросмотру" checks the form and shows the company card from `candidate_card` (`GET /organizations/{org_id}`) and every term as the candidate will see them; focus moves to the heading of the step. The preview is rebuilt each time the step opens, sends nothing, and creates no draft.
- Sending. "Отправить приглашение" runs a command of three operations (`features/send-invitation/model/send-command.ts`): `CreateOrganizationInvitation` with an Idempotency-Key, `UpdateOrganizationInvitation` with `expected_version` when the terms of a saved draft changed, then `SendOrganizationInvitation` with its own Idempotency-Key. The create key is bound to the request body and the send key to the draft and its version; both are kept until the command completes, so a click after a lost response, a 5xx, or 409 `idempotency_in_progress` repeats the same key. A click while the command runs starts nothing. After 412 the form reads the draft again and applies its terms on the next send. Responses are checked with the generated Zod schema.
- Result. After a successful send the screen shows the state "Доставлено", the delivery moment and the response deadline from the server response (`response_deadline_at`, in UTC), the terms version, the salary indicator, and the sent terms; focus moves to the heading. Once a draft exists its `invitation_id` is written to the address: a reload reopens an unsent draft for sending or a sent invitation with its stored deadline.
Checks. Unit tests cover the range rules (`entities/invitation`), draft validation and pointer mapping, the send command over MSW (keys, a retry after a lost create and a lost send response, 400 with fields, a draft update, 412), and the preview and page markup (owner access, an empty address). The Playwright suite `e2e/invitation-compose.spec.ts` runs on the real backend in `make -C deploy test-e2e-registration`: five synthetic candidates publish the same card, the owner finds them with a search, opens the invitation from the result, fills [100000; 140000] net and a package step by step, and checks the preview against every term; without the communication method the form does not leave the terms step, a field error shows, no request is sent, and the candidates' inboxes stay empty. Then the send is slowed down and its first response lost, a second click during the request starts nothing, and the retry uses the same key; the result is one invitation in one inbox (`GET /me/invitations`) with the deadline the screen shows, also after a reload. A 403 for a recruiter is not checked in the browser, since the stand cannot grant that role; the screen for a non-owner role is covered by a unit test.
## Company invitations
`/employer/invitations` (`pages/employer-invitations`) shows the company's invitations from `GET /organizations/{org_id}/invitations`: drafts and sent ones, newest first, in cursor pages ("Показать еще"). The company comes from `organization_id` in the address, otherwise the first company where the account is the owner; with several companies a picker sits above the list. Owner rights are checked against the current organization directory, and other roles are refused.
- Row. The heading is the role title; the state tag names the state in words and its tone repeats the meaning (draft is neutral, waiting for an answer is accented, accepted is a success, declined, expired, and withdrawn are danger). Below: the candidate only as the shortened alias (`entities/match/model/views.ts`), the salary range, the basis (a need with its requirements version or a direct invitation), the creation and last change dates, the response deadline, and the contact access (the contact kinds while `available`, "Доступ закрыт" while `closed`). The list response holds no name or contact value, and the screen shows none.
- Dates. The list summary has no delivery moment, so the screen shows creation and the last change, both in UTC through `formatServerMoment`.
- Filter. A `SegmentedControl` with "Все", "Ожидают ответа", "Приняты", "Закрыты", and "Черновики" works on the client over the loaded pages, because the API has no state filter yet (`entities/invitation/model/list-groups.ts`: every state of the contract belongs to exactly one group). When no loaded item is in a group but more pages remain, the screen does not claim the group is empty and offers to load the next pages.
- Links. A draft and a sent invitation open the same route `/employer/invitations/new` with `organization_id`, `candidate_handle`, and `invitation_id`: for a draft it opens the form with the saved terms, for a sent one the state, the deadline, the terms, and, after an acceptance, the contacts. The company has no separate invitation page.
- States. Loading (message and skeleton), an empty list with a link to "Кандидаты", an error with retry, a 401/403 or 404 refusal without retry, and a refresh error above an already loaded list.
Checks. Unit tests: state groups and tones, the list adapter on MSW (page size, cursor, contract check, a 403 refusal), the list markup (every state with its tone, the filter, empty states, draft and sent links, no contact values), and the page (loading, empty, error with retry, refusal, another company). The Playwright spec `e2e/acceptance-path.spec.ts` opens the owner's screen after three invitations are sent and checks three delivered invitations without candidate contacts.
## Candidate incoming invitations
`/candidate/invitations` (`pages/candidate-invitations`) shows the incoming invitations: a cursor-paged list from `GET /me/invitations`, newest first, which records no view. `/candidate/invitations/:invitationId` opens one invitation. The contract is in the [API](../api/README.en.md#invitations-and-contact-grants).
- Reading and viewing. The screen reads the invitation with `GET /me/invitations/{id}` and records the view once per opening (`POST .../view` with the CSRF token, without an Idempotency-Key). Reading changes nothing; the view moves `delivered` to `viewed` and keeps the deadline. A view answer replaces the shown invitation only when its version is newer.
- Terms. The company, the role, the tasks, the team, the technologies, the format and place of work, the salary range with its basis (net or gross), the package, and the communication method are shown as in the company's preview (`widgets/invitation-preview`, the shared `InvitationTermsArticle`). The response deadline is shown with a UTC label (`formatServerMoment`). The candidate sees no company card: the contract returns only the name.
- Deadline. Whether an answer is open depends on the invitation state and the server clock (`useServerNow`, corrected by the `Date` header). After the deadline the answers are closed, even before the server applies the expiry on a later read.
- Acceptance with C4 (`features/accept-contact-consent`). The contact kinds come from `contact_consent.available_fields`: full name, email, phone, and Telegram, as far as the profile holds them. Nothing is preselected, and each kind is chosen separately. The button becomes available after at least one kind and a separate confirmation of the text are chosen. The consent text is shown as plain text, unchanged, with its paragraphs from the server response. Without a contact in the profile the invitation cannot be accepted, and the screen offers to open the profile.
- Decline (`features/respond-invitation`). A reason is chosen explicitly; none is preselected. The comment is optional for every reason, including "Другая причина", up to 500 characters. Only the candidate reads the comment.
- Outdated terms. A 412 `version_conflict` (and a 409 with the same code) reads the invitation again: the new version of the terms is shown, the choice of contacts and the confirmation are reset, and the screen asks for a new confirmation. A 409 `state_conflict` shows the final state instead of a retry. A repeated answer after a lost response or a 5xx uses the same Idempotency-Key (`entities/invitation/model/command-key.ts`); a changed choice gets a new key.
- Outcome. After acceptance the screen shows only the contact kinds that the grant covers (`contact_grant.fields`) and whether the company can read them now: with `readable` false and the reason `visibility`, it explains that the card must be published and open to the company. After a decline it shows the reason and the candidate's own comment. The company gets contacts only through its own endpoint, and only the kinds of the grant.
Checks. Unit tests cover the deadline and view rules, the classification of answer errors (`entities/invitation/model/response-failure.ts`), the idempotency keys, the form draft states, and the adapters and answer commands over MSW (CSRF and Idempotency-Key headers, schema checks of the response, a retry after a lost response), and the markup of the list, the screen, the forms, and the terms block. The Playwright suite `e2e/candidate-invitations.spec.ts` runs on the real backend in `make -C deploy test-e2e-registration`: five synthetic candidates publish a card, the owner finds them with a search, and three invitations are sent through the API. At 360 px a candidate accepts with the email only: the candidate's API shows one grant, and the company's contact endpoint returns the email and no phone. Outdated terms are checked with an intercepted response: the backend does not implement the raise of the upper salary bound after sending (`RaiseOrganizationInvitationSalary`), so the 412 and the new version of the terms come from a route, while the absence of a grant is checked on the real backend. A decline with "Другая причина" and no comment, followed by a reload, is checked on the real backend: the `declined` state stays after the reload, and the company's contact endpoint answers 404.
## Support and manual assessment
`/candidate/support/cases` and `/employer/support/cases` show each account's paginated support history. Their `.../new` routes create a case and `.../:caseId` routes show its status and history. The public `/support` route directs a signed-in user to their cabinet. The form draft stays in memory, and a retry of an unchanged request reuses its idempotency key. Support history is scoped to the current account and cleared when the session changes or the server denies access.
Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The hint under the specialization and grade selectors uses the published grades from the catalog but does not promise a rubric: the server pins the version on submission. The case page displays the status and rubric version returned by the server and, for `null`, says plainly that no published rubric existed when the request was made; the client does not create an outcome. After a page reload the form loses its idempotency key, and a repeated submission while a manual assessment of the same specialization is open receives 409; the page explains this and links to "My cases" without creating a second request.
## Notifications
`features/notifications` shows the inbox of the signed-in account at `/candidate/notifications` and `/employer/notifications`, and each shell links to it. `NotificationInbox` takes a scope: the candidate cabinet, or one organization. `OrganizationNotificationInbox` chooses the organization from the active memberships of the account (the `organization_id` parameter keeps the choice across reloads) and renders the inbox. The list is read on every visit and window focus and is never kept (`gcTime: 0`); the cached pages are keyed by account and cabinet and dropped when the account or the session changes or when the server refuses access.
The server resolves the text of every item from its current source. An item without content stays in the list with a generic line, and the client never shows an earlier copy. The read state is a word ("Не прочитано" or "Прочитано"), not only a style. "Отметить прочитанным" is a native button, sends the CSRF token of the session (read at call time; after a 403 it reads the session again and retries once, and only a 401 or 404 counts as lost access), and moves focus to the heading of the item after it succeeds, with a polite status message. A content link opens only if it is a same-origin path inside the cabinet that shows it. States: loading, empty, error with retry, forbidden (including a membership that ended), and "Показать еще" for the next page. Component tests render markup in Node; the keyboard path and the delivery of a real event are checked by `frontend/e2e/notifications.spec.ts`.
## API client generation
`make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values.
`fakeFromPattern` parses a regular expression subset (characters, escapes, classes, groups, alternatives, quantifiers, and `^` and `$` at the ends), picks a length within the pattern and the bounds, and builds the string with the faker generator, so the same seed gives the same data. Every value is checked with `new RegExp(pattern, "u")` and the length bounds; a pattern outside the subset (for example, a lookahead or a back reference) or unreachable bounds throw an error.
`src/shared/api/mock-validity.test.ts` calls every `get*ResponseMock` factory in `endpoints/*/*.msw.ts` with 25 faker seeds and checks the result with the generated Zod response schema. Orval's Zod schemas do not check `uniqueItems`, so the test does not cover that constraint; the response arrays with `uniqueItems` currently hold enum values, and the mock picks them with `faker.helpers.arrayElements` without repeats.
## Tokens and theme
Tokens live in `shared/ui/theme/tokens.css`: palette, semantic colors, type scale, spacing in 4px steps, radii, lines, focus ring, content widths, header height, and motion. The values come from the graphite system in `docs/other/design/DESIGN.md`, except the FSP brand mark: the product is Lincodex. Breakpoints are fixed in media queries: 360px minimum, phone layout below 700px (`43.75rem`), 768px tablet (`48rem`), 1024px desktop navigation (`64rem`), and 1280px verified wide layout.
One dark theme ships, and it is the default (`color-scheme: dark`). The canvas is `#1B1C21`, cards and fields are `#202129`, elevated surfaces are `#2D2E37`, boundaries are 1px hairlines, and only popover menus have a shadow. The single action color is blue `#402FFF` on primary buttons; on hover the button inverts to `#EDEDED` with blue text. Text, links, the focus ring, and selected markers use the readable accent `#9A92FF`: `#402FFF` itself reaches only 2.49 on graphite. Red `#EC1D35` is used only for 6-8px dots, error text is `#FF5A6A`, and success is `#3CCF7E`. The current section, the selected tab, and the current step are shown by inversion: a light capsule with graphite text. Every button, field, tab, and tag is a capsule; cards have a 24px radius, panels 32px, surfaces nested in a card 16px, and small objects 6px.
`app/ui/styles.css` sets the base: headings use JetBrains Mono, paragraphs and meta use Inter. Native inputs and selects get the dark capsule and padding from element rules with specificity (0,1,2): above a module rule such as `.field input`, below a state rule such as `.field input[aria-invalid]`. Field borders stay in the screen modules and use `--color-border-strong`.
WCAG 2.2 contrast of the pairs in use:
| Foreground | Background | Ratio | Use |
| ---------- | ---------- | ----- | ----------------------------------------------------------- |
| #EDEDED | #1B1C21 | 14.53 | Text on the canvas |
| #EDEDED | #202129 | 13.68 | Text on cards, fields, and the header |
| #EDEDED | #2D2E37 | 11.52 | Secondary button, menus |
| #FFFFFF | #1B1C21 | 17.01 | Headings on the canvas |
| #FFFFFF | #202129 | 16.02 | Card titles, salary |
| #FFFFFF | #414246 | 10.04 | Secondary button on hover |
| #9B9C9E | #1B1C21 | 6.19 | Secondary text, meta |
| #9B9C9E | #202129 | 5.83 | Secondary text on cards |
| #9B9C9E | #2D2E37 | 4.91 | Secondary text on the elevated surface |
| #878994 | #1B1C21 | 4.89 | Hints and placeholders |
| #878994 | #202129 | 4.60 | Field placeholders |
| #9A92FF | #1B1C21 | 6.42 | Links, accent labels, focus ring |
| #9A92FF | #202129 | 6.05 | Links and focus ring on cards |
| #9A92FF | #2D2E37 | 5.09 | Links and focus in menus |
| #FFFFFF | #402FFF | 6.84 | Primary button, skip link |
| #FFFFFF | #3324E0 | 8.50 | Primary button when pressed |
| #402FFF | #EDEDED | 5.85 | Primary button on hover (inversion) |
| #1B1C21 | #EDEDED | 14.53 | Current section, selected tab, current step |
| #1B1C21 | #9A92FF | 6.42 | Completed step, text selection |
| #FF5A6A | #1B1C21 | 5.61 | Error text |
| #FF5A6A | #202129 | 5.28 | Error text on cards |
| #FF5A6A | #30212A | 5.03 | Text in the error box (8% red over #202129) |
| #9B9C9E | #30212A | 5.55 | Description in the error box |
| #FF5A6A | #41202B | 4.72 | Error tag (16% red over #202129) |
| #3CCF7E | #1B1C21 | 8.44 | Success: saved, confirmed |
| #3CCF7E | #243935 | 6.09 | Success tag (14% green over #202129) |
| #9A92FF | #262450 | 5.47 | Accent tag (18% blue over #202129) |
| #9B9C9E | #2C2D35 | 4.98 | Neutral tag (6% paper over #202129) |
| #EDEDED | #34353D | 10.41 | Stack tag (10% paper over #202129) |
| #EDEDED | #1F2028 | 13.85 | Text on the glass header (88% #202129 over the canvas) |
| #73757F | #1B1C21 | 3.71 | Field and control boundary (needs 3:1) |
| #73757F | #202129 | 3.49 | Field boundary on cards (needs 3:1) |
| #1B1C21 | #FF5A6A | 5.61 | Glyph inside the error mark (graphic) |
| #EC1D35 | #1B1C21 | 3.88 | Red "new" or "live" dot (graphic, meaning repeated in text) |
Excluded pairs: `#402FFF` is not used as text or as a boundary on graphite (2.49 on `#1B1C21`); `#878994` and `#FF5A6A` are not used on `#2D2E37` (3.88 and 4.44); the `#2D2E37` hairline on the canvas (1.26) is decorative only and is never the only boundary of a control.
## Fonts and wordmark
All fonts are self-hosted (`font-src 'self'`) under the SIL Open Font License 1.1; licenses, authors, sources, and character ranges are in `shared/ui/theme/fonts/` (`SOURCES.txt`). The files are subsets made with fontTools:
- JetBrains Mono 2.304 from the brandbook archive, variable weight 400-700: headings, navigation, buttons, labels, numbers, grades, stack, codes; `Mono` adds tabular figures.
- Inter 4.001 from the Google Fonts repository, variable weight 400-700, Latin and Cyrillic: paragraphs, meta, form fields.
- Unbounded 1.701 from the Google Fonts repository, Latin only, used only for the wordmark. The wide geometric face sets the name apart from interface text, which is set in mono and Inter.
The interface has no FSP logo. `Wordmark` is the text mark "Lincodex" with a terminal caret in the action color; the link's accessible name is exactly "Lincodex", the caret is decorative, and the cabinet name sits next to the link. The tab icon `public/favicon.svg` is an L with a caret on a blue square.
## Shared components
- `Page`, `Section`, `Stack`: page layout; `Page` owns the only `h1` and the document title. `Section` hangs on a circuit trace: a node at the heading and a line down the section.
- `Button`, `ButtonLink` (variants `primary`, `secondary`, `quiet`), `TextLink`, `NavItem`: controls with text labels; `NavItem` marks the active section with `aria-current` and an inverted capsule; a shell can state the current state itself (`current`) for a section that stays active on the routes of its sub-sections.
- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark`: the shell header: a floating glass plate, a menu button with `aria-expanded` (the menu closes after a navigation and on Escape, and focus returns to the button; with `dismissOutside` it also closes on a press or focus outside it), and the wordmark.
- `Card` (`raised`, `inset`, `panel`), `Tag` (`neutral`, `grade`, `stack`, `accent`, `success`, `danger`), `AttentionDot`, `Notice`: containers, tags, and messages. The meaning is always given in text; color only repeats it.
- `Stepper` and `buildSteps`: progress through a multi-step flow: a "Шаг N из M" line and a list with `aria-current="step"` and a text status for each step.
- `Tabs` (WAI-ARIA tabs pattern, arrow keys, Home and End; inactive panels stay mounted with the hidden attribute, so form state survives) and `SegmentedControl` (a native radio group drawn as capsules). `SectionSwitch` is a sub-section switch drawn as capsules but made of links to routes: it has no panels, so tabs do not fit.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus`: screen states. Each state has its own shape and text; the empty state draws a circuit trace that ends at an open node. `ErrorState` shows the code, status, server text, and request ID as plain text and offers a retry. `Skeleton`: decorative placeholder lines while loading, always next to a loading message.
- `QueryView`: maps a query result to loading, error, forbidden (401 and 403 without retry), empty, or data.
- `describeError`: the Russian text of an error by problem code, and by HTTP status for an unknown code. The `service_unavailable` code (503, for example while a model loads) reads "Сервис пока не готов" with advice to retry in a minute; the server text stays only as a technical detail.
- `PublishedProjects`: the projects a candidate published on the anonymous card: the title, the description, the tags, and the badge "Подтвержден публичным репозиторием". It is a purely presentational component with no repository address; the candidate's text is shown as text, never as markup.
- `TrustLevel`: an empty mark, ring, partial fill, or full mark with a visible label.
- `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`.
The steps of a long form (`form-steps.tsx`, `use-form-steps.ts`: a step panel whose heading takes the focus, "Назад" and "Далее" navigation, and a review block with "Изменить") are identical copies in `features/edit-profile` and `features/fill-questionnaire` for now; a shared version belongs in `shared/ui`.
Shells. Public: a floating plate with the wordmark and links; below 700px the links open from a "Меню" button; a footer links the technical status. Candidate: the plate holds the wordmark, four sections (Главная, Профиль, Тест, Приглашения), a notifications bell, and an "Аккаунт" menu (Приватность, Поддержка, Выйти); there is no unread badge because the shell does not read notification data. The questionnaire belongs to "Профиль" and the results belong to "Тест": such a section stays current on the routes of its sub-sections (`aria-current="true"`, and `"page"` on the section page itself), and the sub-section pages show a `SectionSwitch` above the heading ("Профиль" and "Анкета", "Проверка" and "Результаты"), which the shell passes to the pages through `PageNavProvider`. Below 1024px the sections form a bottom bar of five items (the four sections and "Ещё"), the plate keeps the wordmark and the bell, and "Ещё" opens a sheet with notifications, privacy, support, and sign-out. Sign-out ends the session on the server and fully reloads the page on the sign-in screen, so no account data stays in memory; on failure the menu says that you are still signed in. The menu closes on Escape (focus returns to the button), after a navigation, and on a press or focus outside it. The navigation comes before `main` in the document, so the keyboard order is the same at every width. Employer (desktop first): from 1024px a floating 240px sidebar, below that a plate with a "Меню" button.
Accessibility: every shell starts with a skip link to `main`, has landmarks and a visible focus ring (2px `#9A92FF`, 2px offset), and moves focus to `main` after navigation. Animations respect `prefers-reduced-motion`.
## Tests
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Playwright checks clicks, input, and focus movement in real Chromium; Vitest does not substitute a browser environment.
Playwright specs in `e2e/` run in a real Chromium against the built frontend and backend: `make -C deploy test-e2e` starts a throwaway Compose stack and runs them in the official Playwright image, so no browser is installed on the host. Vitest excludes `e2e/`; `make -C frontend typecheck` and lint cover the specs. Artifacts of the last run are in `test-results/e2e/`. Details: [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
See the [development guide](../docs/en/DEVELOPMENT.md).
List commands with `make -C frontend help`. Current routes: [src/app/router/routes.tsx](src/app/router/routes.tsx). Development rules: [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md).
+38 -283
View File
@@ -2,304 +2,59 @@
Русский | [English](README.en.md)
SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API. Подбор кандидатов, чтение анонимной карточки работодателем и отправка приглашения из выдачи работают с API. Кандидат читает входящие приглашения, принимает их с выбором контактов и отклоняет. Владелец компании видит список ее приглашений с состояниями.
SPA на React и TypeScript для кандидатов и работодателей. Vite собирает статические файлы; Nginx отдает их и проксирует `/api/` в backend. Приложение использует React Router, TanStack Query, Zod и CSS Modules.
- `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута.
- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, подбор кандидатов, приглашение кандидату, список приглашений компании, входящие приглашения кандидата, обращения в поддержку и технический статус.
- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, виджет истории результатов `assessment-history`, виджет выдачи подбора `match-list`, предпросмотр приглашения `invitation-preview` и технический виджет `system-status`.
- `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)), `company` и `invitation`; `src/features/` - действия пользователя и формы.
- `src/shared/ui/` - токены дизайна, шрифты, словесный знак и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)).
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
- `e2e/` - спецификации Playwright, их настройки в `playwright.config.ts`; запускаются только на Compose-стеке.
## Структура
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
Код следует Feature-Sliced Design:
## Маршруты
| Каталог в `src/` | Назначение |
| ---------------- | --------------------------------------- |
| `app/` | Маршрутизация, провайдеры, общие стили |
| `pages/` | Страницы кабинетов и публичные страницы |
| `widgets/` | Крупные блоки интерфейса |
| `features/` | Действия пользователя |
| `entities/` | Предметные модели и их UI |
| `shared/` | API, UI-компоненты и общие утилиты |
| Группа | Пути | Оболочка |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` |
| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` |
| Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` |
Импорты идут сверху вниз через публичные точки входа слайсов. ESLint и проверка `test:fsd` контролируют границы.
У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере.
## Интерфейс
`/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает.
Публичные юридические страницы доступны по `/terms` и `/privacy` в `PublicShell`; личные настройки остаются на `/candidate/privacy`. Общие `Page`, `Button`, `LabelValue` и `ListRow` собирают заголовки, действия и строки списков. `Button` и `ButtonLink` поддерживают размеры `default` и `small`; `Tag` с тоном `grade` используется для подтвержденных категорий. Палитра, типографика, интервалы и правила контраста собраны в `shared/ui/theme/tokens.css`, а компоненты применяют их через CSS Modules. В поиске и приглашениях opaque handle отображается как `LX-...`, а исходное значение сохраняется для API-запросов.
## Серверные данные
## Запуск
Сгенерированные хуки Orval вызывают общий клиент `apiRequest` того же origin, поэтому у `QueryClient` нет функции запроса по умолчанию. Настройки в `app/providers/query-client.ts`:
Node.js указан в [.node-version](.node-version), pnpm - в [package.json](package.json). Из корня:
- повторы: не больше двух и только при отсутствии ответа (статус 0) и 5xx, кроме 501; 4xx и `invalid_response` завершаются сразу;
- `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса;
- автоматические повторы мутаций выключены; создание компании повторяется явным действием с тем же телом и `Idempotency-Key`.
```sh
make -C frontend install
make -C frontend dev
```
## Профиль кандидата
Vite проксирует `/api` на `http://127.0.0.1:8080`. Backend нужно запустить отдельно. Для полного сценария с cookie и проверкой Origin используйте [Compose](../docs/ru/DEPLOYMENT.md): публичный адрес должен совпадать с `APP_PUBLIC_URL`.
`entities/candidate` хранит модель полного черновика профиля и переводит ее в `CandidateProfileUpdate`. `features/edit-profile` отвечает за поля и сохранение, `pages/profile` - за страницу. Серверные данные остаются в React Query; контакты и черновик не записываются в localStorage или sessionStorage.
## API и генерация
Форма идет по шагам (`Stepper`): контакты, роли с самооценкой и подтвержденными категориями, опыт с подтверждением параллельных периодов, проекты, навыки, условия, проверка и сохранение. Сервер принимает профиль целиком с `expected_version`, поэтому сохранение есть только на последнем шаге. «Далее» проверяет поля текущего шага; ошибка клиента или сервера при сохранении открывает шаг, которому принадлежит поле. Неактивные шаги остаются в дереве со скрытым атрибутом: «Назад» сохраняет введенное, а связи полей с подсказками и ошибками остаются. При смене шага фокус переходит на его заголовок. У сохраненного профиля есть переход «К проверке и сохранению», а шаг проверки ведет к любому шагу кнопкой «Изменить». Перезагрузка открывает первый шаг с серверной записью; несохраненный черновик не восстанавливается.
Контракт находится в [api/core/](../api/core/openapi.yml). Orval по [codegen/orval.config.ts](codegen/orval.config.ts) создает клиент, query hooks, Zod-схемы и MSW handlers в `src/shared/api/endpoints/` и `schemas/`.
Форма сохраняет происхождение нетронутых предложений, показывает пересекающиеся периоды работы и требует явного подтверждения параллельной работы. Подтверждение связано с текущими индексами и датами; перестановка или изменение периодов требует проверки заново. Подтвержденные категории отображаются отдельно и не входят в тело сохранения. Ошибка версии 412 оставляет черновик и предлагает явно заменить его актуальными данными.
```sh
make -C frontend generate
make -C frontend check
```
После сохранения форма перечитывает сессию и показывает шаг аккаунта, который вернул сервер. Сохранение профиля само по себе не завершает шаг согласий; переход от него пока не реализован. Независимое редактирование профиля доступно без ML, файла и ФСП.
`shared/api/client.ts` и `index.ts` поддерживаются вручную. Генерируемые каталоги очищаются при генерации; не кладите туда собственный код. MSW используется в тестах, а не как подтверждение работы backend.
Шаг «Проекты» необязателен: до 10 проектов, у каждого название (одна строка, до 100 символов), описание (до 500), до 10 тегов технологий (чипы; тег добавляют Enter, запятая, кнопка «Добавить» или уход из поля, дубли без учета регистра отбрасываются) и необязательный адрес репозитория. Клиент принимает только `https://github.com/<владелец>/<репозиторий>`, как контракт и сервер: слеш в конце и `.git` убираются, другие хосты, порты, учетные данные, пути, параметры и фрагменты отклоняются, один репозиторий не указывается дважды (регистр не важен). Пустая строка проекта не отправляется; проект без названия, но с другими значениями блокирует шаг. Предупреждение сверху: название и описание могут выдать кандидата, адрес репозитория компании не получают. Список `projects` всегда уходит целиком с `expected_version`; нетронутая подсказка остается `extracted`. Статус проверки репозитория берется из последнего ответа профиля (`repository_check`) и показан тегом и словами: «Проверяется», «Публичный репозиторий найден», «Не найден или закрыт», «Лимит GitHub, повторим позже»; для адреса, которого сервер еще не хранит, написано «Проверка после сохранения». Пока есть `pending`, экран перечитывает профиль каждые 4 секунды (не дольше двух минут) и не трогает черновик. Отметка значит только, что публичный репозиторий существует; авторство она не доказывает. Кнопка «Проверить снова» вызывает `RequestMyRepositoryChecks` один раз для всех сохраненных адресов и показывает число запланированных проверок. На 429 кнопка блокируется с обратным отсчетом из `Retry-After` и текстом `detail` сервера; если сервер срок не назвал, отсчета нет и время не выдумывается.
## Проверки
## Анкета кандидата
| Команда из корня | Что проверяет |
| -------------------------------------- | -------------------------------------------------- |
| `make -C frontend typecheck` | Типы приложения, конфигурации и E2E |
| `make -C frontend test` | Vitest |
| `make -C frontend check` | Формат, lint, типы, тесты, FSD и сборку |
| `make -C deploy test-e2e` | Playwright на отдельном Compose-стенде |
| `make -C deploy test-e2e-registration` | Браузерные сценарии с локальной почтовой фикстурой |
`pages/questionnaire` получает каталог специализаций и приватные ответы текущего кандидата через Orval. Черновик остается в состоянии компонента, сохраненные ответы принадлежат React Query, а reload восстанавливает серверную запись. Форма предлагает одну или две специализации, самооценку грейда, доступные языки заданий, стек, опыт и форматы работы. Специализация без опубликованного банка отмечена как находящаяся в разработке; ее можно сохранить без ФСП.
E2E-артефакты: `test-results/e2e/`. Часть сценариев подменяет API; проверку отображения нужно отличать от полного пути с настоящим backend. Подробности: [TESTING.md](../docs/ru/TESTING.md).
Анкета идет по шагам: направления (одна или две специализации и доступность проверки по каталогу), уровень и опыт для каждой выбранной специализации (самооценка, язык заданий, стек, опыт), формат работы, проверка и сохранение. Правила шагов те же, что у профиля: сохранение целиком на последнем шаге с `expected_version`, проверка текущего шага кнопкой «Далее», переход к шагу с ошибкой сервера, скрытые, но смонтированные шаги, фокус на заголовке шага, первый шаг после перезагрузки.
Конфликт 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/onboarding`, шаг «Согласия») показывает шаги аккаунта - согласия, профиль, анкету и тест - компонентом `Stepper` с текущим шагом и действием для него.
## Проверка кандидата
`/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. Экспресс-тест (`demo_express`) показан как "Экспресс-тест" и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки тем же компонентом, что и страница результатов, со ссылкой на нее (см. [результаты кандидата](#результаты-кандидата)). Категорию присваивает только сервер; клиент не вычисляет баллы и грейды.
Экран попытки сосредоточен на задании: полоса над ним называет попытку, показывает прогресс отвеченных заданий, время до серверного срока `expires_at` моноширинным шрифтом (элемент `timer` без объявления каждой секунды; последнюю минуту отмечают цвет и подпись) и состояние сохранения ответа (вежливое сообщение о статусе). Вариант ответа выбирается клавишами 1-9, Enter на варианте отправляет ответ.
`Idempotency-Key` начала экспресс-запуска хранится в sessionStorage вкладки отдельно для каждого аккаунта, пока запуск не завершен или не истек, и не дольше 24 часов. Если новое начало получает 409 `state_conflict`, страница повторяет начало с ключом активного запуска, и сервер возвращает сохраненный ответ 201 с этой попыткой: незавершенная демонстрация продолжается после перезагрузки. Ключ начала с неизвестным исходом (нет ответа, 5xx) тоже сохраняется и повторяется. Если ключа нет (другой браузер, закрытая вкладка, заблокированное хранилище), экран объясняет, что демонстрация закончится сама не позже чем через 5 минут после начала.
Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки, правило одного окна и водяной знак: бледная плитка с кодом попытки и временем и невидимая метка в тексте задания). Браузер также фиксирует, как слабые подсказки, клавишу снимка экрана (PrintScreen, Cmd+Shift+3, 4 или 5, Win+Shift+S) и догадку об открытых инструментах разработчика по размеру окна; сервер хранит User-Agent только как ключевой отпечаток. Окно прямо говорит, что снимок экрана или фото телефоном предотвратить нельзя, а сигналы ведут только к ручной проверке. Это версия 4 текста уведомления; подтверждение более ранней версии для нее не засчитывается. Страница занимает единственный рабочий сеанс реальной попытки для своего открытого окна (`features/assessment-work-session`) и сообщает, если его держит другое окно. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным.
Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели сборщика пассивные, ничего не блокируют и не показывают (меры из следующего абзаца - отдельная функция и от сборщика не зависят); события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает.
Содержимое буфера и вводимый текст не читаются в сигнал и не отправляются. Размер вставки берется из события `paste`: размер файлов (`File.size`) и длина обычного текста в байтах UTF-8 из `clipboardData`; строка живет в одной локальной переменной на время подсчета и не сохраняется. Clipboard API (`navigator.clipboard`) не используется. Размер копирования и вырезания - длина выделения в единицах UTF-16 по смещениям поля, без чтения его значения; если у активного поля нет числовых смещений, размер равен нулю, а выделение страницы не читается. Это приблизительный размер, а не точный счет байтов. Время ответа по заданию измеряет сервер, клиент его не присылает. Время событий приводится к серверному: клиент запоминает разницу между часами устройства и заголовком `Date` ответов API, потому что сервер отклоняет весь пакет, если метка времени выходит за пять минут от его часов. Длительности считаются по часам устройства и от этой разницы не зависят. Браузерные сигналы легко подделать, а ложные срабатывания возможны, поэтому они только подсказка для перепроверки.
`features/assessment-lockdown` держит реальную попытку в полноэкранном режиме и скрывает задание, когда кандидат его покидает. Клик по кнопке "Начать или продолжить" запрашивает полноэкранный режим: запрос нужно сделать внутри клика, до асинхронной проверки уведомления, потому что браузер принимает его только при действии пользователя; закрытие уведомления без подтверждения снова выходит из полноэкранного режима. Пока идет работа, задание закрывается при выходе из полноэкранного режима, скрытии вкладки и потере фокуса окном (`fullscreenchange`, `visibilitychange`, `focus` и `blur`). Закрытие заменяет задание, а не размывает его: условие, варианты и поля ответа не отрисовываются, поэтому их нет ни в DOM, ни на снимке страницы, ни в дереве доступности. Форма ответа остается смонтированной и ничего не рисует, поэтому черновик сохраняется (копия черновика в sessionStorage по-прежнему ведется). Таймер остается серверным и виден на экране. После выхода из полноэкранного режима кандидат продолжает кнопкой: это действие пользователя, которое браузер требует для повторного входа; уход только с вкладки или из окна клика не требует. Эти выходы записывает сборщик из абзаца выше (`fullscreen_exit`, `focus_loss`), само закрытие ничего не записывает. Браузер без полноэкранного режима элемента (iPhone Safari) или отказавший в запросе получает информационное сообщение и проходит тест только с контролем вкладки (`fallback` `unsupported` или `denied`), поэтому экран не становится тупиком. Экспресс-запуск и завершенная попытка не защищаются, а уход со страницы или завершение попытки выходят из полноэкранного режима.
Та же панель (`ProtectedRegion`) не дает вынести текст задания реальной попытки. Текст нельзя выделить (`user-select` вместе с формой `-webkit-`, которая все еще нужна Safari, и отмененный `selectstart`), контекстное меню и перетаскивание на нем отменяются, копирование и вырезание отменяются, когда цель или выделение доходят до панели (в буфер попадает пустая строка), а `@media print` скрывает панель вместе с заданием, вариантами и полями ответа. Поля исключены: текстовое поле сохраняет выделение, собственное контекстное меню, копирование и вырезание собственного текста кандидата. Вставка в поля ответа отклоняется (событие `paste` и `beforeinput` вставки), экран сообщает об этом коротким статусом, который исчезает при следующем вводе, а сброс текста мышью в поле отклоняется везде. Редактор кода практического задания помечен `data-paste="allowed"`: вставка в нем работает, а ее размер уходит существующим сигналом `paste`. Сборщик видит каждую вставку, копирование и вырезание, в том числе отклоненные, потому что защита отменяет действие по умолчанию и никогда не останавливает распространение события, поэтому отклоненная вставка все равно остается сигналом с размером. Текст остается в странице для экранных дикторов (без canvas и текста в картинках), набор и порядок фокуса не затрагиваются, экспресс-запуск не ограничивается. Эти меры останавливают только простой путь: снимок экрана, второе устройство или расширение браузера все равно выносят задание, а вставка экранной клавиатурой, которая вставляет текст как набор, странице не видна.
## Результаты кандидата
`/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`) выводится только текстом: категория не меняется без отдельной команды кандидата, такой команды в интерфейсе пока нет;
- экспресс-результат подписан "Экспресс-тест без грейда", не показывает категорию и оценку и ведет к полной проверке; подготовленная полная попытка показывается отдельной записью истории. Подтвержденная категория выглядит одинаково при любом основании решения: пометок "демо" и статуса калибровки интерфейс не выводит, значения остаются в ответе API.
## Настройки приватности
`pages/privacy` (`/candidate/privacy`) показывает отдельные настройки видимости. Ни одно действие не включает другое: согласие, публикация, статус поиска и скрытие организации сохраняются своими запросами, у каждого своя версия и свое состояние сохранения.
- Согласия (`features/consent-management`): C1-C5 выдаются и отзываются по отдельности, текст и версия показаны до выдачи. Блок каждой цели имеет якорь, на который переводит фокус кнопка "Перейти к согласию C2".
- Публикация (`features/profile-visibility`): шаг 1 показывает, действует ли C2 по полной активной истории согласий; неизвестное или частично загруженное состояние не считается согласием, сохранение недоступно. Кнопка шага только переносит фокус к блоку C2 и ничего не выдает. Далее выбираются состояние карточки и поля, а публикация сохраняется отдельным действием (`SetMyPublication`, `expected_version` в теле). Конфликт 412 оставляет черновик на экране и предлагает явно загрузить актуальные настройки; ошибка сохранения не сбрасывает черновик. Отзыв C2 закрывает карточку, а новое C2 ее не открывает.
- Объяснение закрытия: по `closed_reason` экран говорит, что будущие чтения закрыты сразу, что новое C2 не откроет карточку само, и что бывшей компании для контактов нужны новое приглашение и новое согласие C4. Те же слова выводятся после отзыва C2, скрытия организации, снятия скрытия и повторной публикации: прежний доступ к контактам не восстанавливается. Скрытие не меняет запись C4 в журнале согласий, поэтому рядом с C4 скрытой компании выведено пояснение, что запись не возвращает доступ к контактам.
- Проекты в публикации. Поле `projects` - отдельный выбор «Проекты: название, описание и технологии». Предупреждение стоит под ним всегда (его читает вспомогательная технология вместе с чекбоксом) и становится «предупреждающим» после выбора: тексты проектов пишет кандидат и по ним его могут узнать, размер группы похожих кандидатов их не скрывает, адрес репозитория и его владелец компаниям не показываются никогда, они видят только отметку о найденном публичном репозитории.
- Статус поиска (`SetMySearchStatus`) - отдельный запрос и отдельный текст. Он не меняет публикацию и не выдает согласие.
- Предпросмотр для работодателя (`EmployerCardPreview` из `entities/candidate-view`) строится только из ответа `GET /me/privacy/preview`. Псевдоним предпросмотра отделен от псевдонимов организаций. Подтвержденные категории и самооценка выведены раздельно; у каждой специализации свой статус "Грейд подтвержден" или "Грейд не подтвержден", различимый по форме значка и тексту, а не по цвету. Кандидат без подтвержденного грейда видит заявленный уровень (или "Уровень не указан") и статус "Грейд не подтвержден" для каждой специализации отдельно; подтвержденный Backend не переносится на сетевую специализацию. Блок подтверждающих фактов показывает навык, грейд, уровень подтверждения, год и основу (`synthetic_demo` выводится как "Результат теста"; калибровка в интерфейсе не показывается). Закрытая карточка показана пустым состоянием. Предпросмотр не создает записи доступа и не учитывает фильтры организаций.
- Проекты в предпросмотре и в карточке работодателя показывает общий компонент `PublishedProjects` (`shared/ui`): название, описание (текст с переводами строк), теги и бейдж «Подтвержден публичным репозиторием» для `repository_verified`, с пояснением, что авторство отметка не доказывает. Адреса и ссылки нет ни в данных, ни в разметке; весь текст кандидата выводится как текст.
- Скрытие организаций: кнопка скрытия предлагается только организациям из собственной истории доступа (сервер отвечает 404 на остальные) и только после полной загрузки списка скрытых организаций. Снятие скрытия не восстанавливает контактный доступ.
- Истории: история настроек и история доступа к карточке постраничные; частичная страница не выдается за полную. Запись доступа показывает вид обращения, время и организацию, если сервер ее назвал (иначе "Организация не раскрывается"); сотрудников, запросов, фильтров и места в выдаче в ней нет. Пустая история и ошибка загрузки показаны отдельными состояниями.
- Ниже остается переход к запросу ручной оценки.
Чтение карточки работодателем и подбор описаны в разделе [Поиск кандидатов](#поиск-кандидатов). Скрытие и отзыв C2 из браузера в связке с подбором пока не проверены: e2e не повторяет их на стороне работодателя.
## Профиль компании
`pages/company` выбирает компанию из постраничного списка действующих membership текущего аккаунта. Читать и менять профиль может только owner. Форма сохраняет черновик в памяти, показывает серверный уровень проверки без возможности повысить его и строит предпросмотр только из `candidate_card`.
Создание использует один ключ идемпотентности для повторов того же тела после потерянного ответа. При конфликте версии 412 черновик сохраняется; пользователь отдельно загружает текущие данные, проверяет перенесенные изменения и повторяет сохранение. Фоновое обновление не сбрасывает черновик. Ответ 401/403/404 скрывает профиль и очищает его запрос из кеша; список компаний перечитывается. Это дополняет серверную проверку membership, а не заменяет ее.
## Потребности работодателя
`/employer/needs` показывает постраничный список компаний, где у текущего аккаунта есть активная роль owner, и их потребности. `/employer/needs/new?organization_id=...` создает потребность, а `/employer/needs/:needId?organization_id=...` открывает ее для редактирования. URL и кеш не дают полномочий: клиент сверяет текущую сессию и каталог владельца, а сервер проверяет membership для каждого запроса. Данные кеша привязаны к аккаунту и компании; ответы предыдущей сессии не возвращаются в новый кеш. При 401/403/404 приватные запросы компании удаляются.
Черновик редактора хранится в памяти. Извлеченные из описания поля и навыки остаются предложениями с происхождением, пока пользователь не подтвердит, не изменит или не удалит их. Неизвестные значения не подменяются дефолтами. Вопросы готовности показываются рядом с незаполненными полями; статус рекомендаций и категории берутся из API, без выдуманных результатов. Создание повторяет неизмененное тело с тем же ключом идемпотентности после неопределенного ответа. Конфликт версии 412 сохраняет черновик, предлагает загрузить актуальную версию и требует проверить перенесенные изменения до повтора.
Форма разбита на пять шагов (компонент `Stepper`): роль и грейд, навыки, задачи и область, условия работы, проверка и сохранение (`features/edit-need/model/steps.ts`). Неактивные шаги остаются смонтированными и скрыты атрибутом `hidden`, поэтому возврат назад и переход вперед не теряют черновик; фокус переходит на заголовок нового шага. Enter в поле ведет на следующий шаг, сохраняет только последний шаг. Название обязательно: шаг 1 не отпускает без него, шаг 4 не отпускает с неполной вилкой. Ошибки сервера по полям открывают шаг с первым из них и ставят фокус на поле. Справа (ниже 1200 px под формой) стоит живая сводка потребности: тег `BACKEND · MIDDLE`, стек-теги, вилка шрифтом mono, число неподтвержденных предложений, а для сохраненной потребности еще категории и версии. У сохраненной потребности на шагах 1-4 есть кнопка "К проверке и сохранению". Грейд и база суммы выбираются сегментным переключателем (`SegmentedControl`), формат работы - чипами-флажками; неизвестный грейд - отдельный пункт "Не указан", а не значение по умолчанию.
## Сущность потребности
`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. Страницы и формы потребностей находятся в `pages/needs`, `pages/need-editor` и `features/edit-need`.
- `fromTransport` строит черновик из `Need`. Каждое поле требования - явное состояние: `unknown` без значения, `extracted` - сохраненное предложение с происхождением и цитатой, `confirmed` - подтвержденное значение. Неизвестное поле никогда не превращается в пустую строку, пустой список или значение по умолчанию; навык вне таксономии сохраняет `taxonomy_code: null`. Данные, нарушающие правило "value и source равны null ровно при unknown", отклоняются ошибкой `NeedTransportError`.
- `toUpdateBody(need, draft)` отправляет только поля, чье значение в запросе изменилось, и `expected_version` прочитанной версии. Нетронутое предложение не отправляется; если его поле или список отправляются по другой причине, оно уходит со статусом `extracted`. Очищенное поле уходит как null, опустошенный список - как `[]`, нетронутый список отсутствует.
- `toCreateBody(draft)` всегда отправляет название, а неизвестные поля и пустые списки опускает, чтобы сервер извлек их из `source_text`.
- Функции правки (`confirmField`, `setFieldValue`, `clearField`, `confirmSkill`, `moveSkill` и другие) сохраняют инварианты: только нетронутое предложение имеет статус `extracted`, измененное значение становится `confirmed`, перенос навыка между списками его не подтверждает.
- `validateNeedCreate` и `validateNeedUpdate` проверяют тело сгенерированными схемами Zod и связывают ошибки с полями формы; межполевые правила (ширина вилки, повтор навыка) проверяет сервер, а `needFormFieldOf` переводит его pointer в поле формы.
Тесты берут фикстуры из именованных примеров контракта в `api/core/openapi.bundle.yml` и проверяют каждое тело сгенерированными схемами `NeedCreate` и `NeedUpdate`.
## Поиск кандидатов
`/employer/candidates` (`pages/matches`) ищет по `POST /organizations/{org_id}/matches` (`SearchOrganizationMatches`). Серверная модель описана в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение), контракт - в [API](../api/README.md#подбор).
- Доступ. Искать может только действующий владелец компании. Организация приходит в `organization_id`, список компаний владельца читается при каждом заходе (как на странице потребностей). Нет прав - состояние "Нужны права владельца компании"; 401 и 403 показывают состояние "нет доступа", 404 - ошибку "Потребность или компания не найдены", остальные ошибки - сообщение с повтором. Ответ 429, если он придет, показывает `Retry-After`.
- Запуск только по действию. Страница и перезагрузка поиск не выполняют: результат живет в мутации компонента и не сохраняется. Над кнопкой "Найти кандидатов" сказано, что поиск расходует квоту просмотров карточек: каждый впервые показанный кандидат считается одним просмотром, а уже показанный в текущем окне повторно не списывается. Двойное нажатие игнорируется, пока поиск идет.
- Основание. "По потребности": список первых 100 потребностей компании, версия требований берется из `GET` потребности (`requirements_version`, не общая `version`), фильтры добавляются сверху; грейд потребности фильтром не служит, об этом сказано под выбором. Ссылка "Подобрать кандидатов" на карточке потребности открывает поиск с выбранной потребностью. "По всем профилям": запрос с одними фильтрами, каждая специализация кандидата приходит отдельной записью.
- Фильтры (`features/filter-matches`): специализация, подтвержденный грейд, статус подтверждения, заявленный кандидатом грейд, технологии из карточки (нужны все), формат работы (достаточно одного общего), совместимость зарплатных ожиданий. Заявленный и подтвержденный грейд - разные поля с разными подписями; заявленный фильтр подсказкой назван "не подтверждением". Форма отправляет ровно включенные фильтры и ничего не ослабляет: противоречивая пара (например, "не подтвержден" и подтвержденный грейд) уходит как есть и дает пустую выдачу. Если форма изменилась после результата, над результатом появляется пометка, что выдача устарела; сама она не обновляется.
- Результат (`widgets/match-list`). Заголовок "Результат поиска" получает фокус после поиска. Ниже основание и текущие фильтры: для поиска по всем профилям это нормализованные фильтры из ответа, для поиска по потребности ответ их не повторяет, поэтому показаны отправленные. Потом три группы в постоянном порядке: "Подтвержденные", "Близкие варианты", "Грейд не подтвержден". Пустая группа остается с пометкой "В этой группе записей нет.". Признак `truncated` объясняется текстом "Показана часть выдачи; квота просмотров или предел группы" без числа. Пустая выдача объясняется отдельно: фильтры остаются включенными, перечислены те, что можно изменить, и ничего не ослабляется само.
- Специализации. Одна запись - это кандидат в одной специализации; один псевдоним может стоять в двух группах (подтвержден в Backend, не подтвержден в сетях). Если в результате больше одной специализации, появляется переключатель представления ("Все специализации", затем каждая): он скрывает записи других специализаций, не пересчитывает ничего и не переносит подтверждение. Псевдоним показан сокращенно (`entities/match/model/views.ts`), полный нужен только запросам и ссылке на приглашение.
- Запись (`entities/match`). Показаны специализация, статус "Грейд подтвержден: X" или "Грейд не подтвержден" (форма значка и текст), подтвержденная категория и сила подтверждения отдельной строкой от заявленного кандидатом грейда, безопасный контекст карточки (технологии, опыт, форматы, ожидания) и серверное объяснение источников: каждая строка `evidence_summary` с состоянием "Подтверждено", "Подтверждено частично", "Только заявлено кандидатом" или "Пробел: подтверждения нет". Значение `null` из контекста выводится как "Нет значения в карточке": контракт не говорит, скрыто оно или отсутствует. Контактов, настоящего идентификатора и причин отсутствия подтверждения в записи нет.
- Объяснение раскрывается кнопкой с `aria-expanded`. Оно строится только из компонентов ответа: Fit, Cov, Dom, Sem, перцентиль, V, Fr, Rsp и итоговый балл S показаны ровно так, как пришли, без округления сверх шести знаков. Нейтральное значение (`unknown_flags`) подписано "Нейтральное значение, не измерено" с причиной (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed` и другие). Перцентиль `null` выводится как "Нет значения", число не выдумывается. Нулевой соревновательный вклад назван "не штрафом". У записи без подтвержденного грейда есть только Fit и Cov: балла S, перцентиля и категории для нее не считают, и экран их не рисует. Неизвестное вне баллов (опыт, форматы, ожидания, результат проверки) перечислено в блоке "Что неизвестно" с пометкой, что это не отсутствие способности.
- Совпадения по смыслу (`semanticBlock` в `entities/match`). Внутри "Почему в подборке" блок "Совпадения по смыслу" печатает `semantic_evidence` в порядке и в пределах, которые прислал сервер: строка "тип требования и его текст → тип элемента и его название" (требование: "Обязательный навык", "Желательный навык", "Задача"; элемент: "Проект", "Стек", "Роль") и тег "Высокое сходство" или "Среднее сходство". У проекта показано название, а у проекта с `repository_verified` еще бейдж "Публичный репозиторий"; у стека и ролей названий нет, поэтому стоят подписи "Технологии карточки" и "Специализации и грейды карточки", а бейдж им не ставится. Если списка нет, потому что сервер назвал компонент `semantics` неизвестным по причине `ml_unavailable`, блок пишет "Совпадения по смыслу: смысловой анализ недоступен." теми же словами, что и объяснение; пустой список без такого флага (поиск по всем профилям, нет совпадений) блок не показывает. Адрес и владелец репозитория не могут попасть в разбор: адаптер отклоняет ответ с полем вне контракта.
- Открытие карточки. Кнопка "Открыть карточку" читает `GET /organizations/{org_id}/candidate-cards/{handle}`, а при наличии категорий - и раздел доказательств; без категорий сервер раздел не отдает, поэтому запрос не отправляется. Чтения не повторяются автоматически и не кешируются после ухода с экрана (`gcTime: 0`, без обновления при фокусе): каждое чтение попадает в журнал доступа кандидата. Закрытая панель остается в дереве, повторное открытие не читает карточку снова. Ответ 429 показывает "Квота просмотров карточек исчерпана" и время из `Retry-After`; если сервер его не назвал, время не выдумывается. Ответ 404 одним текстом заменяет все скрытые случаи и не называет причину. Если кандидат опубликовал проекты, панель карточки показывает их блоком "Проекты" (название, описание, теги, бейдж подтвержденного публичного репозитория) без адреса.
- Приглашение. Кнопка "Пригласить" есть у каждой записи, в том числе у неподтвержденной. Она ведет на `/employer/invitations/new` с параметрами `organization_id`, `candidate_handle`, `specialization` и, для поиска по потребности, `need_id` (см. [приглашение кандидату](#приглашение-кандидату)). Псевдоним привязан к организации и не является идентификатором кандидата.
- Раскладка. Форма стоит над выдачей на всех ширинах: основание поиска (сегментный переключатель "По потребности" и "По всем профилям"), выборы, ряд фильтр-чипов (технологии, формат, совместимость ожиданий; примененный чип синий и с галочкой) и действие; выдача идет на всю ширину. Запись на 768 px и шире - колонка содержимого и колонка действий ("Пригласить", объяснение, карточка); на 360 px действия и факты складываются в один столбец. Блок "Почему в подборке" набран моно на вложенной поверхности: знак "+" (подтверждено), "+/-" (частично), "?" (заявлено), "-" (пробел) повторяет слово состояния. Чип технологии, которую запросил поиск, помечен точкой и скрытым текстом "совпадает с условием поиска". Все действия доступны с клавиатуры, фокус виден, статус кодируется текстом и формой, а не цветом.
Проверки. Модульные тесты: разбор и подписи (`entities/match`), сборка запроса из черновика (`features/filter-matches`), разметка выдачи (`widgets/match-list`). Playwright `e2e/match-search.spec.ts` состоит из двух групп. Первая работает на реальном бэкенде (нужны почтовая и компанийная фикстуры): пять синтетических кандидатов публикуют одинаковую карточку с заявленными грейдами Backend и сетей, владелец ищет, проверяет группы, переключение Backend/Сети для одного псевдонима, сравнение Fit и Cov с ответом, чтение карточки, объясненную пустую выдачу при невыполнимом фильтре, отсутствие повторного поиска после перезагрузки и 360 px. Вторая группа отвечает из заглушки и проверяет то, чего стенд не создает: порядок трех групп с подтвержденным Backend и неподтвержденными сетями у одного псевдонима, нейтральные значения и причины, `truncated`, 429 с `Retry-After`, 404 карточки, ошибки, права и поиск по потребности. Подтвержденные группы на реальном бэкенде не проверены: карточка отдается группе не меньше пяти одинаковых карточек, а подтвержденная категория на стенде требует прохождения проверки каждым из них. Реальная исчерпанная квота и скрытие или отзыв C2 из браузера работодателя тоже не проверены.
## Приглашение кандидату
`/employer/invitations/new` (`pages/invitation-compose`) открывается кнопкой "Пригласить" из выдачи подбора. Кандидат назван только псевдонимом записи (`candidate_handle`, на экране сокращенно); адрес без псевдонима предлагает перейти к поиску. Контракт описан в [API](../api/README.md#приглашения-и-контактные-разрешения).
- Доступ. Как и поиск, экран доступен только активному владельцу компании из `organization_id`: список компаний читается при каждом заходе, у участника с другой ролью кнопки отправки нет ("Нужны права владельца компании"). Сервер проверяет роль сам и отвечает 403; форма показывает это как потерю доступа.
- Форма (`features/send-invitation`). Поля повторяют `InvitationTerms` и ничего сверх: роль, специализация (из записи поиска), грейд, тип предложения, задачи (по одной в строке), команда, технологии, форматы и место работы, канал связи с необязательным комментарием, вилка в рублях с явной базой (net или gross), четыре условия пакета и срок ответа 3, 7 или 14 дней. Каждое условие пакета выбирается явно: "Предусмотрено" с описанием или "Не предусмотрено"; по умолчанию не выбрано ничего. При поиске по потребности форма заполняется только подтвержденными требованиями потребности, а в черновик уходит ссылка на ее `requirements_version`.
- Проверка до запроса. Клиент повторяет правила контракта: обязательные поля и длины, вилка из целых рублей с шагом 1 000, нижняя граница меньше верхней, ширина от 10% до 40% середины (`entities/invitation/model/salary-range.ts`), место работы для офиса и гибрида, повтор технологии без учета регистра. С неполной вилкой, без способа связи или без выбора в пакете запрос не отправляется. Ошибки собираются в список с фокусом в начале формы и привязаны к полям через `aria-invalid` и `aria-describedby`.
- Ответ сервера главнее. Ошибки RFC 9457 из `errors[].pointer` переводятся в поля формы (`fieldOfPointer`, например `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); текст сервера не показывается. `/candidate_handle` и `/need` дают общее сообщение без причины.
- Шаги. Форма идет в четыре шага (`Stepper`): условия, пакет и срок ответа, предпросмотр, отправка. Кнопка "Далее" на первом шаге проверяет только его поля; "К предпросмотру" проверяет всю форму. Ошибка открывает шаг с первым проблемным полем и ставит фокус на список ошибок над шагом. Тип предложения, грейд, база суммы, условия пакета и срок ответа - сегментные переключатели, формат работы - чипы. Enter в поле ведет на следующий шаг, отправляет только последний.
- Предпросмотр (`widgets/invitation-preview`). Переход "К предпросмотру" проверяет форму и показывает карточку компании из `candidate_card` (`GET /organizations/{org_id}`) и все условия так, как их увидит кандидат; фокус переходит на заголовок шага. Предпросмотр строится заново при каждом входе в шаг, ничего не отправляет и не создает черновик.
- Отправка. "Отправить приглашение" выполняет команду из трех операций (`features/send-invitation/model/send-command.ts`): `CreateOrganizationInvitation` с Idempotency-Key, при изменившихся условиях сохраненного черновика `UpdateOrganizationInvitation` с `expected_version`, затем `SendOrganizationInvitation` с отдельным Idempotency-Key. Ключ создания привязан к телу запроса, ключ отправки - к черновику и его версии; оба сохраняются, пока команда не завершится, поэтому повторное нажатие после потерянного ответа, 5xx или 409 `idempotency_in_progress` повторяет тот же ключ. Нажатие во время выполнения ничего не запускает. После 412 форма перечитывает черновик и применит свои условия при следующей отправке. Ответы проверяются сгенерированной схемой Zod.
- Результат. После успешной отправки экран показывает состояние "Доставлено", момент доставки и срок ответа из ответа сервера (`response_deadline_at`, в UTC), версию условий, зарплатный индикатор и отправленные условия; фокус переходит на заголовок. После создания черновика его `invitation_id` записывается в адрес: перезагрузка открывает несохраненный черновик для отправки или уже отправленное приглашение с сохраненным сроком.
Проверки. Модульные тесты: правила вилки (`entities/invitation`), проверка черновика и перевод указателей ошибок, команда отправки на MSW (ключи, повтор после потерянного ответа создания и отправки, 400 с полями, обновление черновика, 412), разметка предпросмотра и страницы (доступ владельца, пустой адрес). Playwright `e2e/invitation-compose.spec.ts` работает на реальном бэкенде в `make -C deploy test-e2e-registration`: пять синтетических кандидатов публикуют одинаковую карточку, владелец находит их поиском, открывает приглашение из выдачи, заполняет [100000; 140000] net и пакет по шагам и сверяет предпросмотр со всеми условиями; без способа связи форма не уходит с шага условий, видна ошибка поля, запросов нет, inbox кандидатов пуст. Затем отправка замедляется, первый ответ теряется, второе нажатие во время запроса ничего не запускает, повтор идет с тем же ключом; в итоге одно приглашение в одном inbox (`GET /me/invitations`) с тем же сроком, что на экране и после перезагрузки. Отказ 403 для рекрутера в браузере не проверен: на стенде нет способа выдать такую роль; поведение экрана для неглавной роли покрыто модульным тестом.
## Приглашения компании
`/employer/invitations` (`pages/employer-invitations`) показывает приглашения компании из `GET /organizations/{org_id}/invitations`: черновики и отправленные, новые сверху, страницами по курсору ("Показать еще"). Компания берется из `organization_id` адреса, иначе первая компания, где аккаунт владелец; при нескольких компаниях выбор виден над списком. Право владельца подтверждается по актуальному списку компаний, остальные роли получают отказ.
- Строка. Заголовок - название роли; тег состояния называет состояние словами, а тон повторяет смысл (черновик - нейтральный, ждет ответа - акцентный, принято - успех, отклонено, истекло и отозвано - опасность). Ниже: кандидат только сокращенным псевдонимом (`entities/match/model/views.ts`), вилка зарплаты, основание (потребность с версией требований или прямое приглашение), даты создания и изменения, срок ответа и доступ к контактам (виды контактов при `available`, "Доступ закрыт" при `closed`). Ни имени, ни значения контакта в ответе списка нет и на экране нет.
- Даты. В сводке списка нет момента доставки, поэтому показаны создание и последнее изменение, оба в UTC через `formatServerMoment`.
- Фильтр. `SegmentedControl` "Все", "Ожидают ответа", "Приняты", "Закрыты" и "Черновики" работает на клиенте по загруженным страницам, потому что фильтра по состоянию в API пока нет (`entities/invitation/model/list-groups.ts`: каждое состояние контракта входит ровно в одну группу). Если в группе нет загруженных записей, а страницы остались, экран не утверждает, что группа пуста, а предлагает загрузить следующие.
- Ссылки. Черновик и отправленное приглашение ведут на один маршрут `/employer/invitations/new` с `organization_id`, `candidate_handle` и `invitation_id`: для черновика он открывает форму с сохраненными условиями, для отправленного - состояние, срок, условия и, после принятия, контакты. Отдельной страницы приглашения у компании нет.
- Состояния. Загрузка (сообщение и скелетон), пустой список со ссылкой на "Кандидаты", ошибка с повтором, отказ 401/403 и 404 без повтора, ошибка обновления над уже загруженным списком.
Проверки. Модульные тесты: группы и тоны состояний, адаптер списка на MSW (размер страницы, курсор, проверка ответа схемой, отказ 403), разметка списка (каждое состояние с тоном, фильтр, пустые состояния, ссылки черновика и отправленного, отсутствие значений контактов) и страницы (загрузка, пусто, ошибка с повтором, отказ, чужая компания). Playwright `e2e/acceptance-path.spec.ts` после отправки трех приглашений открывает экран владельца и сверяет три доставленных приглашения без контактов кандидатов.
## Входящие приглашения кандидата
`/candidate/invitations` (`pages/candidate-invitations`) показывает входящие приглашения: список по курсору из `GET /me/invitations`, новые сверху, без записи просмотра. `/candidate/invitations/:invitationId` открывает одно приглашение. Контракт описан в [API](../api/README.md#приглашения-и-контактные-разрешения).
- Чтение и просмотр. Экран читает приглашение через `GET /me/invitations/{id}`, а при открытии один раз записывает просмотр (`POST .../view` с CSRF-токеном, без Idempotency-Key). Чтение ничего не меняет; просмотр переводит `delivered` в `viewed` и не меняет срок. Ответ просмотра применяется только если его версия новее уже показанной.
- Условия. Компания, роль, задачи, команда, технологии, формат и место работы, вилка зарплаты с базой (net или gross), пакет и способ связи показаны так же, как в предпросмотре компании (`widgets/invitation-preview`, общий блок `InvitationTermsArticle`). Срок ответа показан с меткой UTC (`formatServerMoment`). Карточки компании у кандидата нет: контракт отдает только название.
- Срок. Открыт ли ответ, решают состояние приглашения и серверные часы (`useServerNow`, поправка по заголовку `Date`). После срока ответы закрыты даже до того, как сервер применит истечение при следующем чтении.
- Принятие с C4 (`features/accept-contact-consent`). Виды контактов берутся из `contact_consent.available_fields` и могут быть ФИО, электронная почта, телефон и Telegram, если профиль их содержит. Ничего не отмечено заранее: каждый вид выбирается отдельно. Кнопка становится доступна после выбора хотя бы одного вида и отдельного подтверждения текста. Текст согласия показывается как текст без изменений, абзацы берутся из ответа сервера. Без контактов в профиле принять нельзя, экран предлагает открыть профиль.
- Отказ (`features/respond-invitation`). Причина выбирается явно, ни одна не выбрана заранее. Комментарий необязателен для любой причины, включая «Другая причина»; до 500 символов. Комментарий видит только кандидат.
- Устаревшие условия. Ответ 412 `version_conflict` (и 409 с тем же кодом) перечитывает приглашение: показывается новая версия условий, выбор контактов и подтверждение сбрасываются, экран просит подтвердить заново; ответ 409 `state_conflict` показывает итоговое состояние вместо повтора. Повтор того же ответа после потерянного ответа или 5xx использует тот же Idempotency-Key (`entities/invitation/model/command-key.ts`), изменившийся выбор получает новый ключ.
- Итог. После принятия экран показывает только виды контактов, которые покрывает грант (`contact_grant.fields`), и готовность компании их прочитать: при `readable` false с причиной `visibility` объясняет, что карточка должна быть опубликована и открыта для компании. После отказа показывает причину и собственный комментарий кандидата. Компания получает контакты только через свой эндпоинт, и только виды из гранта.
Проверки. Модульные тесты: правила срока и просмотра, классификация ошибок ответа (`entities/invitation/model/response-failure.ts`), ключи повторов, состояния черновиков формы, адаптеры и команды ответа на MSW (заголовки CSRF и Idempotency-Key, проверка ответа схемой, повтор после потерянного ответа), разметка списка, экрана, форм и блока условий. Playwright `e2e/candidate-invitations.spec.ts` работает на настоящем бэкенде в `make -C deploy test-e2e-registration`: пять синтетических кандидатов публикуют карточку, владелец находит их поиском, три приглашения отправляются через API. На 360 px кандидат принимает приглашение, отметив только электронную почту; API кандидата показывает один грант, эндпоинт компании отдает почту и не отдает телефон. Устаревшие условия проверяются перехватом ответа: команда повышения верхней границы вилки после отправки (`RaiseOrganizationInvitationSalary`) в бэкенде пока не реализована, поэтому 412 и новая версия условий задаются маршрутом, а отсутствие гранта проверяется на настоящем бэкенде. Отказ «Другая причина» без комментария и перезагрузка проверяются на настоящем бэкенде: после перезагрузки состояние `declined` сохраняется, эндпоинт контактов компании отвечает 404.
## Поддержка и ручная оценка
`/candidate/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе.
Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Подсказка под выбором специальности и грейда учитывает опубликованные грейды каталога, но не обещает рубрику: версию фиксирует сервер при отправке. Страница обращения показывает статус и версию рубрики, возвращенные сервером, а при `null` прямо сообщает, что опубликованной рубрики на момент запроса не было; результат не создается на клиенте. После перезагрузки страницы форма теряет ключ идемпотентности, и повторная отправка при открытой ручной оценке той же специальности получает 409; страница объясняет это и ведет в "Мои обращения", не создавая второй запрос.
## Уведомления
`features/notifications` показывает inbox текущего аккаунта на `/candidate/notifications` и `/employer/notifications`, а каждая оболочка ссылается на него. `NotificationInbox` принимает область: кабинет кандидата или одна организация. `OrganizationNotificationInbox` выбирает организацию из активных членств аккаунта (параметр `organization_id` сохраняет выбор при перезагрузке) и показывает inbox. Список читается при каждом заходе и при фокусе окна и не сохраняется (`gcTime: 0`); кэшированные страницы привязаны к аккаунту и кабинету и сбрасываются при смене аккаунта или сессии и когда сервер отказывает в доступе.
Текст каждого элемента сервер вычисляет из его текущего источника. Элемент без содержимого остается в списке с общей строкой, а клиент никогда не показывает прежнюю копию. Состояние прочтения выражено словом ("Не прочитано" или "Прочитано"), а не только стилем. "Отметить прочитанным" - нативная кнопка, она отправляет CSRF-токен сессии (читается в момент запроса; после 403 сессия читается заново и запрос повторяется один раз, а потерей доступа считаются только 401 и 404) и после успеха переводит фокус на заголовок элемента, объявляя вежливое сообщение о статусе. Ссылка содержимого открывается, только если это путь того же origin внутри кабинета, который ее показывает. Состояния: загрузка, пусто, ошибка с повтором, нет доступа (в том числе при завершенном членстве) и "Показать еще" для следующей страницы. Компонентные тесты отрисовывают разметку в Node; путь с клавиатуры и доставку настоящего события проверяет `frontend/e2e/notifications.spec.ts`.
## Генерация API-клиента
`make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения.
`fakeFromPattern` разбирает подмножество регулярных выражений (символы, экранирование, классы, группы, альтернативы, квантификаторы, `^` и `$` по краям), выбирает длину в пределах шаблона и границ и строит строку генератором faker, поэтому одинаковый seed дает одинаковые данные. Каждое значение проверяется через `new RegExp(pattern, "u")` и границы длины; шаблон вне подмножества (например, lookahead или обратная ссылка) или недостижимые границы вызывают исключение.
`src/shared/api/mock-validity.test.ts` вызывает каждую фабрику `get*ResponseMock` из `endpoints/*/*.msw.ts` с 25 значениями seed и проверяет результат сгенерированной Zod-схемой ответа. Zod-схемы Orval не проверяют `uniqueItems`, поэтому тест эту границу не покрывает; массивы с `uniqueItems` в ответах сейчас состоят из значений перечислений, и мок выбирает их через `faker.helpers.arrayElements` без повторов.
## Токены и тема
Токены лежат в `shared/ui/theme/tokens.css`: палитра, семантические цвета, шкала шрифтов, отступы с шагом 4px, радиусы, линии, кольцо фокуса, ширины контента, высота шапки и анимация. Значения взяты из графитовой системы `docs/other/design/DESIGN.md`, кроме фирменного знака ФСП: продукт называется Lincodex. Точки перелома зафиксированы в media-запросах: минимум 360px, телефонная раскладка до 700px (`43.75rem`), планшет 768px (`48rem`), навигация для компьютера 1024px (`64rem`) и проверенная широкая ширина 1280px.
Поставляется одна темная тема, она же тема по умолчанию (`color-scheme: dark`). Холст `#1B1C21`, карточки и поля `#202129`, приподнятые поверхности `#2D2E37`, границы - линии в 1px, тень есть только у всплывающих меню. Единственный цвет действия - синий `#402FFF` на основных кнопках; при наведении кнопка инвертируется в `#EDEDED` с синим текстом. Текст, ссылки, кольцо фокуса и выбранные метки используют читаемый акцент `#9A92FF`: сам `#402FFF` на графите дает только 2.49. Красный `#EC1D35` - только точки 6-8px, текст ошибок - `#FF5A6A`, успех - `#3CCF7E`. Текущий раздел, выбранная вкладка и текущий шаг показаны инверсией: светлая капсула с графитовым текстом. Все кнопки, поля, вкладки и метки - капсулы, карточки скруглены на 24px, панели на 32px, вложенные поверхности на 16px, мелкие объекты на 6px.
`app/ui/styles.css` задает базу: заголовки набраны JetBrains Mono, абзацы и мета - Inter. Нативные поля ввода и списки получают темную капсулу и отступы правилами элементов со специфичностью (0,1,2): выше правила модуля вроде `.field input`, ниже правил состояния вроде `.field input[aria-invalid]`. Границы полей остаются в модулях экранов и используют `--color-border-strong`.
Контраст используемых пар по WCAG 2.2:
| Текст | Фон | Контраст | Где |
| ------- | ------- | -------- | ----------------------------------------------------------------- |
| #EDEDED | #1B1C21 | 14.53 | Текст на холсте |
| #EDEDED | #202129 | 13.68 | Текст на карточках, полях и шапке |
| #EDEDED | #2D2E37 | 11.52 | Вторичная кнопка, меню |
| #FFFFFF | #1B1C21 | 17.01 | Заголовки на холсте |
| #FFFFFF | #202129 | 16.02 | Заголовки карточек, зарплата |
| #FFFFFF | #414246 | 10.04 | Вторичная кнопка при наведении |
| #9B9C9E | #1B1C21 | 6.19 | Вторичный текст, мета |
| #9B9C9E | #202129 | 5.83 | Вторичный текст на карточках |
| #9B9C9E | #2D2E37 | 4.91 | Вторичный текст на приподнятой поверхности |
| #878994 | #1B1C21 | 4.89 | Подсказки и плейсхолдеры |
| #878994 | #202129 | 4.60 | Плейсхолдеры полей |
| #9A92FF | #1B1C21 | 6.42 | Ссылки, акцентные метки, кольцо фокуса |
| #9A92FF | #202129 | 6.05 | Ссылки и кольцо фокуса на карточках |
| #9A92FF | #2D2E37 | 5.09 | Ссылки и фокус в меню |
| #FFFFFF | #402FFF | 6.84 | Основная кнопка, ссылка пропуска |
| #FFFFFF | #3324E0 | 8.50 | Основная кнопка при нажатии |
| #402FFF | #EDEDED | 5.85 | Основная кнопка при наведении (инверсия) |
| #1B1C21 | #EDEDED | 14.53 | Текущий раздел, выбранная вкладка, текущий шаг |
| #1B1C21 | #9A92FF | 6.42 | Выполненный шаг, выделение текста |
| #FF5A6A | #1B1C21 | 5.61 | Текст ошибок |
| #FF5A6A | #202129 | 5.28 | Текст ошибок на карточках |
| #FF5A6A | #30212A | 5.03 | Ошибка в блоке ошибки (8% красного на #202129) |
| #9B9C9E | #30212A | 5.55 | Пояснение в блоке ошибки |
| #FF5A6A | #41202B | 4.72 | Метка ошибки (16% красного на #202129) |
| #3CCF7E | #1B1C21 | 8.44 | Успех: сохранено, подтверждено |
| #3CCF7E | #243935 | 6.09 | Метка успеха (14% зеленого на #202129) |
| #9A92FF | #262450 | 5.47 | Акцентная метка (18% синего на #202129) |
| #9B9C9E | #2C2D35 | 4.98 | Нейтральная метка (6% светлого на #202129) |
| #EDEDED | #34353D | 10.41 | Метка стека (10% светлого на #202129) |
| #EDEDED | #1F2028 | 13.85 | Текст на стеклянной шапке (88% #202129 на холсте) |
| #73757F | #1B1C21 | 3.71 | Граница полей и элементов управления (нужно 3:1) |
| #73757F | #202129 | 3.49 | Граница полей на карточках (нужно 3:1) |
| #1B1C21 | #FF5A6A | 5.61 | Знак внутри метки ошибки (графика) |
| #EC1D35 | #1B1C21 | 3.88 | Красная точка "новое", "live" (графика, смысл дублирован текстом) |
Исключенные пары: `#402FFF` не используется как текст или граница на графите (2.49 на `#1B1C21`); `#878994` и `#FF5A6A` не используются на `#2D2E37` (3.88 и 4.44); волосяная линия `#2D2E37` на холсте (1.26) только декоративна и не является единственной границей элемента управления.
## Шрифты и словесный знак
Все шрифты раздаются с нашего сервера (`font-src 'self'`), лицензия SIL OFL 1.1; лицензии, авторы, источники и диапазоны символов лежат в `shared/ui/theme/fonts/` (`SOURCES.txt`). Файлы - подмножества, собранные fontTools:
- JetBrains Mono 2.304 из архива брендбука, переменный вес 400-700: заголовки, навигация, кнопки, метки, числа, грейды, стек, коды; `Mono` добавляет табличные цифры.
- Inter 4.001 из репозитория Google Fonts, переменный вес 400-700, латиница и кириллица: абзацы, мета, поля форм.
- Unbounded 1.701 из репозитория Google Fonts, только латиница, только словесный знак. Широкий геометрический гротеск отличает название от текста интерфейса, который набран моноширинным шрифтом и Inter.
Логотипа ФСП в интерфейсе нет. `Wordmark` - текстовый знак "Lincodex" с курсором терминала цвета действия; доступное имя ссылки ровно "Lincodex", курсор декоративен, а название кабинета стоит рядом со ссылкой. Иконка вкладки `public/favicon.svg` - буква L с курсором на синем квадрате.
## Общие компоненты
- `Page`, `Section`, `Stack` - раскладка страницы; `Page` содержит единственный `h1` и задает заголовок документа. `Section` висит на дорожке платы: узел у заголовка и линия вдоль раздела.
- `Button`, `ButtonLink` (варианты `primary`, `secondary`, `quiet`), `TextLink`, `NavItem` - элементы управления с текстовыми подписями; `NavItem` отмечает активный раздел через `aria-current` и инверсией капсулы; оболочка может сама задать состояние (`current`) для раздела, который остается активным на маршрутах подразделов.
- `HeaderPlate`, `MenuButton`, `useMenuToggle`, `Wordmark` - шапка оболочек: плавающая стеклянная плашка, кнопка меню с `aria-expanded` (меню закрывается после перехода и по Escape, фокус возвращается на кнопку; с параметром `dismissOutside` еще и при нажатии или фокусе вне меню) и словесный знак.
- `Card` (`raised`, `inset`, `panel`), `Tag` (`neutral`, `grade`, `stack`, `accent`, `success`, `danger`), `AttentionDot`, `Notice` - контейнеры, метки и сообщения. Смысл всегда передан текстом, цвет его только повторяет.
- `Stepper` и `buildSteps` - ход многошагового сценария: строка "Шаг N из M", список с `aria-current="step"` и текстовым статусом каждого шага.
- `Tabs` (шаблон вкладок WAI-ARIA, стрелки, Home и End, неактивные панели остаются в дереве со скрытым атрибутом, поэтому состояние формы сохраняется) и `SegmentedControl` (нативная группа радиокнопок в виде капсул). `SectionSwitch` - переключатель подразделов в виде капсул, но из ссылок на маршруты: у него нет панелей, поэтому вкладки не подходят.
- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus` - состояния экранов. У каждого состояния своя форма и текст; пустое состояние рисует дорожку платы, которая заканчивается пустым узлом. `ErrorState` показывает код, статус, текст сервера и идентификатор запроса как обычный текст и предлагает повтор. `Skeleton` - декоративные заготовки строк при загрузке, только вместе с сообщением о загрузке.
- `QueryView` - превращает результат запроса в загрузку, ошибку, отсутствие доступа (401 и 403 без повтора), пустое состояние или данные.
- `describeError` - русский текст ошибки по коду проблемы, а для неизвестного кода по HTTP-статусу. Код `service_unavailable` (503, например пока загружается модель) показан как "Сервис пока не готов" с советом повторить через минуту; серверный текст остается только технической деталью.
- `PublishedProjects` - проекты, которые кандидат опубликовал в анонимной карточке: название, описание, теги и бейдж "Подтвержден публичным репозиторием". Это чисто презентационный компонент без адреса репозитория; текст кандидата выводится как текст, никогда как разметка.
- `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью.
- `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`.
Шаги длинной формы (`form-steps.tsx`, `use-form-steps.ts`: панель шага с заголовком, получающим фокус, навигация «Назад» и «Далее», блок проверки с кнопкой «Изменить») пока лежат одинаковыми копиями в `features/edit-profile` и `features/fill-questionnaire`; общий вариант стоит перенести в `shared/ui`.
Оболочки. Публичная: плавающая плашка со словесным знаком и ссылками, ниже 700px ссылки открываются кнопкой "Меню"; подвал со ссылкой на технический статус. Кандидат: в плашке словесный знак, четыре раздела (Главная, Профиль, Тест, Приглашения), колокольчик уведомлений и меню "Аккаунт" (Приватность, Поддержка, Выйти); бейджа непрочитанных нет, потому что оболочка не читает данные уведомлений. Анкета - часть раздела "Профиль", результаты - часть раздела "Тест": такой раздел остается текущим на маршрутах своих подразделов (`aria-current="true"`, на самой странице раздела `"page"`), а страницы подраздела показывают над заголовком переключатель `SectionSwitch` ("Профиль" и "Анкета", "Проверка" и "Результаты"), который оболочка передает страницам через `PageNavProvider`. Ниже 1024px разделы образуют нижнюю панель из пяти пунктов (четвертый раздел и "Ещё"), плашка остается со словесным знаком и колокольчиком; "Ещё" открывает лист с уведомлениями, приватностью, поддержкой и выходом. Выход завершает сессию на сервере и полностью перезагружает страницу на входе, чтобы в памяти не осталось данных аккаунта; при ошибке меню сообщает, что вы остались в кабинете. Меню закрывается по Escape (фокус возвращается на кнопку), после перехода и при нажатии или фокусе вне меню. Навигация в документе идет до `main`, поэтому порядок клавиатуры одинаков на любой ширине. Работодатель (сначала компьютер): с 1024px плавающая боковая панель 240px, ниже - плашка с кнопкой "Меню".
Доступность: каждая оболочка начинается со ссылки пропуска к `main`, содержит ориентиры и видимое кольцо фокуса (2px `#9A92FF` с отступом 2px) и переводит фокус на `main` после перехода. Анимации учитывают `prefers-reduced-motion`.
## Тесты
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия, ввод и перемещение фокуса проверяются Playwright в настоящем Chromium; Vitest не подменяет браузерное окружение.
Спецификации Playwright из `e2e/` выполняются в настоящем Chromium на собранных frontend и backend: `make -C deploy test-e2e` поднимает одноразовый Compose-стек и запускает их в официальном образе Playwright, поэтому браузер на хост не ставится. Vitest исключает `e2e/`; `make -C frontend typecheck` и lint проверяют спецификации. Артефакты последнего прогона лежат в `test-results/e2e/`. Подробнее: [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
Полный список команд: `make -C frontend help`. Текущие маршруты: [src/app/router/routes.tsx](src/app/router/routes.tsx). Правила разработки: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md).
+8
View File
@@ -400,6 +400,14 @@ function scenarioAnswer(scenario: Scenario, pathname: string): Stub {
page: { has_more: false, next_cursor: null },
},
};
case "/api/v1/me/invitations":
return {
status: 200,
body: {
items: [],
page: { has_more: false, next_cursor: null },
},
};
case "/api/v1/me/privacy":
return { status: 200, body: scenario.privacy ?? closedPrivacy };
default:
+43 -46
View File
@@ -221,30 +221,26 @@ async function expectNoHorizontalOverflow(page: Page, width: number): Promise<vo
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
}
// The list of contacts that the grant covers, found by the heading above it.
function grantList(page: Page): Locator {
return page
.getByRole("heading", { name: "Контакты, которые открыты компании" })
.locator("xpath=following-sibling::ul[1]")
.getByRole("listitem");
}
// Opens an invitation screen by an action (a link click or a direct address)
// and waits for the view the page records once when it opens.
async function openInvitation(
// Opens the answer form on the candidate home and waits for its one-time view.
async function openHomeInvitation(
candidatePage: Page,
invitationId: string,
navigate: () => Promise<unknown>,
): Promise<void> {
organizationName: string,
): Promise<Locator> {
await candidatePage.goto("/candidate");
const card = candidatePage.locator("article").filter({ hasText: organizationName });
await expect(card).toBeVisible();
const viewed = candidatePage.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === `/api/v1/me/invitations/${invitationId}/view` &&
response.status() === 200,
);
await navigate();
await card.getByRole("button", { name: "Ответить на приглашение" }).click();
expect((await viewed).status()).toBe(200);
await expect(candidatePage.getByRole("heading", { level: 1, name: "Приглашение" })).toBeVisible();
await expect(card.getByRole("heading", { name: "Принять приглашение" })).toBeVisible();
await expect(candidatePage).toHaveURL(/\/candidate\/?$/);
return card;
}
test.describe("candidate invitations with the real backend", () => {
@@ -318,16 +314,12 @@ test.describe("candidate invitations with the real backend", () => {
await test.step("accepts with the email only at 360px, and the organization reads the email only", async () => {
const candidatePage = accepting.candidate.page;
await candidatePage.setViewportSize({ width: 360, height: 900 });
await candidatePage.goto("/candidate/invitations");
const link = candidatePage.getByRole("link", { name: new RegExp(organizationName) });
await expect(link).toBeVisible();
const card = await openHomeInvitation(
candidatePage,
accepting.invitationId,
organizationName,
);
await expectNoHorizontalOverflow(candidatePage, 360);
await openInvitation(candidatePage, accepting.invitationId, async () => {
await link.click();
await expect(candidatePage).toHaveURL(
new RegExp(`/candidate/invitations/${accepting.invitationId}$`),
);
});
// Nothing is preselected: every kind and the confirmation start unchecked.
for (const label of ["ФИО", "Электронная почта", "Телефон"]) {
@@ -336,7 +328,7 @@ test.describe("candidate invitations with the real backend", () => {
).not.toBeChecked();
}
await expect(candidatePage.getByRole("checkbox", { name: "Telegram" })).toHaveCount(0);
const submit = candidatePage.getByRole("button", { name: "Принять и передать контакты" });
const submit = card.getByRole("button", { name: "Принять и передать контакты" });
await expect(submit).toHaveAttribute("aria-disabled", "true");
await candidatePage
@@ -357,8 +349,11 @@ test.describe("candidate invitations with the real backend", () => {
await submit.click();
expect((await accepted).status()).toBe(200);
await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято");
await expect(grantList(candidatePage)).toHaveText(["Электронная почта"]);
const confirmation = candidatePage
.getByRole("status")
.filter({ hasText: "Приглашение принято" });
await expect(confirmation).toBeVisible();
await expect(confirmation.getByRole("listitem")).toHaveText(["Электронная почта"]);
await expectNoHorizontalOverflow(candidatePage, 360);
// The candidate's read: exactly one granted kind.
@@ -388,9 +383,7 @@ test.describe("candidate invitations with the real backend", () => {
const staleId = stale.invitationId;
const candidatePage = stale.candidate.page;
await candidatePage.setViewportSize({ width: 360, height: 900 });
await openInvitation(candidatePage, staleId, () =>
candidatePage.goto(`/candidate/invitations/${staleId}`),
);
const card = await openHomeInvitation(candidatePage, staleId, organizationName);
await candidatePage.getByRole("checkbox", { name: "Телефон", exact: true }).check();
await candidatePage
.getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ })
@@ -439,7 +432,7 @@ test.describe("candidate invitations with the real backend", () => {
});
});
await candidatePage.getByRole("button", { name: "Принять и передать контакты" }).click();
await card.getByRole("button", { name: "Принять и передать контакты" }).click();
await expect(
candidatePage.getByRole("status").filter({ hasText: "Приглашение изменилось" }),
).toBeVisible();
@@ -478,8 +471,10 @@ test.describe("candidate invitations with the real backend", () => {
await test.step("declines without a comment, keeps the decline after a reload, and discloses nothing", async () => {
const candidatePage = declining.candidate.page;
await candidatePage.setViewportSize({ width: 360, height: 900 });
await openInvitation(candidatePage, declining.invitationId, () =>
candidatePage.goto(`/candidate/invitations/${declining.invitationId}`),
const card = await openHomeInvitation(
candidatePage,
declining.invitationId,
organizationName,
);
await candidatePage.getByRole("radio", { name: "Другая причина", exact: true }).check();
// No comment is written: the neutral reason never asks for one.
@@ -490,23 +485,25 @@ test.describe("candidate invitations with the real backend", () => {
`/api/v1/me/invitations/${declining.invitationId}/decline` &&
response.status() === 200,
);
await candidatePage.getByRole("button", { name: "Отклонить приглашение" }).click();
await card.getByRole("button", { name: "Отклонить приглашение" }).click();
expect((await declined).status()).toBe(200);
await expect(candidatePage.locator('[data-state="declined"]')).toHaveText(
"Вы отклонили приглашение",
);
await expect(candidatePage.getByText("Причина: Другая причина.")).toBeVisible();
await candidatePage.reload();
await expect(candidatePage.locator('[data-state="declined"]')).toHaveText(
"Вы отклонили приглашение",
);
await expect(candidatePage.getByText("Причина: Другая причина.")).toBeVisible();
await expect(
candidatePage.getByRole("button", { name: "Отклонить приглашение" }),
).toHaveCount(0);
candidatePage.getByRole("status").filter({ hasText: "Приглашение отклонено" }),
).toBeVisible();
await expect(candidatePage).toHaveURL(/\/candidate\/?$/);
await expectNoHorizontalOverflow(candidatePage, 360);
const declinedInvitation = await api(
candidatePage,
"GET",
`/api/v1/me/invitations/${declining.invitationId}`,
);
expect(declinedInvitation.body).toMatchObject({
state: "declined",
decline: { reason: "other", comment: null },
contact_grant: null,
});
const mine = await api(
candidatePage,
"GET",
+54 -9
View File
@@ -443,30 +443,48 @@ test.describe("minimal path states with a stubbed API", () => {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/assessment-availability": () =>
failing ? problem("internal_error", 500) : { status: 200, body: { specializations: [] } },
"GET /api/v1/me/profile": {
status: 200,
body: { version: 0, confirmed_categories: [] },
},
"GET /api/v1/me/questionnaire": {
status: 200,
body: { version: 0, specializations: [], work_context: null, updated_at: null },
},
"GET /api/v1/me/assessment-results": {
status: 200,
body: { items: [], page: { has_more: false, next_cursor: null } },
},
});
await page.goto("/candidate/assessment");
await expect(page.getByRole("alert")).toContainText(
const availabilityRegion = page.getByRole("region", { name: "Доступность проверки" });
await expect(availabilityRegion.getByRole("alert")).toContainText(
"Не удалось загрузить состояние проверки",
{ timeout: 15_000 },
);
const progressAlert = page
.getByRole("alert")
.filter({ hasText: "Не удалось загрузить прогресс" });
await expect(progressAlert).toBeVisible();
await expectNoHorizontalOverflow(page, width);
failing = false;
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await tabTo(page, availabilityRegion.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Сначала выберите специализацию")).toBeVisible();
await expect(page.getByRole("link", { name: "Открыть анкету" })).toBeVisible();
await tabTo(page, progressAlert.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByRole("heading", { name: "Профиль, анкета и тест" })).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
test(`candidate profile at ${width}px: loading, an error with a retry, and access denied`, async ({
page,
}) => {
// The profile query does not retry, so the state changes only when the
// candidate presses the retry button: the second answer is a 403.
// Hold every profile read until the form's loading state is visible.
// The form retry then answers with a 403 while the journey error remains
// independently retryable.
const release = deferred<void>();
let stage: "error" | "forbidden" = "error";
await mockApi(page, {
@@ -475,17 +493,44 @@ test.describe("minimal path states with a stubbed API", () => {
await release.promise;
return stage === "error" ? problem("internal_error", 500) : problem("forbidden", 403);
},
"GET /api/v1/me/questionnaire": {
status: 200,
body: { version: 0, specializations: [], work_context: null, updated_at: null },
},
"GET /api/v1/me/assessment-availability": {
status: 200,
body: { specializations: [] },
},
"GET /api/v1/me/assessment-results": {
status: 200,
body: { items: [], page: { has_more: false, next_cursor: null } },
},
"GET /api/v1/me/privacy/preview": {
status: 200,
body: {
state: "closed",
fields: [],
card: null,
evidence: null,
generated_at: "2026-10-09T10:00:00Z",
},
},
});
await page.goto("/candidate/profile");
await expect(page.getByText("Загружаем профиль кандидата...")).toBeVisible();
await expect(page.getByText("Загружаем профиль кандидата...", { exact: true })).toBeVisible();
await expectNoHorizontalOverflow(page, width);
release.resolve();
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить профиль");
const profileAlert = page
.getByRole("alert")
.filter({ hasText: "Не удалось загрузить профиль" });
await expect(profileAlert).toContainText("Не удалось загрузить профиль");
stage = "forbidden";
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await tabTo(page, profileAlert.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Профиль недоступен")).toBeVisible();
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
const profileForbidden = page.getByRole("status").filter({ hasText: "Профиль недоступен" });
await expect(profileForbidden).toBeVisible();
await expect(profileForbidden.getByRole("button", { name: "Повторить" })).toHaveCount(0);
await expect(profileForbidden.locator("input, textarea, select")).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
}
+44
View File
@@ -0,0 +1,44 @@
import { expect, test } from "@playwright/test";
const legalPages = [
{ href: "/terms", linkName: "Условия использования", heading: "Условия использования" },
{ href: "/privacy", linkName: "Конфиденциальность", heading: "Конфиденциальность" },
] as const;
test("public footer links navigate to Terms and Privacy", async ({ page }) => {
await page.goto("/");
const footer = page.getByRole("contentinfo");
for (const legalPage of legalPages) {
await expect(
footer.getByRole("link", { name: legalPage.linkName, exact: true }),
).toHaveAttribute("href", legalPage.href);
}
for (const legalPage of legalPages) {
await footer.getByRole("link", { name: legalPage.linkName, exact: true }).click();
await expect(page.getByRole("heading", { level: 1, name: legalPage.heading })).toBeVisible();
expect(new URL(page.url()).pathname).toBe(legalPage.href);
}
});
for (const legalPage of legalPages) {
test(`public ${legalPage.href} page loads directly and after reload`, async ({ page }) => {
await page.goto(legalPage.href);
await expect(page.getByRole("heading", { level: 1, name: legalPage.heading })).toBeVisible();
expect(new URL(page.url()).pathname).toBe(legalPage.href);
const footer = page.getByRole("contentinfo");
for (const linkedPage of legalPages) {
await expect(
footer.getByRole("link", { name: linkedPage.linkName, exact: true }),
).toHaveAttribute("href", linkedPage.href);
}
await page.reload();
await expect(page.getByRole("heading", { level: 1, name: legalPage.heading })).toBeVisible();
expect(new URL(page.url()).pathname).toBe(legalPage.href);
await expect(page).not.toHaveURL(/\/login(?:\/|$)/);
});
}
@@ -0,0 +1,147 @@
import { expect, test, type Route } from "@playwright/test";
const accountId = "11111111-1111-4111-8111-111111111111";
const session = {
account: {
id: accountId,
email: "visual-candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "candidate_questionnaire",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "synthetic-csrf-token-for-visual-test",
};
const catalog = {
directions: [
{
code: "development",
title: "Разработка",
specializations: [
{
code: "backend",
title: "Backend",
test_availability: {
status: "available",
grades: ["intern", "junior", "middle"],
task_languages: ["python", "go"],
note: null,
},
},
{
code: "frontend",
title: "Frontend",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Тест по этой специализации готовится.",
},
},
{
code: "mobile",
title: "Мобильная разработка",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Тест по этой специализации готовится.",
},
},
],
},
{
code: "security",
title: "Безопасность",
specializations: [
{
code: "information_security",
title: "Информационная безопасность",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Тест по этой специализации готовится.",
},
},
],
},
],
grades: [
{ code: "intern", title: "Стажер" },
{ code: "junior", title: "Junior" },
{ code: "middle", title: "Middle" },
{ code: "senior", title: "Senior" },
],
};
const questionnaire = {
version: 0,
specializations: [],
work_context: null,
updated_at: null,
};
async function respond(route: Route, body: unknown): Promise<void> {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(body),
});
}
test("shows the populated specialization catalog on desktop and mobile", async ({
page,
}, testInfo) => {
await page.route("**/api/v1/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname === "/api/v1/identity/sessions/current") {
await respond(route, session);
return;
}
if (url.pathname === "/api/v1/me/profile") {
await respond(route, { version: 0, confirmed_categories: [] });
return;
}
if (url.pathname === "/api/v1/me/questionnaire") {
await respond(route, questionnaire);
return;
}
if (url.pathname === "/api/v1/me/assessment-availability") {
await respond(route, { specializations: [] });
return;
}
if (url.pathname === "/api/v1/me/assessment-results") {
await respond(route, { items: [], page: { has_more: false, next_cursor: null } });
return;
}
if (url.pathname === "/api/v1/specializations") {
await respond(route, catalog);
return;
}
await route.continue();
});
await page.setViewportSize({ width: 1440, height: 1100 });
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { level: 1, name: "Анкета" })).toBeVisible();
const specialization = page.getByLabel("Специализация", { exact: true });
await expect(specialization.locator("option", { hasText: "Backend" })).toHaveCount(1);
await expect(
specialization.locator("option", { hasText: "Информационная безопасность" }),
).toHaveCount(1);
await specialization.selectOption("backend");
await expect(page.getByText(/Проверка опубликована для уровней:/)).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("questionnaire-catalog-desktop.png"),
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
await expect(specialization).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("questionnaire-catalog-mobile.png"),
fullPage: true,
});
});
+8 -3
View File
@@ -111,7 +111,7 @@ async function signIn(page: Page, email: string): Promise<void> {
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Анкета" })).toBeVisible();
await expect(page.getByRole("heading", { name: "Анкета", level: 1, exact: true })).toBeVisible();
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
}
@@ -390,7 +390,9 @@ test.describe("candidate questionnaire", () => {
.getByRole("navigation", { name: "Разделы кабинета кандидата" })
.getByRole("link", { name: "Профиль" })
.click();
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await expect(
page.getByRole("heading", { name: "Профиль", level: 1, exact: true }),
).toBeVisible();
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "GET") {
await fulfillProblem(route, 401, "unauthenticated");
@@ -404,7 +406,10 @@ test.describe("candidate questionnaire", () => {
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("link", { name: "Анкета" }).click();
await page
.getByRole("navigation", { name: "Разделы профиля" })
.getByRole("link", { name: "Анкета", exact: true })
.click();
expect((await failedRead).status()).toBe(401);
await expect(page.getByText("Анкета недоступна", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
@@ -35,6 +35,18 @@ describe("demonstration stand routes", () => {
expect(production).not.toContain('href="/demo"');
});
it("shows synthetic-data notes on legal pages only on a demo stand", async () => {
const demoTerms = await renderPath("/terms", true);
const productionTerms = await renderPath("/terms", false);
const demoPrivacy = await renderPath("/privacy", true);
const productionPrivacy = await renderPath("/privacy", false);
expect(demoTerms).toContain("синтетические данные");
expect(productionTerms).not.toContain("синтетические данные");
expect(demoPrivacy).toContain("синтетические данные");
expect(productionPrivacy).not.toContain("синтетические данные");
});
it("keeps the skip link as the first link of a demo page", async () => {
const html = await renderPath("/", true);
const firstLink = html.match(/<a[^>]*>(.*?)<\/a>/);
+10 -1
View File
@@ -150,6 +150,8 @@ describe("route groups", () => {
["/register", "Регистрация", "Публичные разделы"],
["/verify-email", "Подтверждение почты", "Публичные разделы"],
["/support", "Поддержка", "Публичные разделы"],
["/terms", "Условия использования", "Публичные разделы"],
["/privacy", "Конфиденциальность", "Публичные разделы"],
["/candidate", "Главная", "Разделы кабинета кандидата"],
["/candidate/profile", "Профиль", "Разделы кабинета кандидата"],
["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"],
@@ -196,6 +198,13 @@ describe("route groups", () => {
}
});
it("links to the public terms and privacy pages from the footer", async () => {
const html = await renderHtml("/");
expect(html).toMatch(/<a[^>]*href="\/terms"[^>]*>Условия использования<\/a>/);
expect(html).toMatch(/<a[^>]*href="\/privacy"[^>]*>Конфиденциальность<\/a>/);
});
it("marks the active cabinet section with aria-current", async () => {
expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]);
// The results are a sub-section of the test: the switch segment is the
@@ -256,7 +265,7 @@ describe("product readiness", () => {
expect(html).toContain("Регистрация, вход и основные сценарии кабинетов уже работают");
expect(html).not.toContain("каркас");
expect(html).not.toContain("Пустой каркас");
expect(html).toContain("Пока не готово");
expect(html).toContain("Список доступен в кабинете работодателя");
expect(html).toMatch(/<a[^>]*href="\/login"[^>]*>Войти<\/a>/);
expect(html).toMatch(/<a[^>]*href="\/register"[^>]*>Зарегистрироваться<\/a>/);
// The API liveness check lives on the technical page, not on the landing.
+4 -1
View File
@@ -9,7 +9,8 @@ import {
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { CompanyPage } from "../../pages/company";
import { EmployerInvitationsPage } from "../../pages/employer-invitations";
import { PrivacyPage } from "../../pages/privacy";
import { PrivacyPage, PublicPrivacyPage } from "../../pages/privacy";
import { TermsPage } from "../../pages/terms";
import { SessionGate } from "../../entities/session";
import { MatchesPage } from "../../pages/matches";
import { InvitationComposePage } from "../../pages/invitation-compose";
@@ -58,6 +59,8 @@ export function createRoutes(stand: StandMode = standMode): RouteObject[] {
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
{ path: paths.support, element: <SupportRoute /> },
{ path: paths.status, element: <StatusPage /> },
{ path: paths.terms, element: <TermsPage demoStand={stand.demo} /> },
{ path: paths.privacy, element: <PublicPrivacyPage demoStand={stand.demo} /> },
...(stand.demo ? [{ path: paths.demoGuide, element: <JuryGuidePage /> }] : []),
{ path: "*", element: <NotFoundPage /> },
],
@@ -3,11 +3,19 @@ import {
allSpecializationsView,
cardsForView,
matchCardKey,
shortHandle,
specializationsInResult,
} from "./views";
import { backendHandle, matchModelFixture } from "./match.fixtures";
describe("specialization views", () => {
it("shows an LX alias while retaining the opaque backend handle", () => {
const handle = backendHandle;
expect(shortHandle(handle)).toBe("LX-AAAAAAAA");
expect(handle).toBe("cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
});
it("lists the specializations of the result in catalog order", () => {
expect(specializationsInResult(matchModelFixture().cards)).toEqual([
"backend",
+1 -1
View File
@@ -34,5 +34,5 @@ export function cardsForView(
/** Short display form of an opaque handle; the full handle is used for requests only. */
export function shortHandle(handle: string): string {
return `${handle.slice(0, 12)}...`;
return "LX-" + handle.slice(-8);
}
@@ -3,3 +3,4 @@
// chosen one by one. The page reacts to the outcome and reads the invitation again.
export { AcceptContactConsentForm } from "./ui/accept-contact-consent-form";
export { acceptDraftResetKey } from "./model/accept-draft";
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { contactConsentOffer } from "../../../entities/invitation/testing";
import type { ContactConsentOffer } from "../../../shared/api/schemas";
import {
acceptDraftResetKey,
acceptReady,
acceptanceBody,
consentParagraphs,
@@ -15,6 +17,22 @@ describe("accept draft", () => {
expect(acceptReady(emptyAcceptDraft, contactConsentOffer)).toBe(false);
});
it("resets the decision when the C4 text version or offered contacts change", () => {
const original = acceptDraftResetKey("invitation-1", 2, contactConsentOffer);
const newText = {
...contactConsentOffer,
text: { ...contactConsentOffer.text, text_version: "c4-2026-11" },
};
const newContacts: ContactConsentOffer = {
...contactConsentOffer,
available_fields: ["email", "phone"],
};
expect(acceptDraftResetKey("invitation-1", 2, newText)).not.toBe(original);
expect(acceptDraftResetKey("invitation-1", 2, newContacts)).not.toBe(original);
expect(acceptDraftResetKey("invitation-1", 3, contactConsentOffer)).not.toBe(original);
});
it("chooses each contact kind separately and keeps the contract order", () => {
let draft = toggleAcceptField(emptyAcceptDraft, "phone", true);
draft = toggleAcceptField(draft, "email", true);
@@ -16,6 +16,20 @@ export interface AcceptDraft {
export const emptyAcceptDraft: AcceptDraft = { fields: [], confirmed: false };
/** Stable React key that clears a decision whenever its terms or C4 offer changes. */
export function acceptDraftResetKey(
invitationId: string,
termsVersion: number,
offer: ContactConsentOffer,
): string {
return JSON.stringify([
invitationId,
termsVersion,
offer.text.text_version,
orderedContactKinds(offer.available_fields),
]);
}
/** Adds or removes one contact kind; the list keeps the contract order and never repeats a kind. */
export function toggleAcceptField(
draft: AcceptDraft,
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useQueryClient, type UseQueryResult } from "@tanstack/react-query";
import {
candidateHomeQueryKeys,
buildCandidateProfileUpdate,
hasPendingRepositoryChecks,
mapProfileServerErrors,
@@ -9,6 +10,7 @@ import {
type CandidateProfileDraft,
type ProfileFormIssue,
} from "../../../entities/candidate";
import { candidateViewQueryKeys } from "../../../entities/candidate-view";
import { getOnboardingDestination } from "../../../entities/session";
import { ApiRequestError } from "../../../shared/api";
import {
@@ -253,6 +255,12 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
const saved = await saveMutation.mutateAsync({ data: result.data });
if (!isSubmittingSessionCurrent()) return;
queryClient.setQueryData(getGetMyProfileQueryKey(), saved);
void queryClient.invalidateQueries({
queryKey: candidateHomeQueryKeys.profile(submittingSession.account.id),
});
void queryClient.invalidateQueries({
queryKey: candidateViewQueryKeys.preview(submittingSession.account.id),
});
setDraft(toCandidateProfileDraft(saved));
setIssues([]);
setConflict(false);
@@ -45,6 +45,7 @@ import {
type QuestionnaireDraft,
type QuestionnaireFormIssue,
} from "../model/questionnaire-form";
import { candidateHomeQueryKeys } from "../../../entities/candidate";
import { activeSessionMatches, storeQuestionnaireForActiveSession } from "../model/session-guard";
import { QuestionnaireForm } from "./questionnaire-form";
import styles from "./fill-questionnaire.module.css";
@@ -351,6 +352,12 @@ function QuestionnaireEditor({
}
return;
}
void queryClient.invalidateQueries({
queryKey: candidateHomeQueryKeys.questionnaire(actor.account.id),
});
void queryClient.invalidateQueries({
queryKey: candidateHomeQueryKeys.availability(actor.account.id),
});
setDraft(toQuestionnaireDraft(saved));
setIssues([]);
setConflict(false);
@@ -44,6 +44,7 @@ import {
useAssessmentQuestionnaire,
} from "../../../entities/assessment";
import { newIdempotencyKey } from "../../../features/answer-assessment";
import { CandidateJourneyProgress } from "../../../widgets/candidate-next-step";
import {
SignalNoticeDialog,
SignalNoticeSummary,
@@ -489,6 +490,7 @@ export function AssessmentPage() {
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide"
>
<CandidateJourneyProgress />
<div className={styles.layout}>
<Card as="section" tone="panel" labelledBy="assessment-full-title" className={styles.main}>
<header className={styles["block-header"]}>
@@ -0,0 +1,91 @@
.list {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.card {
display: grid;
gap: var(--space-3);
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.head {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: start;
justify-content: space-between;
}
.label {
margin: 0 0 var(--space-1);
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
}
.company,
.title {
margin: 0;
color: var(--color-text-strong);
font-size: var(--font-size-m);
font-weight: var(--font-weight-medium);
}
.role {
margin: 0;
font-weight: var(--font-weight-medium);
}
.facts,
.text {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.actions,
.more {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin-top: var(--space-2);
}
.details {
display: grid;
gap: var(--space-5);
padding-top: var(--space-4);
border-top: var(--line-thin) solid var(--color-divider);
}
.answer {
display: grid;
gap: var(--space-5);
}
.notice,
.outcome,
.response-notice {
margin: 0;
padding: var(--space-3);
border-radius: var(--radius-s);
background: var(--color-surface-raised);
color: var(--color-text-secondary);
line-height: var(--line-height-body);
}
.response-notice p {
margin: 0;
}
.response-notice ul {
margin: var(--space-2) 0 0;
padding-inline-start: var(--space-5);
}
@@ -0,0 +1,140 @@
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 { candidateInvitationQueryKeys } from "../../../entities/invitation";
import {
candidateAccountId,
candidateInvitationFixture,
} from "../../../entities/invitation/testing";
import { ApiRequestError } from "../../../shared/api";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type {
CandidateInvitationList,
CandidateInvitationSummary,
Session,
} from "../../../shared/api/schemas";
import { CandidateHomeInvitations } from "./candidate-home-invitations";
const switchedAccountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4001";
const staleOrganizationName = "Секретная компания старого аккаунта";
const session = {
account: {
id: candidateAccountId,
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
const staleInvitation = candidateInvitationFixture();
const staleSummary: CandidateInvitationSummary = {
id: staleInvitation.id,
organization: { ...staleInvitation.organization, name: staleOrganizationName },
state: staleInvitation.state,
expiry_reason: staleInvitation.expiry_reason,
version: staleInvitation.version,
terms_version: staleInvitation.terms_version,
role_title: staleInvitation.terms.role_title,
salary: staleInvitation.terms.salary,
work_formats: staleInvitation.terms.work_formats,
response_deadline_at: staleInvitation.response_deadline_at,
delivered_at: staleInvitation.delivered_at,
viewed_at: staleInvitation.viewed_at,
updated_at: staleInvitation.updated_at,
};
const stalePage: CandidateInvitationList = {
items: [staleSummary],
page: { has_more: false, next_cursor: null },
};
function render(queryClient: QueryClient): string {
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<CandidateHomeInvitations />
</MemoryRouter>
</QueryClientProvider>,
);
}
function seedStaleInbox(queryClient: QueryClient): void {
queryClient.setQueryData([...candidateInvitationQueryKeys.inbox(candidateAccountId), "home"], {
pages: [stalePage],
pageParams: [undefined],
});
}
describe("CandidateHomeInvitations session privacy", () => {
it("hides cached invitation details when checking the current session fails", () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, retryOnMount: false } },
});
seedStaleInbox(queryClient);
const sessionError = new ApiRequestError({
status: 503,
code: "service_unavailable",
title: "Unavailable",
});
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "error",
data: session,
dataUpdatedAt: Date.now(),
error: sessionError,
errorUpdateCount: 1,
errorUpdatedAt: Date.now(),
fetchFailureCount: 1,
fetchFailureReason: sessionError,
fetchStatus: "idle",
});
const html = render(queryClient);
expect(html).toContain("Не удалось проверить вход");
expect(html).not.toContain(staleOrganizationName);
});
it("hides cached invitation details while a session refetch is in progress", () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, retryOnMount: false } },
});
seedStaleInbox(queryClient);
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "success",
data: session,
dataUpdatedAt: Date.now(),
error: null,
errorUpdateCount: 0,
fetchStatus: "fetching",
});
const html = render(queryClient);
expect(html).toContain("Проверяем текущий вход");
expect(html).not.toContain(staleOrganizationName);
});
it("does not show the previous account inbox after the session switches", () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
seedStaleInbox(queryClient);
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
...session,
account: { ...session.account, id: switchedAccountId },
});
const html = render(queryClient);
expect(html).not.toContain(staleOrganizationName);
});
});
@@ -0,0 +1,464 @@
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useId, useRef, useState } from "react";
import {
candidateInvitationQueryKeys,
candidateStatusLabel,
contactKindLabels,
declineReasonLabels,
formatSalaryRange,
formatServerMoment,
isAnswerable,
newerInvitation,
orderedContactKinds,
readCandidateInvitation,
viewCandidateInvitation,
useServerNow,
type ResponseFailure,
listCandidateInvitations,
} from "../../../entities/invitation";
import { DeclineInvitationForm } from "../../../features/respond-invitation";
import {
acceptDraftResetKey,
AcceptContactConsentForm,
} from "../../../features/accept-contact-consent";
import {
isCurrentCandidateSession,
runForCurrentCandidate,
} from "../../../features/profile-visibility";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
CandidateInvitation,
CandidateInvitationSummary,
Session,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
Card,
EmptyState,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Section,
Skeleton,
Tag,
} from "../../../shared/ui";
import { InvitationTermsArticle } from "../../../widgets/invitation-preview";
import styles from "./candidate-home-invitations.module.css";
const staleAcceptNotice =
"Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и подтвердите выбор контактов заново.";
const privateQueryOptions = {
gcTime: 0,
staleTime: 0,
retry: false,
refetchOnMount: "always" as const,
refetchOnWindowFocus: "always" as const,
};
function InvitationAnswer({
invitation,
csrfToken,
serverNow,
notice,
onAnswered,
onFailure,
}: {
invitation: CandidateInvitation;
csrfToken: string;
serverNow: number;
notice: string | null;
onAnswered: (invitation: CandidateInvitation) => void;
onFailure: (failure: ResponseFailure) => void;
}) {
if (!isAnswerable(invitation, serverNow)) {
const decline = invitation.decline;
return (
<div className={styles.outcome} data-state={invitation.state}>
{invitation.state === "accepted" ? (
<>
<p role="status">
Вы приняли приглашение. Компания получила доступ только к контактам, отмеченным в
согласии C4.
</p>
{invitation.contact_grant ? (
<ul className={styles.granted}>
{orderedContactKinds(invitation.contact_grant.fields).map((kind) => (
<li key={kind}>{contactKindLabels[kind]}</li>
))}
</ul>
) : null}
</>
) : invitation.state === "declined" ? (
<>
<p role="status">Вы отклонили приглашение. Контакты компании не переданы.</p>
{decline ? (
<p>
Причина отказа: {declineReasonLabels[decline.reason]}.
{decline.comment ? ` Ваш комментарий: ${decline.comment}` : ""}
</p>
) : null}
</>
) : (
<p role="status">{candidateStatusLabel(invitation, serverNow)}</p>
)}
</div>
);
}
const offer = invitation.contact_consent;
return (
<div className={styles.answer}>
{notice ? (
<p className={styles.notice} role="status">
{notice}
</p>
) : null}
{offer ? (
<AcceptContactConsentForm
key={acceptDraftResetKey(invitation.id, invitation.terms_version, offer)}
invitation={invitation}
offer={offer}
organizationName={invitation.organization.name}
csrfToken={csrfToken}
onAccepted={onAnswered}
onFailure={onFailure}
/>
) : (
<Card tone="raised">
<h4 className={styles.title}>Принять приглашение нельзя</h4>
<p className={styles.text}>
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт, чтобы
принять приглашение.
</p>
<ButtonLink to={paths.candidate.profile} variant="secondary">
Открыть профиль
</ButtonLink>
</Card>
)}
<DeclineInvitationForm
key={invitation.id}
invitation={invitation}
csrfToken={csrfToken}
onDeclined={onAnswered}
onFailure={onFailure}
/>
</div>
);
}
function HomeInvitationCard({
item,
accountId,
actor,
serverNow,
onAnsweredInHome,
}: {
item: CandidateInvitationSummary;
accountId: string;
actor: Session;
serverNow: number;
onAnsweredInHome: (invitation: CandidateInvitation) => void;
}) {
const queryClient = useQueryClient();
const cardId = useId();
const [expanded, setExpanded] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
const [answeredInvitation, setAnsweredInvitation] = useState<CandidateInvitation | null>(null);
const viewedId = useRef<string | null>(null);
const detailKey = candidateInvitationQueryKeys.detail(accountId, item.id);
const detail = useQuery({
queryKey: detailKey,
queryFn: ({ signal }) =>
runForCurrentCandidate(queryClient, actor, () => readCandidateInvitation(item.id, signal)),
enabled: expanded,
...privateQueryOptions,
});
useEffect(() => {
if (
!expanded ||
detail.data?.id !== item.id ||
actor.csrf_token === "" ||
viewedId.current === item.id
) {
return;
}
viewedId.current = item.id;
void runForCurrentCandidate(queryClient, actor, () =>
viewCandidateInvitation(item.id, { csrfToken: actor.csrf_token }),
).then(
(viewed) => {
queryClient.setQueryData<CandidateInvitation>(detailKey, (current) =>
newerInvitation(current, viewed),
);
},
() => undefined,
);
}, [expanded, detail.data, item.id, actor, queryClient, detailKey]);
function handleAnswered(updated: CandidateInvitation) {
setAnsweredInvitation(updated);
onAnsweredInHome(updated);
queryClient.setQueryData<CandidateInvitation>(detailKey, (current) =>
newerInvitation(current, updated),
);
setNotice(null);
void queryClient.invalidateQueries({
queryKey: candidateInvitationQueryKeys.inbox(accountId),
});
}
function handleFailure(failure: ResponseFailure) {
if (failure.kind === "stale-terms") setNotice(staleAcceptNotice);
if (failure.kind === "csrf") {
void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() });
}
if (failure.refresh) void detail.refetch();
}
const displayedInvitation = answeredInvitation ?? item;
const answerable = isAnswerable(displayedInvitation, serverNow);
return (
<li>
<article className={styles.card}>
<header className={styles.head}>
<div>
<p className={styles.label}>Компания</p>
<h3 className={styles.company}>{item.organization.name}</h3>
</div>
<Tag tone={answerable ? "accent" : "neutral"} dot>
{candidateStatusLabel(displayedInvitation, serverNow)}
</Tag>
</header>
<p className={styles.role}>{item.role_title}</p>
<p className={styles.facts}>{formatSalaryRange(item.salary)}</p>
<p className={styles.facts}>
Срок ответа: до {formatServerMoment(item.response_deadline_at)}
</p>
<div className={styles.actions}>
<Button
variant="secondary"
aria-expanded={expanded}
aria-controls={cardId}
onClick={() => setExpanded((current) => !current)}
>
{expanded ? "Скрыть условия" : answerable ? "Ответить на приглашение" : "Показать итог"}
</Button>
</div>
{expanded ? (
<div id={cardId} className={styles.details}>
{detail.isPending ? <LoadingState label="Загружаем условия приглашения..." /> : null}
{detail.isError ? (
isAccessDenied(detail.error) ? (
<ForbiddenState error={detail.error} />
) : (
<ErrorState
error={detail.error}
isRetrying={detail.isFetching}
onRetry={() => void detail.refetch()}
title="Не удалось загрузить условия"
/>
)
) : null}
{detail.data ? (
<>
<section aria-label="Условия приглашения">
<InvitationTermsArticle
terms={detail.data.terms}
responsePeriodDays={null}
responseDeadlineAt={detail.data.response_deadline_at}
headingLevel={4}
/>
</section>
<InvitationAnswer
invitation={detail.data}
csrfToken={actor.csrf_token}
serverNow={serverNow}
notice={notice}
onAnswered={handleAnswered}
onFailure={handleFailure}
/>
</>
) : null}
</div>
) : null}
</article>
</li>
);
}
export function CandidateHomeInvitations() {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const actor = session.data;
const accountId = actor?.account.id ?? "";
const isCandidate = actor?.account.scenario === "candidate";
const sessionCanRead = Boolean(
actor &&
isCandidate &&
!session.isPending &&
!session.isFetching &&
!session.isError &&
isCurrentCandidateSession(queryClient, actor),
);
const inboxKey = [...candidateInvitationQueryKeys.inbox(accountId), "home"] as const;
const inbox = useInfiniteQuery({
queryKey: inboxKey,
queryFn: ({ pageParam, signal }) => {
if (!actor || actor.account.scenario !== "candidate") {
throw new Error("A candidate session is required.");
}
return runForCurrentCandidate(queryClient, actor, () =>
listCandidateInvitations({ cursor: pageParam, signal }),
);
},
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
enabled: sessionCanRead,
...privateQueryOptions,
});
const serverNow = useServerNow();
const items = inbox.data?.pages.flatMap((page) => page.items) ?? [];
const answerable = items.filter((item) => isAnswerable(item, serverNow));
const [responseNotice, setResponseNotice] = useState<{
accountId: string;
invitation: CandidateInvitation;
} | null>(null);
const visibleResponseNotice =
responseNotice?.accountId === accountId ? responseNotice.invitation : null;
if (session.isError) {
return (
<Section title="Приглашения">
{isAccessDenied(session.error) ? (
<ForbiddenState error={session.error} />
) : (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
)}
</Section>
);
}
if (session.isPending || session.isFetching) {
return (
<Section title="Приглашения" description="Проверяем новые предложения от компаний.">
<LoadingState label="Проверяем текущий вход..." />
</Section>
);
}
if (!actor) {
return (
<Section title="Приглашения">
<ForbiddenState
title="Приглашения недоступны"
description="Откройте кабинет кандидата и повторите проверку входа."
/>
</Section>
);
}
if (!isCandidate) return null;
if (!sessionCanRead) {
return (
<Section title="Приглашения">
<ForbiddenState
title="Приглашения недоступны"
description="Откройте кабинет кандидата и повторите проверку входа."
/>
</Section>
);
}
if (inbox.isPending) {
return (
<Section title="Приглашения" description="Проверяем новые предложения от компаний.">
<LoadingState label="Загружаем приглашения..." />
<Skeleton shape="card" lines={3} />
</Section>
);
}
if (inbox.isError) {
return (
<Section title="Приглашения">
{isAccessDenied(inbox.error) ? (
<ForbiddenState error={inbox.error} />
) : (
<ErrorState
error={inbox.error}
isRetrying={inbox.isFetching}
onRetry={() => void inbox.refetch()}
title="Не удалось загрузить приглашения"
/>
)}
</Section>
);
}
if (answerable.length === 0 && !inbox.hasNextPage && !visibleResponseNotice) return null;
return (
<Section
title="Приглашения"
description="Откройте условия здесь. Контакты передаются только после вашего отдельного выбора и подтверждения согласия C4."
>
{visibleResponseNotice ? (
<div className={styles["response-notice"]} role="status" aria-live="polite">
{visibleResponseNotice.state === "accepted" ? (
<>
<p>Приглашение принято. Компании открыты только выбранные вами контакты:</p>
<ul>
{orderedContactKinds(visibleResponseNotice.contact_grant?.fields ?? []).map(
(kind) => (
<li key={kind}>{contactKindLabels[kind]}</li>
),
)}
</ul>
</>
) : (
<p>Приглашение отклонено. Контакты компании не переданы.</p>
)}
</div>
) : null}
{answerable.length > 0 ? (
<ul className={styles.list}>
{answerable.map((item) => (
<HomeInvitationCard
key={`${accountId}:${item.id}`}
item={item}
accountId={accountId}
actor={actor}
serverNow={serverNow}
onAnsweredInHome={(invitation) => setResponseNotice({ accountId, invitation })}
/>
))}
</ul>
) : (
<EmptyState
title="Открытых приглашений пока нет"
description="Новые предложения от компаний будут появляться здесь."
/>
)}
{inbox.hasNextPage ? (
<div className={styles.more}>
<Button
variant="secondary"
isBusy={inbox.isFetchingNextPage}
onClick={() => void inbox.fetchNextPage()}
>
{inbox.isFetchingNextPage ? "Загружаем..." : "Показать еще приглашения"}
</Button>
</div>
) : null}
</Section>
);
}
@@ -19,6 +19,7 @@ import {
TextLink,
} from "../../../shared/ui";
import { CandidateNextStep } from "../../../widgets/candidate-next-step";
import { CandidateHomeInvitations } from "./candidate-home-invitations";
import styles from "./candidate-home-page.module.css";
const closedReasonText: Readonly<Record<NonNullable<VisibilitySummary["closedReason"]>, string>> = {
@@ -148,6 +149,7 @@ export function CandidateHomePage() {
lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом."
width="wide"
>
<CandidateHomeInvitations />
<CandidateNextStep />
<div className={styles.columns}>
<LatestResultSection />
@@ -1,7 +1,10 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useParams } from "react-router-dom";
import { AcceptContactConsentForm } from "../../../features/accept-contact-consent";
import {
acceptDraftResetKey,
AcceptContactConsentForm,
} from "../../../features/accept-contact-consent";
import { DeclineInvitationForm } from "../../../features/respond-invitation";
import {
candidateInvitationQueryKeys,
@@ -179,7 +182,7 @@ function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerS
<div className={styles.decisions}>
{offer ? (
<AcceptContactConsentForm
key={`${invitation.id}:${invitation.terms_version}`}
key={acceptDraftResetKey(invitation.id, invitation.terms_version, offer)}
invitation={invitation}
offer={offer}
organizationName={invitation.organization.name}
@@ -3,6 +3,22 @@
font-size: var(--font-size-l);
}
.layout {
display: grid;
gap: var(--space-5);
align-items: start;
}
.layout > * {
min-width: 0;
}
@media (width >= 64rem) {
.layout {
grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);
}
}
.steps {
display: grid;
gap: var(--space-3);
@@ -6,6 +6,9 @@ import {
buildSteps,
ButtonLink,
Card,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Mono,
Page,
@@ -13,6 +16,7 @@ import {
Stepper,
Tag,
} from "../../../shared/ui";
import { CandidateProfilePreview } from "../../../widgets/candidate-profile-preview";
import styles from "./candidate-onboarding-page.module.css";
/**
@@ -44,6 +48,17 @@ const accountSteps = [
export function CandidateOnboardingPage() {
const session = useGetCurrentSession();
if (session.isError) {
if (isAccessDenied(session.error)) return <ForbiddenState error={session.error} />;
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (!session.data) return <LoadingState label="Загружаем сохраненный шаг..." />;
const { onboarding_step: step, scenario } = session.data.account;
@@ -78,49 +93,52 @@ export function CandidateOnboardingPage() {
lead="Четыре шага до подтвержденной категории. Состояние шага хранится на сервере, поэтому его можно продолжить с любого устройства."
width="wide"
>
<Card as="section" tone="panel" labelledBy="onboarding-progress-title">
<h2 id="onboarding-progress-title" className={styles["panel-title"]}>
Шаги аккаунта
</h2>
<Stepper label="Шаги аккаунта кандидата" steps={buildSteps(accountSteps, currentIndex)} />
<ol className={styles.steps}>
{accountSteps.map((item, index) => {
const isCurrent = index === currentIndex;
return (
<li
key={item.id}
className={styles.step}
data-current={isCurrent || undefined}
aria-labelledby={`onboarding-step-${item.id}`}
>
<div className={styles["step-head"]}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono>
<h3 id={`onboarding-step-${item.id}`} className={styles["step-title"]}>
{item.label}
</h3>
{isCurrent ? (
<Tag tone="accent" dot>
сейчас
</Tag>
) : null}
</div>
<p className={styles["step-text"]}>{item.text}</p>
{isCurrent ? (
<div className={styles.action}>
<ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности
</ButtonLink>
<div className={styles.layout}>
<Card as="section" tone="panel" labelledBy="onboarding-progress-title">
<h2 id="onboarding-progress-title" className={styles["panel-title"]}>
Шаги аккаунта
</h2>
<Stepper label="Шаги аккаунта кандидата" steps={buildSteps(accountSteps, currentIndex)} />
<ol className={styles.steps}>
{accountSteps.map((item, index) => {
const isCurrent = index === currentIndex;
return (
<li
key={item.id}
className={styles.step}
data-current={isCurrent || undefined}
aria-labelledby={`onboarding-step-${item.id}`}
>
<div className={styles["step-head"]}>
<Mono>{String(index + 1).padStart(2, "0")}</Mono>
<h3 id={`onboarding-step-${item.id}`} className={styles["step-title"]}>
{item.label}
</h3>
{isCurrent ? (
<Tag tone="accent" dot>
сейчас
</Tag>
) : null}
</div>
) : null}
</li>
);
})}
</ol>
<p className={styles.note}>
Сохраненный шаг хранит сервер. Профиль, анкета и тест открываются из меню кабинета и
сохраняются независимо от него. Привязка ФСП ID и резюме для этого пути не нужны.
</p>
</Card>
<p className={styles["step-text"]}>{item.text}</p>
{isCurrent ? (
<div className={styles.action}>
<ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности
</ButtonLink>
</div>
) : null}
</li>
);
})}
</ol>
<p className={styles.note}>
Сохраненный шаг хранит сервер. Профиль, анкета и тест открываются из меню кабинета и
сохраняются независимо от него. Привязка ФСП ID и резюме для этого пути не нужны.
</p>
</Card>
<CandidateProfilePreview />
</div>
</Page>
);
}
@@ -113,7 +113,7 @@ describe("employer invitations page", () => {
expect(html).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
expect(html).toContain("Middle Go-разработчик в команду платежей");
expect(html).toContain("Черновик");
expect(html).toContain("cv1_CCCCCCCC...");
expect(html).toContain("LX-CCCCCCCC");
// The full handle is only in the link, never in the text.
expect(html.replace(/href="[^"]*"/g, "")).not.toContain(draft.candidate_handle);
expect(html).not.toContain("Экран будет реализован");
@@ -66,23 +66,6 @@
margin: 0;
}
.fact {
display: grid;
grid-template-columns: minmax(7rem, max-content) minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
min-width: 0;
}
.fact > dt {
color: var(--color-text-secondary);
}
.fact > dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.actions {
display: flex;
flex-wrap: wrap;
@@ -96,12 +79,6 @@
margin-block-start: var(--space-4);
}
@media (width < 30rem) {
.fact {
grid-template-columns: minmax(0, 1fr);
}
}
@media (width >= 64rem) {
.list {
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -101,7 +101,7 @@ describe("employer invitation list", () => {
expect(html.match(/<li[\s>]/g)).toHaveLength(1);
expect(html).toMatch(/<h2[^>]*>Приглашения компании<\/h2>/);
expect(html).toMatch(/<h3[^>]*>Роль 1<\/h3>/);
expect(html).toContain("cv1_BBBBBBBB...");
expect(html).toContain("LX-BBBBBBBB");
// The full handle is only in the link, never in the text.
expect(html.replace(/href="[^"]*"/g, "")).not.toContain(handleOf("B"));
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
@@ -6,6 +6,7 @@ import {
ButtonLink,
Card,
EmptyState,
LabelValue,
Mono,
SegmentedControl,
Section,
@@ -85,15 +86,13 @@ function InvitationCard({ item, organizationId }: InvitationCardProps) {
</div>
<dl className={styles.facts}>
{factsOf(item).map((fact) => (
<div key={fact.label} className={styles.fact}>
<dt>{fact.label}</dt>
<dd>{fact.value}</dd>
</div>
<LabelValue key={fact.label} label={fact.label} value={fact.value} />
))}
</dl>
<div className={styles.actions}>
<ButtonLink
variant={item.state === "draft" ? "primary" : "secondary"}
size="small"
to={paths.employer.invitation({
organizationId,
invitationId: item.id,
@@ -174,7 +173,7 @@ export function InvitationList({
}
action={
filter === "all" ? null : (
<Button variant="secondary" onClick={() => onFilterChange("all")}>
<Button variant="secondary" size="small" onClick={() => onFilterChange("all")}>
Показать все
</Button>
)
@@ -58,7 +58,7 @@ describe("invitation compose page", () => {
const html = render(entryPath);
expect(html).toContain("Приглашение кандидату</h1>");
expect(html).toContain("cv1_BBBB");
expect(html).toContain("LX-BBBBBBBB");
expect(html).not.toContain(handle);
expect(html).toContain("Северный ветер");
for (const label of [
+1
View File
@@ -1 +1,2 @@
export { PrivacyPage } from "./ui/privacy-page";
export { PublicPrivacyPage } from "./ui/public-privacy-page";
@@ -0,0 +1,19 @@
.details {
display: grid;
gap: var(--space-3);
margin: 0;
}
.list {
margin: 0;
padding: 0;
list-style: none;
}
.purpose-title {
color: var(--color-text-strong);
}
.purpose-copy {
margin-block-start: var(--space-2);
}
@@ -0,0 +1,68 @@
import { consentPurposeDetails, consentPurposeOrder } from "../../../entities/consent";
import { paths } from "../../../shared/config";
import { ButtonLink, LabelValue, ListRow, Page, Section, TextLink } from "../../../shared/ui";
import styles from "./public-privacy-page.module.css";
export function PublicPrivacyPage({ demoStand = false }: { demoStand?: boolean }) {
return (
<Page
title="Конфиденциальность"
eyebrow="Lincodex"
lead="Кандидат управляет публикацией карточки, статусом поиска и доступом к контактам."
>
<Section title="Управление видимостью">
<dl className={styles.details}>
<LabelValue
label="Карточка кандидата"
value="Согласие C2 разрешает публиковать карточку. Его отзыв закрывает будущие просмотры; для новой публикации требуется новое согласие."
/>
<LabelValue
label="Поиск"
value="Статус поиска управляется отдельно и влияет на доступность кандидата для поиска."
/>
<LabelValue
label="Контакты"
value="Компания получает только выбранные кандидатом поля после принятия приглашения и согласия C4."
/>
</dl>
</Section>
<Section title="Назначение согласий">
<p>
В кабинете доступны полный текст и версия каждого согласия. Назначение и последствия
отзыва:
</p>
<ul className={styles.list}>
{consentPurposeOrder.map((purpose) => {
const details = consentPurposeDetails[purpose];
return (
<ListRow key={purpose}>
<strong className={styles["purpose-title"]}>
{"C" + purpose.slice(1) + ". " + details.title}
</strong>
<p className={styles["purpose-copy"]}>{details.consequence}</p>
</ListRow>
);
})}
</ul>
<ButtonLink
to={paths.candidate.privacy + "#privacy-consents"}
variant="secondary"
size="small"
>
Открыть настройки приватности
</ButtonLink>
</Section>
{demoStand ? (
<Section title="Демонстрация">
<p>На этом стенде используются синтетические данные и подготовленные аккаунты.</p>
</Section>
) : null}
<Section title="Ваши согласия">
<p>
В настройках приватности доступны тексты, версии и состояния согласий вашего аккаунта.
</p>
<TextLink to={paths.terms}>Условия использования</TextLink>
</Section>
</Page>
);
}
@@ -0,0 +1,15 @@
.summary {
display: grid;
gap: var(--space-5);
align-items: start;
}
.summary > * {
min-width: 0;
}
@media (width >= 64rem) {
.summary {
grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr);
}
}
@@ -1,5 +1,8 @@
import { EditProfile } from "../../../features/edit-profile";
import { Page } from "../../../shared/ui";
import { CandidateJourneyProgress } from "../../../widgets/candidate-next-step";
import { CandidateProfilePreview } from "../../../widgets/candidate-profile-preview";
import styles from "./profile-page.module.css";
export function ProfilePage() {
return (
@@ -8,6 +11,10 @@ export function ProfilePage() {
lead="Управляйте своими сведениями и проверяйте, какие данные подтверждены оценкой."
width="wide"
>
<div className={styles.summary}>
<CandidateJourneyProgress />
<CandidateProfilePreview />
</div>
<EditProfile />
</Page>
);
@@ -1,5 +1,6 @@
import { FillQuestionnaire } from "../../../features/fill-questionnaire";
import { Page } from "../../../shared/ui";
import { CandidateJourneyProgress } from "../../../widgets/candidate-next-step";
export function QuestionnairePage() {
return (
@@ -8,6 +9,7 @@ export function QuestionnairePage() {
lead="Укажите специализации и условия поиска. Самооценка не становится подтвержденной категорией."
width="wide"
>
<CandidateJourneyProgress />
<FillQuestionnaire />
</Page>
);
+1
View File
@@ -0,0 +1 @@
export { TermsPage } from "./ui/terms-page";
@@ -0,0 +1,41 @@
import { paths } from "../../../shared/config";
import { ButtonLink, Notice, Page, Section, TextLink } from "../../../shared/ui";
export function TermsPage({ demoStand = false }: { demoStand?: boolean }) {
return (
<Page
title="Условия использования"
eyebrow="Lincodex"
lead="Lincodex помогает работодателям находить ИТ-специалистов по подтвержденным навыкам. Кандидаты проходят оценку и управляют карточкой; работодатели описывают потребности, ищут кандидатов и отправляют приглашения."
>
<Section title="Работа с приглашениями">
<p>
Работодатель указывает условия приглашения. Кандидат видит их версию и отдельно выбирает,
какие контактные данные предоставить этой компании.
</p>
</Section>
{demoStand ? (
<Section title="Демонстрация">
<p>
На этом стенде доступны синтетические данные и подготовленные аккаунты для знакомства с
интерфейсом. Демонстрационные категории не подтверждают точность оценки для реальных
кандидатов.
</p>
</Section>
) : null}
<Section title="Доступ к контактам">
<p>
Контакты кандидата доступны компании только после согласия на передачу выбранных данных. О
настройках видимости и назначении согласий читайте на странице{" "}
<TextLink to={paths.privacy}>конфиденциальности</TextLink>.
</p>
<ButtonLink to={paths.privacy} variant="quiet" size="small">
Конфиденциальность
</ButtonLink>
</Section>
<Notice tone="neutral" title="Юридические сведения">
Сведения об операторе и полные юридические условия еще не опубликованы.
</Notice>
</Page>
);
}
@@ -1,12 +1,3 @@
.page {
display: grid;
gap: var(--space-8);
width: 100%;
max-width: calc(var(--content-width-wide) + 2 * var(--gutter));
margin-inline: auto;
padding: var(--space-7) var(--gutter) var(--space-6);
}
/* Hero: the thesis, then the protocol trace; side by side on desktop. */
.hero {
display: grid;
@@ -210,11 +201,6 @@
}
@media (width >= 64rem) {
.page {
gap: var(--space-9);
padding-top: var(--space-8);
}
.hero {
grid-template-columns: minmax(0, 7fr) minmax(0, 5fr);
gap: var(--space-8);
@@ -1,6 +1,6 @@
import { useId } from "react";
import { paths } from "../../../shared/config";
import { ButtonLink, Tag, TextLink } from "../../../shared/ui";
import { ButtonLink, Page, Tag, TextLink } from "../../../shared/ui";
import { ProtocolTrace } from "./protocol-trace";
import styles from "./welcome-page.module.css";
@@ -50,9 +50,7 @@ export function WelcomePage({ demoStand = false }: { demoStand?: boolean }) {
const pendingId = useId();
return (
<div className={styles.page}>
<title>{`${title} - Lincodex`}</title>
<Page title={title} width="wide" hideTitle>
<section className={styles.hero} aria-labelledby={titleId}>
<div className={styles.thesis}>
<p className={styles.status}>
@@ -126,13 +124,12 @@ export function WelcomePage({ demoStand = false }: { demoStand?: boolean }) {
<section className={styles.block} aria-labelledby={pendingId}>
<h2 id={pendingId} className={styles["block-title"]}>
Пока не готово
Приглашения работодателя
</h2>
<p className={styles.pending}>
Список приглашений, отправленных компанией, пока заготовка: этот экран не показывает
данных и не выполняет действий.
Список доступен в кабинете работодателя и загружает приглашения выбранной компании.
</p>
</section>
</div>
</Page>
);
}
+2
View File
@@ -9,6 +9,8 @@ export const paths = {
verifyEmail: "/verify-email",
support: "/support",
status: "/status",
terms: "/terms",
privacy: "/privacy",
/** Jury guide of the demonstration stand; the route exists only in a demo build. */
demoGuide: "/demo",
candidate: {
@@ -23,6 +23,11 @@
transform var(--duration-fast) var(--easing-standard);
}
.small {
padding: var(--space-1) var(--space-3);
font-size: var(--font-size-s);
}
.root:active {
transform: scale(0.98);
}
+21 -3
View File
@@ -3,14 +3,25 @@ import { Link, type LinkProps } from "react-router-dom";
import styles from "./button.module.css";
export type ButtonVariant = "primary" | "secondary" | "quiet";
export type ButtonSize = "small" | "default";
function buttonClassName(variant: ButtonVariant, className: string | undefined): string {
const base = `${styles.root} ${styles[variant]}`;
return className ? `${base} ${className}` : base;
}
function sizedButtonClassName(
variant: ButtonVariant,
size: ButtonSize,
className: string | undefined,
): string {
const base = buttonClassName(variant, className);
return size === "small" ? base + " " + styles.small : base;
}
type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className"> & {
variant?: ButtonVariant;
size?: ButtonSize;
/** Marks a pending action without removing the button from the tab order. */
isBusy?: boolean;
className?: string | undefined;
@@ -23,6 +34,7 @@ type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className"> &
*/
export function Button({
variant = "primary",
size = "default",
type = "button",
isBusy = false,
className,
@@ -34,7 +46,7 @@ export function Button({
<button
{...rest}
type={type}
className={buttonClassName(variant, className)}
className={sizedButtonClassName(variant, size, className)}
aria-disabled={isBusy ? true : rest["aria-disabled"]}
aria-busy={isBusy || undefined}
onClick={(event) => {
@@ -52,10 +64,16 @@ export function Button({
type ButtonLinkProps = Omit<LinkProps, "className"> & {
variant?: ButtonVariant;
size?: ButtonSize;
className?: string | undefined;
};
/** Router link that looks like a button, for navigation calls to action. */
export function ButtonLink({ variant = "primary", className, ...rest }: ButtonLinkProps) {
return <Link {...rest} className={buttonClassName(variant, className)} />;
export function ButtonLink({
variant = "primary",
size = "default",
className,
...rest
}: ButtonLinkProps) {
return <Link {...rest} className={sizedButtonClassName(variant, size, className)} />;
}
+3 -1
View File
@@ -1,8 +1,10 @@
export { Wordmark } from "./brand/wordmark";
export { Button, ButtonLink, type ButtonVariant } from "./button/button";
export { Button, ButtonLink, type ButtonSize, type ButtonVariant } from "./button/button";
export { Card } from "./card/card";
export { CircuitTrace } from "./decor/circuit-trace";
export { HeaderPlate } from "./header-plate/header-plate";
export { LabelValue } from "./label-value/label-value";
export { ListRow } from "./list-row/list-row";
export { Page } from "./layout/page";
export { PageNavProvider } from "./layout/page-nav";
export { Section } from "./layout/section";
@@ -0,0 +1,24 @@
.root {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.label {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.value {
min-width: 0;
margin: 0;
color: var(--color-text);
overflow-wrap: anywhere;
}
@media (width >= 43.75rem) {
.root {
grid-template-columns: minmax(7rem, max-content) minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
}
}
@@ -0,0 +1,17 @@
import type { ReactNode } from "react";
import styles from "./label-value.module.css";
type LabelValueProps = {
label: ReactNode;
value: ReactNode;
};
/** One term and its description inside a description list. */
export function LabelValue({ label, value }: LabelValueProps) {
return (
<div className={styles.root}>
<dt className={styles.label}>{label}</dt>
<dd className={styles.value}>{value}</dd>
</div>
);
}
+21 -10
View File
@@ -5,8 +5,10 @@ import { usePageNav } from "./page-nav";
const productName = "Lincodex";
type PageProps = {
/** Text of the page's single h1 and of the document title. */
/** Document title and default h1. The page content owns h1 when hidden. */
title: string;
/** Hide the standard heading when the page renders its own h1 in children. */
hideTitle?: boolean;
/** Short context line above the heading, for example the cabinet name. */
eyebrow?: string | undefined;
lead?: ReactNode;
@@ -15,21 +17,30 @@ type PageProps = {
};
/**
* Page content inside a shell's main landmark. It owns the only h1 of the
* page and sets the document title (React hoists <title> into <head>). A
* secondary navigation from the shell (see PageNavProvider) sits above it.
* Page content inside a shell's main landmark. It supplies the heading unless
* hidden, sets the document title, and shows shell navigation above the body.
* When hideTitle is true, the page content must render its own h1.
*/
export function Page({ title, eyebrow, lead, width = "narrow", children }: PageProps) {
export function Page({
title,
hideTitle = false,
eyebrow,
lead,
width = "narrow",
children,
}: PageProps) {
const sectionNav = usePageNav();
return (
<div className={`${styles.page} ${styles[width]}`}>
<title>{`${title} - ${productName}`}</title>
{sectionNav ? <div className={styles["section-nav"]}>{sectionNav}</div> : null}
<header className={styles["page-header"]}>
{eyebrow ? <p className={styles.eyebrow}>{eyebrow}</p> : null}
<h1 className={styles.title}>{title}</h1>
{lead ? <div className={styles.lead}>{lead}</div> : null}
</header>
{!hideTitle || eyebrow || lead ? (
<header className={styles["page-header"]}>
{eyebrow ? <p className={styles.eyebrow}>{eyebrow}</p> : null}
{!hideTitle ? <h1 className={styles.title}>{title}</h1> : null}
{lead ? <div className={styles.lead}>{lead}</div> : null}
</header>
) : null}
{children ? <div className={styles["page-body"]}>{children}</div> : null}
</div>
);
@@ -0,0 +1,8 @@
.root {
padding-block: var(--space-3);
border-top: var(--line-thin) solid var(--color-divider);
}
.root:last-child {
border-bottom: var(--line-thin) solid var(--color-divider);
}
@@ -0,0 +1,14 @@
import type { LiHTMLAttributes } from "react";
import styles from "./list-row.module.css";
type ListRowProps = LiHTMLAttributes<HTMLLIElement>;
/** A divided row inside a semantic list. */
export function ListRow({ children, className, ...props }: ListRowProps) {
const classes = [styles.root, className].filter(Boolean).join(" ");
return (
<li {...props} className={classes}>
{children}
</li>
);
}
@@ -2,6 +2,10 @@ import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { Wordmark } from "./brand/wordmark";
import { Button, ButtonLink } from "./button/button";
import { LabelValue } from "./label-value/label-value";
import { Page } from "./layout/page";
import { ListRow } from "./list-row/list-row";
import { SegmentedControl } from "./segmented-control/segmented-control";
import { Skeleton } from "./skeleton/skeleton";
import { buildSteps } from "./stepper/build-steps";
@@ -34,6 +38,71 @@ describe("Wordmark", () => {
});
});
describe("shared layout primitives", () => {
it("keeps the document title and lets a page provide its own h1", () => {
const html = renderToStaticMarkup(
<MemoryRouter>
<Page title="Главная" hideTitle>
<h1>Свой заголовок</h1>
</Page>
</MemoryRouter>,
);
expect(html).toContain("<title>Главная - Lincodex</title>");
expect(html.match(/<h1[\s>]/g)).toHaveLength(1);
expect(html).toContain("<h1>Свой заголовок</h1>");
expect(html).not.toContain("<header");
});
it("preserves default button rendering and offers the small size for both controls", () => {
const defaultButton = renderToStaticMarkup(<Button>Продолжить</Button>);
expect(renderToStaticMarkup(<Button size="default">Продолжить</Button>)).toBe(defaultButton);
expect(renderToStaticMarkup(<Button size="small">Продолжить</Button>)).not.toBe(defaultButton);
const defaultLink = renderToStaticMarkup(
<MemoryRouter>
<ButtonLink to="/terms">Условия</ButtonLink>
</MemoryRouter>,
);
expect(
renderToStaticMarkup(
<MemoryRouter>
<ButtonLink to="/terms" size="default">
Условия
</ButtonLink>
</MemoryRouter>,
),
).toBe(defaultLink);
expect(
renderToStaticMarkup(
<MemoryRouter>
<ButtonLink to="/terms" size="small">
Условия
</ButtonLink>
</MemoryRouter>,
),
).not.toBe(defaultLink);
});
it("keeps shared row components compatible with semantic lists and descriptions", () => {
const html = renderToStaticMarkup(
<dl>
<LabelValue label="Кандидат" value="LX-AAAAAAAA" />
</dl>,
);
const list = renderToStaticMarkup(
<ul>
<ListRow>Согласие</ListRow>
</ul>,
);
expect(html).toMatch(
/<dl><div[^>]*><dt[^>]*>Кандидат<\/dt><dd[^>]*>LX-AAAAAAAA<\/dd><\/div><\/dl>/,
);
expect(list).toMatch(/<ul><li[^>]*>Согласие<\/li><\/ul>/);
});
});
describe("Stepper", () => {
const steps = [
{ id: "account", label: "Данные аккаунта" },
+1 -2
View File
@@ -1,5 +1,4 @@
/* Contrast after the tint is laid over the surface #202129 is listed in
* frontend/README.en.md; every tone stays above 4.5:1. */
/* Semantic tones use the color tokens documented in frontend/README.en.md. */
.root {
display: inline-flex;
gap: 0.375rem;
+2 -2
View File
@@ -1,8 +1,8 @@
/*
* Design tokens of the Lincodex interface: the dark graphite system from
* docs/other/design/DESIGN.md. Dark is the default and the only theme.
* frontend/README.en.md#ui-composition. Dark is the default and the only theme.
*
* Contrast rules (every pair is listed in frontend/README.en.md):
* Contrast rules:
* - Text tokens reach 4.5:1 on canvas and surface. --color-text-muted and
* --color-danger are for canvas and surface only (they drop below 4.5:1 on
* the elevated surface).
@@ -1 +1,2 @@
export { CandidateNextStep } from "./ui/candidate-next-step";
export { CandidateJourneyProgress } from "./ui/candidate-journey-progress";
@@ -0,0 +1,20 @@
.title {
margin: 0 0 var(--space-3);
color: var(--color-text-strong);
font-size: var(--font-size-l);
font-weight: var(--font-weight-medium);
}
.note {
margin: var(--space-3) 0 0;
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);
margin-top: var(--space-3);
}
@@ -0,0 +1,39 @@
import type { ReactNode } from "react";
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 { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { CandidateJourneyProgress } from "./candidate-journey-progress";
function renderWithSessionError(node: ReactNode): string {
const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } });
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "error",
error: new ApiRequestError({
status: 503,
code: "service_unavailable",
title: "Unavailable",
}),
errorUpdateCount: 1,
fetchStatus: "idle",
});
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{node}</MemoryRouter>
</QueryClientProvider>,
);
}
describe("CandidateJourneyProgress", () => {
it("reports a failed session check instead of leaving the progress spinner", () => {
const html = renderWithSessionError(<CandidateJourneyProgress />);
expect(html).toContain("Не удалось проверить вход");
expect(html).not.toContain("Загружаем прогресс профиля");
});
});
@@ -0,0 +1,93 @@
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { paths } from "../../../shared/config";
import {
buildSteps,
Card,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Stepper,
TextLink,
} from "../../../shared/ui";
import { useCandidateJourney } from "../../../entities/candidate";
import styles from "./candidate-journey-progress.module.css";
const journeySteps = [
{ id: "profile", label: "Профиль" },
{ id: "questionnaire", label: "Анкета" },
{ id: "assessment", label: "Тест" },
] as const;
export function CandidateJourneyProgress() {
const session = useGetCurrentSession();
const state = useCandidateJourney(session.data);
if (session.isError) {
if (isAccessDenied(session.error)) return <ForbiddenState error={session.error} />;
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (session.isPending) {
return <LoadingState label="Проверяем вход перед загрузкой прогресса..." />;
}
if (!session.data || session.data.account.scenario !== "candidate") {
return (
<ForbiddenState
title="Прогресс кандидата недоступен"
description="Откройте кабинет кандидата, чтобы продолжить заполнение профиля."
/>
);
}
if (state.status === "pending") {
return <LoadingState label="Загружаем прогресс профиля, анкеты и теста..." />;
}
if (state.status === "error") {
if (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />;
return (
<ErrorState
error={state.error}
isRetrying={state.isRetrying}
onRetry={state.retry}
title="Не удалось загрузить прогресс"
/>
);
}
const currentIndex =
state.journey.nextStep.kind === "profile"
? 0
: state.journey.nextStep.kind === "questionnaire"
? 1
: state.journey.nextStep.kind === "result"
? journeySteps.length
: 2;
return (
<Card as="section" tone="panel" labelledBy="candidate-journey-progress-title">
<h2 id="candidate-journey-progress-title" className={styles.title}>
Профиль, анкета и тест
</h2>
<Stepper
label="Прогресс заполнения профиля кандидата"
steps={buildSteps(journeySteps, currentIndex)}
/>
<p className={styles.note}>
{state.journey.questionnaireSaved
? "Самооценка сохранена. Подтвержденную категорию присваивает только тест."
: "Сначала сохраните профиль и анкету, затем проверьте уровень тестом."}
</p>
<div className={styles.links}>
<TextLink to={paths.candidate.profile}>Профиль</TextLink>
<TextLink to={paths.candidate.questionnaire}>Анкета</TextLink>
<TextLink to={paths.candidate.assessment}>Тест</TextLink>
</div>
</Card>
);
}
@@ -0,0 +1 @@
export { CandidateProfilePreview } from "./ui/candidate-profile-preview";
@@ -0,0 +1,3 @@
.preview {
max-width: 62rem;
}
@@ -0,0 +1,39 @@
import type { ReactNode } from "react";
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 { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { CandidateProfilePreview } from "./candidate-profile-preview";
function renderWithSessionError(node: ReactNode): string {
const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } });
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "error",
error: new ApiRequestError({
status: 503,
code: "service_unavailable",
title: "Unavailable",
}),
errorUpdateCount: 1,
fetchStatus: "idle",
});
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{node}</MemoryRouter>
</QueryClientProvider>,
);
}
describe("CandidateProfilePreview", () => {
it("reports a failed session check instead of leaving the preview spinner", () => {
const html = renderWithSessionError(<CandidateProfilePreview />);
expect(html).toContain("Не удалось проверить вход");
expect(html).not.toContain("Загружаем карточку для компаний");
});
});
@@ -0,0 +1,98 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { EmployerCardPreview, candidateViewQueryKeys } from "../../../entities/candidate-view";
import {
isCurrentCandidateSession,
runForCurrentCandidate,
} from "../../../features/profile-visibility";
import { getMyCardPreview } from "../../../shared/api/endpoints/privacy/privacy";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import {
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Section,
} from "../../../shared/ui";
import styles from "./candidate-profile-preview.module.css";
const privateQueryOptions = {
gcTime: 0,
staleTime: 0,
retry: false,
refetchOnMount: "always" as const,
refetchOnWindowFocus: "always" as const,
};
export function CandidateProfilePreview() {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const accountId = actor?.account.id ?? "no-candidate-session";
const enabled = Boolean(
actor &&
actor.account.scenario === "candidate" &&
!session.isFetching &&
!session.isError &&
isCurrentCandidateSession(queryClient, actor),
);
const preview = useQuery({
queryKey: candidateViewQueryKeys.preview(accountId),
queryFn: ({ signal }) => {
if (!actor) throw new Error("A candidate session is required.");
return runForCurrentCandidate(queryClient, actor, () => getMyCardPreview({ signal }));
},
enabled,
...privateQueryOptions,
});
if (session.isError) {
if (isAccessDenied(session.error)) return <ForbiddenState error={session.error} />;
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (session.isPending) {
return <LoadingState label="Загружаем карточку для компаний..." />;
}
if (!actor || actor.account.scenario !== "candidate" || isAccessDenied(preview.error)) {
return (
<ForbiddenState
error={session.error ?? preview.error}
title="Предпросмотр недоступен"
description="Войдите в кабинет кандидата и повторите проверку доступа."
/>
);
}
if (!enabled) {
return (
<ForbiddenState
title="Предпросмотр недоступен"
description="Сессия кандидата обновляется. Повторите проверку после обновления страницы."
/>
);
}
if (preview.isPending) {
return <LoadingState label="Загружаем карточку для компаний..." />;
}
return (
<Section
title="Так увидят компании"
description="Показана анонимная карточка по текущим настройкам публикации. Вид для каждой компании может отличаться."
>
<div className={styles.preview}>
<EmployerCardPreview
preview={preview.data}
isLoading={preview.isFetching}
error={preview.error}
onRetry={() => void preview.refetch()}
/>
</div>
</Section>
);
}
@@ -67,6 +67,12 @@
max-width: 38rem;
}
.footer-links {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-5);
}
@media (width >= 43.75rem) {
.toggle {
display: none;
@@ -19,9 +19,8 @@ const navigation = [
] as const;
/**
* Layout of public pages: the landing, sign-in, registration, email
* confirmation, and support. Below 700px the links collapse behind a menu
* button.
* Layout of public pages, including authentication, support, and legal
* information. Below 700px the links collapse behind a menu button.
*/
export function PublicShell() {
const menu = useMenuToggle();
@@ -65,7 +64,11 @@ export function PublicShell() {
Подбор в ИТ по категории, которую подтверждает тест. Контакты кандидата открываются
только с его согласия.
</p>
<TextLink to={paths.status}>Технический статус</TextLink>
<div className={styles["footer-links"]}>
<TextLink to={paths.terms}>Условия использования</TextLink>
<TextLink to={paths.privacy}>Конфиденциальность</TextLink>
<TextLink to={paths.status}>Технический статус</TextLink>
</div>
</div>
</footer>
</div>